xrpld
Loading...
Searching...
No Matches
LendingHelpers_test.cpp
1#include <xrpl/beast/unit_test/suite.h>
2// DO NOT REMOVE
3#include <test/jtx/Account.h>
4#include <test/jtx/Env.h>
5#include <test/jtx/TestHelpers.h>
6#include <test/jtx/amount.h>
7#include <test/jtx/fee.h>
8#include <test/jtx/pay.h>
9#include <test/jtx/sig.h>
10#include <test/jtx/vault.h>
11
12#include <xrpl/basics/Number.h>
13#include <xrpl/basics/chrono.h>
14#include <xrpl/ledger/helpers/LendingHelpers.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/Indexes.h>
17#include <xrpl/protocol/Issue.h>
18#include <xrpl/protocol/LedgerFormats.h>
19#include <xrpl/protocol/Protocol.h>
20#include <xrpl/protocol/SField.h>
21#include <xrpl/protocol/STAmount.h>
22#include <xrpl/protocol/STLedgerEntry.h>
23#include <xrpl/protocol/STTakesAsset.h>
24#include <xrpl/protocol/SeqProxy.h>
25#include <xrpl/protocol/TER.h>
26#include <xrpl/protocol/TxFlags.h>
27#include <xrpl/protocol/Units.h>
28
29#include <cstdint>
30#include <memory>
31#include <optional>
32#include <string>
33#include <utility>
34#include <vector>
35
36namespace xrpl::test {
37
39{
40 void
42 {
43 using namespace jtx;
44 using namespace xrpl::detail;
45 Env const env{*this};
46 auto const& rules = env.current()->rules();
47 struct TestCase
48 {
49 std::string name;
50 Number periodicRate;
51 std::uint32_t paymentsRemaining;
52 Number expectedPaymentFactor;
53 };
54
55 auto const testCases = std::vector<TestCase>{
56 {
57 .name = "Zero periodic rate",
58 .periodicRate = Number{0},
59 .paymentsRemaining = 4,
60 .expectedPaymentFactor = Number{25, -2},
61 }, // 1/4 = 0.25
62 {
63 .name = "One payment remaining",
64 .periodicRate = Number{5, -2},
65 .paymentsRemaining = 1,
66 .expectedPaymentFactor = Number{105, -2},
67 }, // 0.05/1 = 1.05
68 {
69 .name = "Multiple payments remaining",
70 .periodicRate = Number{5, -2},
71 .paymentsRemaining = 3,
72 .expectedPaymentFactor = Number{3672085646312450436, -19},
73 }, // from calc
74 {
75 .name = "Zero payments remaining",
76 .periodicRate = Number{5, -2},
77 .paymentsRemaining = 0,
78 .expectedPaymentFactor = Number{0},
79 }, // edge case
80 };
81
82 for (auto const& tc : testCases)
83 {
84 testcase("computePaymentFactor: " + tc.name);
85
86 auto const computedPaymentFactor =
87 computePaymentFactor(rules, tc.periodicRate, tc.paymentsRemaining);
88 BEAST_EXPECTS(
89 computedPaymentFactor == tc.expectedPaymentFactor,
90 "Payment factor mismatch: expected " + to_string(tc.expectedPaymentFactor) +
91 ", got " + to_string(computedPaymentFactor));
92 }
93 }
94
95 void
97 {
98 using namespace jtx;
99 using namespace xrpl::detail;
100 Env const env{*this};
101 auto const& rules = env.current()->rules();
102
103 struct TestCase
104 {
105 std::string name;
106 Number principalOutstanding;
107 Number periodicRate;
108 std::uint32_t paymentsRemaining;
109 Number expectedPeriodicPayment;
110 };
111
112 auto const testCases = std::vector<TestCase>{
113 {
114 .name = "Zero principal outstanding",
115 .principalOutstanding = Number{0},
116 .periodicRate = Number{5, -2},
117 .paymentsRemaining = 5,
118 .expectedPeriodicPayment = Number{0},
119 },
120 {
121 .name = "Zero payments remaining",
122 .principalOutstanding = Number{1'000},
123 .periodicRate = Number{5, -2},
124 .paymentsRemaining = 0,
125 .expectedPeriodicPayment = Number{0},
126 },
127 {
128 .name = "Zero periodic rate",
129 .principalOutstanding = Number{1'000},
130 .periodicRate = Number{0},
131 .paymentsRemaining = 4,
132 .expectedPeriodicPayment = Number{250},
133 },
134 {
135 .name = "Standard case",
136 .principalOutstanding = Number{1'000},
137 .periodicRate = loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60),
138 .paymentsRemaining = 3,
139 .expectedPeriodicPayment = Number{389569066396123265, -15}, // from calc
140 },
141 };
142
143 for (auto const& tc : testCases)
144 {
145 testcase("loanPeriodicPayment: " + tc.name);
146
147 auto const computedPeriodicPayment = loanPeriodicPayment(
148 rules, tc.principalOutstanding, tc.periodicRate, tc.paymentsRemaining);
149 BEAST_EXPECTS(
150 computedPeriodicPayment == tc.expectedPeriodicPayment,
151 "Periodic payment mismatch: expected " + to_string(tc.expectedPeriodicPayment) +
152 ", got " + to_string(computedPeriodicPayment));
153 }
154 }
155
156 void
158 {
159 using namespace jtx;
160 using namespace xrpl::detail;
161 Env const env{*this};
162 auto const& rules = env.current()->rules();
163
164 struct TestCase
165 {
166 std::string name;
167 Number periodicPayment;
168 Number periodicRate;
169 std::uint32_t paymentsRemaining;
170 Number expectedPrincipalOutstanding;
171 };
172
173 auto const testCases = std::vector<TestCase>{
174 {
175 .name = "Zero periodic payment",
176 .periodicPayment = Number{0},
177 .periodicRate = Number{5, -2},
178 .paymentsRemaining = 5,
179 .expectedPrincipalOutstanding = Number{0},
180 },
181 {
182 .name = "Zero payments remaining",
183 .periodicPayment = Number{1'000},
184 .periodicRate = Number{5, -2},
185 .paymentsRemaining = 0,
186 .expectedPrincipalOutstanding = Number{0},
187 },
188 {
189 .name = "Zero periodic rate",
190 .periodicPayment = Number{250},
191 .periodicRate = Number{0},
192 .paymentsRemaining = 4,
193 .expectedPrincipalOutstanding = Number{1'000},
194 },
195 {
196 .name = "Standard case",
197 .periodicPayment = Number{389569066396123265, -15}, // from calc
198 .periodicRate = loanPeriodicRate(TenthBips32(100'000), 30 * 24 * 60 * 60),
199 .paymentsRemaining = 3,
200 .expectedPrincipalOutstanding = Number{1'000},
201 },
202 };
203
204 for (auto const& tc : testCases)
205 {
206 testcase("loanPrincipalFromPeriodicPayment: " + tc.name);
207
208 auto const computedPrincipalOutstanding = loanPrincipalFromPeriodicPayment(
209 rules, tc.periodicPayment, tc.periodicRate, tc.paymentsRemaining);
210 BEAST_EXPECTS(
211 computedPrincipalOutstanding == tc.expectedPrincipalOutstanding,
212 "Principal outstanding mismatch: expected " +
213 to_string(tc.expectedPrincipalOutstanding) + ", got " +
214 to_string(computedPrincipalOutstanding));
215 }
216 }
217
218 void
220 {
221 using namespace jtx;
222 using namespace xrpl::detail;
223
224 // Edge cases.
225 {
226 testcase("computePowerMinusOne: zero rate returns zero");
227 BEAST_EXPECT(computePowerMinusOne(0, 5) == 0);
228 }
229 {
230 testcase("computePowerMinusOne: zero paymentsRemaining returns zero");
231 Number const fivePercent{5, -2};
232 BEAST_EXPECT(computePowerMinusOne(fivePercent, 0) == 0);
233 }
234 // (1.05)^3 - 1 = 0.157625, computed independently by hand.
235 {
236 testcase("computePowerMinusOne: standard case (1.05)^3 - 1 = 0.157625");
237 Number const r{5, -2};
238 Number const expected{157625, -6};
239 BEAST_EXPECT(computePowerMinusOne(r, 3) == expected);
240 }
241 // (1+1)^1 - 1 = 1.
242 {
243 testcase("computePowerMinusOne: r=1, n=1");
244 BEAST_EXPECT(computePowerMinusOne(1, 1) == 1);
245 }
246
247 // Property check at near-zero rate (the bug regime): for n=2 the
248 // mathematical identity is `(1+r)^2 - 1 = 2r + r^2`. We compute
249 // `2r + r^2` by direct multiplication in Number arithmetic — a
250 // path that doesn't share any code with the binomial loop — and
251 // assert the two paths agree.
252 {
253 testcase("computePowerMinusOne: near-zero rate matches independent 2r + r^2");
254 // r = 1 TenthBips32 over 600s payment interval, computed
255 // independently below using xrpl::detail::loanPeriodicRate.
256 Number const r = loanPeriodicRate(TenthBips32{1}, 600);
257 Number const independentExpected = 2 * r + r * r; // (1+r)^2 - 1
258 BEAST_EXPECT(computePowerMinusOne(r, 2) == independentExpected);
259 }
260 // Same property at n=3: (1+r)^3 - 1 = 3r + 3r^2 + r^3.
261 {
262 testcase("computePowerMinusOne: near-zero rate matches independent 3r + 3r^2 + r^3");
263 Number const r = loanPeriodicRate(TenthBips32{1}, 600);
264 Number const independentExpected = 3 * r + 3 * r * r + r * r * r;
265 BEAST_EXPECT(computePowerMinusOne(r, 3) == independentExpected);
266 }
267
268 // Larger-n stress test for the loop's early-termination logic.
269 // At very small r the binomial terms decrease by a factor of
270 // ~r*(n-k)/(k+1) per step, so even at n=1000 the loop should
271 // terminate in a small handful of iterations. Cross-check the
272 // result against the hybrid (which dispatches to this same
273 // binomial path when r*n < 1e-9).
274 {
275 testcase("computePowerMinusOne: large n, early termination matches hybrid output");
276 // r*n = 1e-10 and 1e-12 — both clearly below the 1e-9 threshold.
277 Number const r1{1, -13};
278 std::uint32_t const n1 = 1'000;
279 Number const r2{1, -15};
280 std::uint32_t const n2 = 1'000;
281 BEAST_EXPECT(computePowerMinusOne(r1, n1) == computePowerMinusOneHybrid(r1, n1));
282 BEAST_EXPECT(computePowerMinusOne(r2, n2) == computePowerMinusOneHybrid(r2, n2));
283 BEAST_EXPECT(computePowerMinusOne(r1, n1) > 0);
284 BEAST_EXPECT(computePowerMinusOne(r2, n2) > 0);
285 }
286 }
287
288 // Direct tests of `computePowerMinusOneHybrid`. Verifies the dispatcher
289 // picks the right branch and produces the right result on each side
290 // of the threshold.
291 void
293 {
294 using namespace jtx;
295 using namespace xrpl::detail;
296
297 // Above threshold (r * n >= 1e-9): hybrid must agree with the closed
298 // form `power(1+r, n) - 1` exactly (it is the closed form).
299 {
300 testcase("computePowerMinusOneHybrid: r*n >= 1e-9 uses closed form (bit-exact match)");
301
302 struct AboveThreshold
303 {
304 std::string name;
305 Number r;
307 };
308 auto const cases = std::vector<AboveThreshold>{
309 {.name = "r=5%, n=3", .r = Number{5, -2}, .n = 3},
310 {.name = "r=0.1%, n=1000", .r = Number{1, -3}, .n = 1'000},
311 {.name = "r=1e-7, n=100 (above threshold by 10x)", .r = Number{1, -7}, .n = 100},
312 };
313 for (auto const& tc : cases)
314 {
315 Number const closed = power(1 + tc.r, tc.n) - 1;
316 Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n);
317 BEAST_EXPECTS(
318 hybrid == closed,
319 tc.name + ": closed=" + to_string(closed) + ", hybrid=" + to_string(hybrid));
320 }
321 }
322
323 // Below threshold (r * n < 1e-9): hybrid must agree with
324 // `computePowerMinusOne` (the binomial expansion). At this regime
325 // the closed form is provably wrong (cancellation); we verify the
326 // dispatcher routes to the binomial path.
327 {
328 testcase(
329 "computePowerMinusOneHybrid: r*n < 1e-9 uses binomial expansion (bit-exact match)");
330
331 struct BelowThreshold
332 {
333 std::string name;
334 Number r;
336 };
337 auto const cases = std::vector<BelowThreshold>{
338 // bug regime: r = 1 TenthBips32 over 600s payment interval
339 // → r ≈ 1.9e-10, r*n ≈ 3.8e-10 < 1e-9.
340 {
341 .name = "bug regime: r~1.9e-10, n=2",
342 .r = loanPeriodicRate(TenthBips32{1}, 600),
343 .n = 2,
344 },
345 {.name = "r=1e-12, n=100", .r = Number{1, -12}, .n = 100},
346 };
347 for (auto const& tc : cases)
348 {
349 Number const binom = computePowerMinusOne(tc.r, tc.n);
350 Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n);
351 BEAST_EXPECTS(
352 hybrid == binom,
353 tc.name + ": binom=" + to_string(binom) + ", hybrid=" + to_string(hybrid));
354 }
355 }
356
357 // Edge cases.
358 {
359 testcase("computePowerMinusOneHybrid: edge cases");
360 Number const fivePercent{5, -2};
361 BEAST_EXPECT(computePowerMinusOneHybrid(0, 100) == 0);
362 BEAST_EXPECT(computePowerMinusOneHybrid(fivePercent, 0) == 0);
363 BEAST_EXPECT(computePowerMinusOneHybrid(0, 0) == 0);
364 }
365
366 // Threshold boundary: r*n = 1e-9 exactly. Hybrid uses `>=` against
367 // the threshold, so this case must take the closed-form branch.
368 // We also verify that the binomial path agrees with the closed
369 // form to high precision at this crossover — confirming the
370 // threshold is placed where both paths give "adequate" answers.
371 {
372 testcase("computePowerMinusOneHybrid: threshold boundary r*n = 1e-9");
373
374 // Construct exactly r*n = 1e-9 with two distinct (r, n) pairs.
375 struct Boundary
376 {
377 std::string name;
378 Number r;
380 };
381 auto const cases = std::vector<Boundary>{
382 {.name = "r=1e-9, n=1", .r = Number{1, -9}, .n = 1},
383 {.name = "r=1e-12, n=1000", .r = Number{1, -12}, .n = 1'000},
384 };
385
386 for (auto const& tc : cases)
387 {
388 Number const closed = power(1 + tc.r, tc.n) - 1;
389 Number const hybrid = computePowerMinusOneHybrid(tc.r, tc.n);
390 Number const binom = computePowerMinusOne(tc.r, tc.n);
391
392 // At exact threshold, hybrid must take closed-form path:
393 // bit-exact match with closed.
394 BEAST_EXPECTS(
395 hybrid == closed,
396 tc.name + ": hybrid should equal closed at threshold; got hybrid=" +
397 to_string(hybrid) + ", closed=" + to_string(closed));
398
399 // Closed-form and binomial must agree at the threshold to
400 // within Number's post-subtraction precision (~10 sig
401 // digits of `r*n = 1e-9`, i.e. ~1e-19 absolute error).
402 Number const tolerance{1, -18};
403 Number const diff = abs(closed - binom);
404 BEAST_EXPECTS(
405 diff < tolerance,
406 tc.name + ": closed and binomial diverge at threshold by " + to_string(diff));
407 }
408 }
409 }
410
411 // Regression: at near-zero rate, `loanPrincipalFromPeriodicPayment`
412 // must satisfy `principal <= periodicPayment * paymentsRemaining` for
413 // any non-negative rate. The naive closed-form path violated this
414 // bound due to catastrophic cancellation in `(1+r)^n - 1`.
415 void
417 {
418 testcase("loanPrincipalFromPeriodicPayment: principal <= payment*n at near-zero rate");
419 using namespace jtx;
420 using namespace xrpl::detail;
421 Env const env{*this};
422 auto const& rules = env.current()->rules();
423
424 // Inputs from the near-zero-rate LoanPay bug reproduction:
425 // InterestRate = 1 TenthBips32 (0.001 % per year),
426 // PaymentInterval = 600 s, principal = 100, 3 payments.
427 // periodicRate is ~1.9e-10.
428 auto const periodicRate = loanPeriodicRate(TenthBips32{1}, 600);
429 auto const periodicPayment = loanPeriodicPayment(rules, 100, periodicRate, 3);
430
431 for (auto const n : {3u, 2u, 1u})
432 {
433 auto const computed =
434 loanPrincipalFromPeriodicPayment(rules, periodicPayment, periodicRate, n);
435 auto const upperBound = periodicPayment * Number{n};
436 BEAST_EXPECTS(
437 computed <= upperBound,
438 "n=" + std::to_string(n) + ": payment*n=" + to_string(upperBound) +
439 ", principal=" + to_string(computed));
440 }
441 }
442
443 // Regression: `computeTheoreticalLoanState` must produce a non-negative
444 // `interestDue` for any non-negative rate. Pre-fix, near-zero rates
445 // produced a negative `interestDue` because `(1+r)^n - 1` lost most of
446 // its precision to cancellation.
447 void
449 {
450 testcase("computeTheoreticalLoanState: non-negative interestDue at near-zero rate");
451 using namespace jtx;
452 using namespace xrpl::detail;
453 Env const env{*this};
454 auto const& rules = env.current()->rules();
455
456 auto const periodicRate = loanPeriodicRate(TenthBips32{1}, 600);
457 auto const periodicPayment = loanPeriodicPayment(rules, 100, periodicRate, 3);
458
459 auto const state =
460 computeTheoreticalLoanState(rules, periodicPayment, periodicRate, 2, TenthBips32{0});
461
462 BEAST_EXPECT(state.principalOutstanding <= state.valueOutstanding);
463 BEAST_EXPECT(state.interestDue >= 0);
464 BEAST_EXPECT(state.managementFeeDue == 0);
465 }
466
467 // Direct gating proof: at near-zero rate, `computePaymentFactor` must
468 // return different values with `fixCleanup3_2_0` disabled vs enabled.
469 // The enabled path agrees with an independent polynomial reference;
470 // the disabled path diverges by a measurable amount due to the
471 // catastrophic cancellation in `(1+r)^n - 1`.
472 void
474 {
475 testcase("computePaymentFactor: near-zero rate, amendment disabled vs enabled");
476 using namespace jtx;
477 using namespace xrpl::detail;
478
479 Number const r = loanPeriodicRate(TenthBips32{1}, 600);
480 std::uint32_t const n = 3;
481
482 // Independent reference: expand F(r,3) = r*(1+r)^3/((1+r)^3-1)
483 // algebraically for n=3, dividing numerator and denominator by r:
484 // F(r,3) = (1 + 3r + 3r^2 + r^3) / (3 + 3r + r^2)
485 // No power(), no binomial series — pure polynomial arithmetic in
486 // Number.
487 Number const reference = (1 + 3 * r + 3 * r * r + r * r * r) / (3 + 3 * r + r * r);
488
489 // Pre-fix: closed form power(1+r, n) - 1 suffers catastrophic
490 // cancellation when r*n ~ 5.7e-10.
491 Env const envBug{*this, testableAmendments() - fixCleanup3_2_0};
492 Number const buggyFactor = computePaymentFactor(envBug.current()->rules(), r, n);
493
494 // Post-fix: hybrid binomial path avoids cancellation.
495 Env const envFix{*this};
496 Number const correctFactor = computePaymentFactor(envFix.current()->rules(), r, n);
497
498 // The amendment must change the computed factor in this regime.
499 BEAST_EXPECT(buggyFactor != correctFactor);
500
501 // The fixed factor must agree with the polynomial reference to
502 // within a few ULPs of Number's 19-digit precision.
503 BEAST_EXPECT(abs(correctFactor - reference) < Number(1, -15));
504
505 // The buggy factor must diverge from the reference by a measurable
506 // amount — empirically ~1e-10 in this regime.
507 BEAST_EXPECT(abs(buggyFactor - reference) > Number(1, -12));
508 }
509
510 void
512 {
513 testcase("computeOverpaymentComponents");
514 using namespace jtx;
515 using namespace xrpl::detail;
516
517 Account const issuer{"issuer"};
518 PrettyAsset const iou = issuer["IOU"];
519 int32_t const loanScale = 1;
520 auto const overpayment = Number{1'000};
521 auto const overpaymentInterestRate = TenthBips32{10'000}; // 10%
522 auto const overpaymentFeeRate = TenthBips32{50'000}; // 50%
523 auto const managementFeeRate = TenthBips16{10'000}; // 10%
524
525 auto const expectedOverpaymentFee = Number{500}; // 50% of 1,000
526 auto const expectedOverpaymentInterestGross = Number{100}; // 10% of 1,000
527 auto const expectedOverpaymentInterestNet = Number{90}; // 100 - 10% of 100
528 auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100
529 auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500
530
531 Env const env{*this};
532 auto const components = xrpl::detail::computeOverpaymentComponents(
533 env.current()->rules(),
534 iou,
535 loanScale,
536 overpayment,
537 overpaymentInterestRate,
538 overpaymentFeeRate,
539 managementFeeRate);
540
541 BEAST_EXPECT(components.untrackedManagementFee == expectedOverpaymentFee);
542
543 BEAST_EXPECT(components.untrackedInterest == expectedOverpaymentInterestNet);
544
545 BEAST_EXPECT(components.trackedInterestPart() == expectedOverpaymentInterestNet);
546
547 BEAST_EXPECT(components.trackedManagementFeeDelta == expectedOverpaymentManagementFee);
548 BEAST_EXPECT(components.trackedPrincipalDelta == expectedPrincipalPortion);
549 BEAST_EXPECT(
550 components.trackedManagementFeeDelta + components.untrackedInterest ==
551 expectedOverpaymentInterestGross);
552
553 BEAST_EXPECT(
554 components.trackedManagementFeeDelta + components.untrackedInterest +
555 components.trackedPrincipalDelta + components.untrackedManagementFee ==
556 overpayment);
557 }
558
559 void
561 {
562 using namespace jtx;
563 using namespace xrpl::detail;
564
565 struct TestCase
566 {
567 std::string name;
568 Number interest;
569 TenthBips16 managementFeeRate;
570 Number expectedInterestPart;
571 Number expectedFeePart;
572 };
573
574 Account const issuer{"issuer"};
575 PrettyAsset const iou = issuer["IOU"];
576 std::int32_t const loanScale = 1;
577
578 auto const testCases = std::vector<TestCase>{
579 {
580 .name = "Zero interest",
581 .interest = Number{0},
582 .managementFeeRate = TenthBips16{10'000},
583 .expectedInterestPart = Number{0},
584 .expectedFeePart = Number{0},
585 },
586 {
587 .name = "Zero fee rate",
588 .interest = Number{1'000},
589 .managementFeeRate = TenthBips16{0},
590 .expectedInterestPart = Number{1'000},
591 .expectedFeePart = Number{0},
592 },
593 {
594 .name = "10% fee rate",
595 .interest = Number{1'000},
596 .managementFeeRate = TenthBips16{10'000},
597 .expectedInterestPart = Number{900},
598 .expectedFeePart = Number{100},
599 },
600 };
601
602 for (auto const& tc : testCases)
603 {
604 testcase("computeInterestAndFeeParts: " + tc.name);
605
606 auto const [computedInterestPart, computedFeePart] =
607 computeInterestAndFeeParts(iou, tc.interest, tc.managementFeeRate, loanScale);
608 BEAST_EXPECTS(
609 computedInterestPart == tc.expectedInterestPart,
610 "Interest part mismatch: expected " + to_string(tc.expectedInterestPart) +
611 ", got " + to_string(computedInterestPart));
612 BEAST_EXPECTS(
613 computedFeePart == tc.expectedFeePart,
614 "Fee part mismatch: expected " + to_string(tc.expectedFeePart) + ", got " +
615 to_string(computedFeePart));
616 }
617 }
618
619 void
621 {
622 using namespace jtx;
623 using namespace xrpl::detail;
624 struct TestCase
625 {
626 std::string name;
627 Number principalOutstanding;
628 TenthBips32 lateInterestRate;
629 NetClock::time_point parentCloseTime;
630 std::uint32_t nextPaymentDueDate;
631 Number expectedLateInterest;
632 };
633
634 auto const testCases = std::vector<TestCase>{
635 {
636 .name = "On-time payment",
637 .principalOutstanding = Number{1'000},
638 .lateInterestRate = TenthBips32{10'000}, // 10%
639 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
640 .nextPaymentDueDate = 3'000,
641 .expectedLateInterest = Number{0},
642 },
643 {
644 .name = "Early payment",
645 .principalOutstanding = Number{1'000},
646 .lateInterestRate = TenthBips32{10'000}, // 10%
647 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
648 .nextPaymentDueDate = 4'000,
649 .expectedLateInterest = Number{0},
650 },
651 {
652 .name = "No principal outstanding",
653 .principalOutstanding = Number{0},
654 .lateInterestRate = TenthBips32{10'000}, // 10%
655 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
656 .nextPaymentDueDate = 2'000,
657 .expectedLateInterest = Number{0},
658 },
659 {
660 .name = "No late interest rate",
661 .principalOutstanding = Number{1'000},
662 .lateInterestRate = TenthBips32{0}, // 0%
663 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
664 .nextPaymentDueDate = 2'000,
665 .expectedLateInterest = Number{0},
666 },
667 {
668 .name = "Late payment",
669 .principalOutstanding = Number{1'000},
670 .lateInterestRate = TenthBips32{100'000}, // 100%
671 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
672 .nextPaymentDueDate = 2'000,
673 .expectedLateInterest = Number{317097919837645865, -19}, // from calc
674 },
675 };
676
677 for (auto const& tc : testCases)
678 {
679 testcase("loanLatePaymentInterest: " + tc.name);
680
681 auto const computedLateInterest = loanLatePaymentInterest(
682 tc.principalOutstanding,
683 tc.lateInterestRate,
684 tc.parentCloseTime,
685 tc.nextPaymentDueDate);
686 BEAST_EXPECTS(
687 computedLateInterest == tc.expectedLateInterest,
688 "Late interest mismatch: expected " + to_string(tc.expectedLateInterest) +
689 ", got " + to_string(computedLateInterest));
690 }
691 }
692
693 void
695 {
696 using namespace jtx;
697 using namespace xrpl::detail;
698 struct TestCase
699 {
700 std::string name;
701 Number principalOutstanding;
702 Number periodicRate;
703 NetClock::time_point parentCloseTime;
704 std::uint32_t startDate;
705 std::uint32_t prevPaymentDate;
706 std::uint32_t paymentInterval;
707 Number expectedAccruedInterest;
708 };
709
710 auto const testCases = std::vector<TestCase>{
711 {
712 .name = "Zero principal outstanding",
713 .principalOutstanding = Number{0},
714 .periodicRate = Number{5, -2},
715 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
716 .startDate = 2'000,
717 .prevPaymentDate = 2'500,
718 .paymentInterval = 30 * 24 * 60 * 60,
719 .expectedAccruedInterest = Number{0},
720 },
721 {
722 .name = "Before start date",
723 .principalOutstanding = Number{1'000},
724 .periodicRate = Number{5, -2},
725 .parentCloseTime = NetClock::time_point{NetClock::duration{1'000}},
726 .startDate = 2'000,
727 .prevPaymentDate = 1'500,
728 .paymentInterval = 30 * 24 * 60 * 60,
729 .expectedAccruedInterest = Number{0},
730 },
731 {
732 .name = "Zero periodic rate",
733 .principalOutstanding = Number{1'000},
734 .periodicRate = Number{0},
735 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
736 .startDate = 2'000,
737 .prevPaymentDate = 2'500,
738 .paymentInterval = 30 * 24 * 60 * 60,
739 .expectedAccruedInterest = Number{0},
740 },
741 {
742 .name = "Zero payment interval",
743 .principalOutstanding = Number{1'000},
744 .periodicRate = Number{5, -2},
745 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
746 .startDate = 2'000,
747 .prevPaymentDate = 2'500,
748 .paymentInterval = 0,
749 .expectedAccruedInterest = Number{0},
750 },
751 {
752 .name = "Standard case",
753 .principalOutstanding = Number{1'000},
754 .periodicRate = Number{5, -2},
755 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
756 .startDate = 1'000,
757 .prevPaymentDate = 2'000,
758 .paymentInterval = 30 * 24 * 60 * 60,
759 .expectedAccruedInterest = Number{1929012345679012346, -20}, // from calc
760 },
761 };
762
763 for (auto const& tc : testCases)
764 {
765 testcase("loanAccruedInterest: " + tc.name);
766
767 auto const computedAccruedInterest = loanAccruedInterest(
768 tc.principalOutstanding,
769 tc.periodicRate,
770 tc.parentCloseTime,
771 tc.startDate,
772 tc.prevPaymentDate,
773 tc.paymentInterval);
774 BEAST_EXPECTS(
775 computedAccruedInterest == tc.expectedAccruedInterest,
776 "Accrued interest mismatch: expected " + to_string(tc.expectedAccruedInterest) +
777 ", got " + to_string(computedAccruedInterest));
778 }
779 }
780
781 // This test overlaps with testLoanAccruedInterest, the test cases only
782 // exercise the computeFullPaymentInterest parts unique to it.
783 void
785 {
786 using namespace jtx;
787 using namespace xrpl::detail;
788
789 struct TestCase
790 {
791 std::string name;
792 Number rawPrincipalOutstanding;
793 Number periodicRate;
794 NetClock::time_point parentCloseTime;
795 std::uint32_t paymentInterval;
796 std::uint32_t prevPaymentDate;
797 std::uint32_t startDate;
798 TenthBips32 closeInterestRate;
799 Number expectedFullPaymentInterest;
800 };
801
802 auto const testCases = std::vector<TestCase>{
803 {
804 .name = "Zero principal outstanding",
805 .rawPrincipalOutstanding = Number{0},
806 .periodicRate = Number{5, -2},
807 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
808 .paymentInterval = 30 * 24 * 60 * 60,
809 .prevPaymentDate = 2'000,
810 .startDate = 1'000,
811 .closeInterestRate = TenthBips32{10'000},
812 .expectedFullPaymentInterest = Number{0},
813 },
814 {
815 .name = "Zero close interest rate",
816 .rawPrincipalOutstanding = Number{1'000},
817 .periodicRate = Number{5, -2},
818 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
819 .paymentInterval = 30 * 24 * 60 * 60,
820 .prevPaymentDate = 2'000,
821 .startDate = 1'000,
822 .closeInterestRate = TenthBips32{0},
823 .expectedFullPaymentInterest = Number{1929012345679012346, -20}, // from calc
824 },
825 {
826 .name = "Standard case",
827 .rawPrincipalOutstanding = Number{1'000},
828 .periodicRate = Number{5, -2},
829 .parentCloseTime = NetClock::time_point{NetClock::duration{3'000}},
830 .paymentInterval = 30 * 24 * 60 * 60,
831 .prevPaymentDate = 2'000,
832 .startDate = 1'000,
833 .closeInterestRate = TenthBips32{10'000},
834 .expectedFullPaymentInterest = Number{1000192901234567901, -16}, // from calc
835 },
836 };
837
838 for (auto const& tc : testCases)
839 {
840 testcase("computeFullPaymentInterest: " + tc.name);
841
842 auto const computedFullPaymentInterest = computeFullPaymentInterest(
843 tc.rawPrincipalOutstanding,
844 tc.periodicRate,
845 tc.parentCloseTime,
846 tc.paymentInterval,
847 tc.prevPaymentDate,
848 tc.startDate,
849 tc.closeInterestRate);
850 BEAST_EXPECTS(
851 computedFullPaymentInterest == tc.expectedFullPaymentInterest,
852 "Full payment interest mismatch: expected " +
853 to_string(tc.expectedFullPaymentInterest) + ", got " +
854 to_string(computedFullPaymentInterest));
855 }
856 }
857
858 void
860 {
861 // This test ensures that overpayment with no interest works correctly.
862 testcase("tryOverpayment - No Interest No Fee");
863
864 using namespace jtx;
865 using namespace xrpl::detail;
866
867 Env const env{*this};
868 Account const issuer{"issuer"};
869 PrettyAsset const asset = issuer["USD"];
870 std::int32_t const loanScale = -5;
871 TenthBips16 const managementFeeRate{0}; // 0%
872 TenthBips32 const loanInterestRate{0}; // 0%
873 Number const loanPrincipal{1'000};
874 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
875 std::uint32_t const paymentsRemaining = 10;
876 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
877 Number const overpaymentAmount{50};
878
879 auto const overpaymentComponents = computeOverpaymentComponents(
880 env.current()->rules(),
881 asset,
882 loanScale,
883 overpaymentAmount,
884 TenthBips32(0),
885 TenthBips32(0),
886 managementFeeRate);
887
888 auto const loanProperties = computeLoanProperties(
889 env.current()->rules(),
890 asset,
891 loanPrincipal,
892 loanInterestRate,
893 paymentInterval,
894 paymentsRemaining,
895 managementFeeRate,
896 loanScale);
897
898 auto const ret = tryOverpayment(
899 env.current()->rules(),
900 asset,
901 loanScale,
902 overpaymentComponents,
903 loanProperties.loanState,
904 loanProperties.periodicPayment,
905 periodicRate,
906 paymentsRemaining,
907 managementFeeRate,
908 env.journal);
909
910 BEAST_EXPECT(ret);
911
912 auto const& [actualPaymentParts, newLoanProperties] = *ret;
913 auto const& newState = newLoanProperties.loanState;
914
915 // =========== VALIDATE PAYMENT PARTS ===========
916 BEAST_EXPECTS(
917 actualPaymentParts.valueChange == 0,
918 " valueChange mismatch: expected 0, got " + to_string(actualPaymentParts.valueChange));
919
920 BEAST_EXPECTS(
921 actualPaymentParts.feePaid == 0,
922 " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid));
923
924 BEAST_EXPECTS(
925 actualPaymentParts.interestPaid == 0,
926 " interestPaid mismatch: expected 0, got " +
927 to_string(actualPaymentParts.interestPaid));
928
929 BEAST_EXPECTS(
930 actualPaymentParts.principalPaid == overpaymentAmount,
931 " principalPaid mismatch: expected " + to_string(overpaymentAmount) + ", got " +
932 to_string(actualPaymentParts.principalPaid));
933
934 // =========== VALIDATE STATE CHANGES ===========
935 BEAST_EXPECTS(
936 loanProperties.loanState.interestDue - newState.interestDue == 0,
937 " interest change mismatch: expected 0, got " +
938 to_string(loanProperties.loanState.interestDue - newState.interestDue));
939
940 BEAST_EXPECTS(
941 loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0,
942 " management fee change mismatch: expected 0, got " +
943 to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue));
944
945 BEAST_EXPECTS(
946 actualPaymentParts.principalPaid ==
947 loanProperties.loanState.principalOutstanding - newState.principalOutstanding,
948 " principalPaid mismatch: expected " +
949 to_string(
950 loanProperties.loanState.principalOutstanding - newState.principalOutstanding) +
951 ", got " + to_string(actualPaymentParts.principalPaid));
952 }
953
954 void
956 {
957 testcase("tryOverpayment - No Interest With Overpayment Fee");
958
959 using namespace jtx;
960 using namespace xrpl::detail;
961
962 Env const env{*this};
963 Account const issuer{"issuer"};
964 PrettyAsset const asset = issuer["USD"];
965 std::int32_t const loanScale = -5;
966 TenthBips16 const managementFeeRate{0}; // 0%
967 TenthBips32 const loanInterestRate{0}; // 0%
968 Number const loanPrincipal{1'000};
969 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
970 std::uint32_t const paymentsRemaining = 10;
971 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
972
973 auto const overpaymentComponents = computeOverpaymentComponents(
974 env.current()->rules(),
975 asset,
976 loanScale,
977 Number{50, 0},
978 TenthBips32(0),
979 TenthBips32(10'000), // 10% overpayment fee
980 managementFeeRate);
981
982 auto const loanProperties = computeLoanProperties(
983 env.current()->rules(),
984 asset,
985 loanPrincipal,
986 loanInterestRate,
987 paymentInterval,
988 paymentsRemaining,
989 managementFeeRate,
990 loanScale);
991
992 auto const ret = tryOverpayment(
993 env.current()->rules(),
994 asset,
995 loanScale,
996 overpaymentComponents,
997 loanProperties.loanState,
998 loanProperties.periodicPayment,
999 periodicRate,
1000 paymentsRemaining,
1001 managementFeeRate,
1002 env.journal);
1003
1004 BEAST_EXPECT(ret);
1005
1006 auto const& [actualPaymentParts, newLoanProperties] = *ret;
1007 auto const& newState = newLoanProperties.loanState;
1008
1009 // =========== VALIDATE PAYMENT PARTS ===========
1010 BEAST_EXPECTS(
1011 actualPaymentParts.valueChange == 0,
1012 " valueChange mismatch: expected 0, got " + to_string(actualPaymentParts.valueChange));
1013
1014 BEAST_EXPECTS(
1015 actualPaymentParts.feePaid == 5,
1016 " feePaid mismatch: expected 5, got " + to_string(actualPaymentParts.feePaid));
1017
1018 BEAST_EXPECTS(
1019 actualPaymentParts.principalPaid == 45,
1020 " principalPaid mismatch: expected 45, got `" +
1021 to_string(actualPaymentParts.principalPaid));
1022
1023 BEAST_EXPECTS(
1024 actualPaymentParts.interestPaid == 0,
1025 " interestPaid mismatch: expected 0, got " +
1026 to_string(actualPaymentParts.interestPaid));
1027
1028 // =========== VALIDATE STATE CHANGES ===========
1029 // With no Loan interest, interest outstanding should not change
1030 BEAST_EXPECTS(
1031 loanProperties.loanState.interestDue - newState.interestDue == 0,
1032 " interest change mismatch: expected 0, got " +
1033 to_string(loanProperties.loanState.interestDue - newState.interestDue));
1034
1035 // With no Loan management fee, management fee due should not change
1036 BEAST_EXPECTS(
1037 loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0,
1038 " management fee change mismatch: expected 0, got " +
1039 to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue));
1040
1041 BEAST_EXPECTS(
1042 actualPaymentParts.principalPaid ==
1043 loanProperties.loanState.principalOutstanding - newState.principalOutstanding,
1044 " principalPaid mismatch: expected " +
1045 to_string(
1046 loanProperties.loanState.principalOutstanding - newState.principalOutstanding) +
1047 ", got " + to_string(actualPaymentParts.principalPaid));
1048 }
1049
1050 void
1052 {
1053 testcase("tryOverpayment - Loan Interest, No Overpayment Fees");
1054
1055 using namespace jtx;
1056 using namespace xrpl::detail;
1057
1058 Env const env{*this};
1059 Account const issuer{"issuer"};
1060 PrettyAsset const asset = issuer["USD"];
1061 std::int32_t const loanScale = -5;
1062 TenthBips16 const managementFeeRate{0}; // 0%
1063 TenthBips32 const loanInterestRate{10'000}; // 10%
1064 Number const loanPrincipal{1'000};
1065 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
1066 std::uint32_t const paymentsRemaining = 10;
1067 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
1068
1069 auto const overpaymentComponents = computeOverpaymentComponents(
1070 env.current()->rules(),
1071 asset,
1072 loanScale,
1073 Number{50, 0},
1074 TenthBips32(0), // no overpayment interest
1075 TenthBips32(0), // 0% overpayment fee
1076 managementFeeRate);
1077
1078 auto const loanProperties = computeLoanProperties(
1079 env.current()->rules(),
1080 asset,
1081 loanPrincipal,
1082 loanInterestRate,
1083 paymentInterval,
1084 paymentsRemaining,
1085 managementFeeRate,
1086 loanScale);
1087
1088 auto const ret = tryOverpayment(
1089 env.current()->rules(),
1090 asset,
1091 loanScale,
1092 overpaymentComponents,
1093 loanProperties.loanState,
1094 loanProperties.periodicPayment,
1095 periodicRate,
1096 paymentsRemaining,
1097 managementFeeRate,
1098 env.journal);
1099
1100 BEAST_EXPECT(ret);
1101
1102 auto const& [actualPaymentParts, newLoanProperties] = *ret;
1103 auto const& newState = newLoanProperties.loanState;
1104
1105 // =========== VALIDATE PAYMENT PARTS ===========
1106 // with no overpayment interest portion, value change should equal
1107 // interest decrease
1108 BEAST_EXPECTS(
1109 (actualPaymentParts.valueChange == Number{-228802, -5}),
1110 " valueChange mismatch: expected " + to_string(Number{-228802, -5}) + ", got " +
1111 to_string(actualPaymentParts.valueChange));
1112
1113 // with no fee portion, fee paid should be zero
1114 BEAST_EXPECTS(
1115 actualPaymentParts.feePaid == 0,
1116 " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid));
1117
1118 BEAST_EXPECTS(
1119 actualPaymentParts.principalPaid == 50,
1120 " principalPaid mismatch: expected 50, got `" +
1121 to_string(actualPaymentParts.principalPaid));
1122
1123 // with no interest portion, interest paid should be zero
1124 BEAST_EXPECTS(
1125 actualPaymentParts.interestPaid == 0,
1126 " interestPaid mismatch: expected 0, got " +
1127 to_string(actualPaymentParts.interestPaid));
1128
1129 // =========== VALIDATE STATE CHANGES ===========
1130 BEAST_EXPECTS(
1131 actualPaymentParts.principalPaid ==
1132 loanProperties.loanState.principalOutstanding - newState.principalOutstanding,
1133 " principalPaid mismatch: expected " +
1134 to_string(
1135 loanProperties.loanState.principalOutstanding - newState.principalOutstanding) +
1136 ", got " + to_string(actualPaymentParts.principalPaid));
1137
1138 BEAST_EXPECTS(
1139 actualPaymentParts.valueChange ==
1140 newState.interestDue - loanProperties.loanState.interestDue,
1141 " valueChange mismatch: expected " +
1142 to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " +
1143 to_string(actualPaymentParts.valueChange));
1144
1145 // With no Loan management fee, management fee due should not change
1146 BEAST_EXPECTS(
1147 loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0,
1148 " management fee change mismatch: expected 0, got " +
1149 to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue));
1150 }
1151
1152 void
1154 {
1155 testcase("tryOverpayment - Loan Interest, Overpayment Interest, No Fee");
1156
1157 using namespace jtx;
1158 using namespace xrpl::detail;
1159
1160 Env const env{*this};
1161 Account const issuer{"issuer"};
1162 PrettyAsset const asset = issuer["USD"];
1163 std::int32_t const loanScale = -5;
1164 TenthBips16 const managementFeeRate{0}; // 0%
1165 TenthBips32 const loanInterestRate{10'000}; // 10%
1166 Number const loanPrincipal{1'000};
1167 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
1168 std::uint32_t const paymentsRemaining = 10;
1169 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
1170
1171 auto const overpaymentComponents = computeOverpaymentComponents(
1172 env.current()->rules(),
1173 asset,
1174 loanScale,
1175 Number{50, 0},
1176 TenthBips32(10'000), // 10% overpayment interest
1177 TenthBips32(0), // 0% overpayment fee
1178 managementFeeRate);
1179
1180 auto const loanProperties = computeLoanProperties(
1181 env.current()->rules(),
1182 asset,
1183 loanPrincipal,
1184 loanInterestRate,
1185 paymentInterval,
1186 paymentsRemaining,
1187 managementFeeRate,
1188 loanScale);
1189
1190 auto const ret = tryOverpayment(
1191 env.current()->rules(),
1192 asset,
1193 loanScale,
1194 overpaymentComponents,
1195 loanProperties.loanState,
1196 loanProperties.periodicPayment,
1197 periodicRate,
1198 paymentsRemaining,
1199 managementFeeRate,
1200 env.journal);
1201
1202 BEAST_EXPECT(ret);
1203
1204 auto const& [actualPaymentParts, newLoanProperties] = *ret;
1205 auto const& newState = newLoanProperties.loanState;
1206
1207 // =========== VALIDATE PAYMENT PARTS ===========
1208 // with overpayment interest portion, interest paid should be 5
1209 BEAST_EXPECTS(
1210 actualPaymentParts.interestPaid == 5,
1211 " interestPaid mismatch: expected 5, got " +
1212 to_string(actualPaymentParts.interestPaid));
1213
1214 // With overpayment interest portion, value change should equal the
1215 // interest decrease plus overpayment interest portion
1216 BEAST_EXPECTS(
1217 (actualPaymentParts.valueChange ==
1218 Number{-205922, -5} + actualPaymentParts.interestPaid),
1219 " valueChange mismatch: expected " +
1220 to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid) +
1221 ", got " + to_string(actualPaymentParts.valueChange));
1222
1223 // with no fee portion, fee paid should be zero
1224 BEAST_EXPECTS(
1225 actualPaymentParts.feePaid == 0,
1226 " feePaid mismatch: expected 0, got " + to_string(actualPaymentParts.feePaid));
1227
1228 BEAST_EXPECTS(
1229 actualPaymentParts.principalPaid == 45,
1230 " principalPaid mismatch: expected 45, got `" +
1231 to_string(actualPaymentParts.principalPaid));
1232
1233 // =========== VALIDATE STATE CHANGES ===========
1234 BEAST_EXPECTS(
1235 actualPaymentParts.principalPaid ==
1236 loanProperties.loanState.principalOutstanding - newState.principalOutstanding,
1237 " principalPaid mismatch: expected " +
1238 to_string(
1239 loanProperties.loanState.principalOutstanding - newState.principalOutstanding) +
1240 ", got " + to_string(actualPaymentParts.principalPaid));
1241
1242 // The change in interest is equal to the value change sans the
1243 // overpayment interest
1244 BEAST_EXPECTS(
1245 actualPaymentParts.valueChange - actualPaymentParts.interestPaid ==
1246 newState.interestDue - loanProperties.loanState.interestDue,
1247 " valueChange mismatch: expected " +
1248 to_string(
1249 newState.interestDue - loanProperties.loanState.interestDue +
1250 actualPaymentParts.interestPaid) +
1251 ", got " + to_string(actualPaymentParts.valueChange));
1252
1253 // With no Loan management fee, management fee due should not change
1254 BEAST_EXPECTS(
1255 loanProperties.loanState.managementFeeDue - newState.managementFeeDue == 0,
1256 " management fee change mismatch: expected 0, got " +
1257 to_string(loanProperties.loanState.managementFeeDue - newState.managementFeeDue));
1258 }
1259
1260 void
1262 {
1263 testcase(
1264 "tryOverpayment - Loan Interest and Fee, Overpayment Interest, No "
1265 "Fee");
1266
1267 using namespace jtx;
1268 using namespace xrpl::detail;
1269
1270 Env const env{*this};
1271 Account const issuer{"issuer"};
1272 PrettyAsset const asset = issuer["USD"];
1273 std::int32_t const loanScale = -5;
1274 TenthBips16 const managementFeeRate{10'000}; // 10%
1275 TenthBips32 const loanInterestRate{10'000}; // 10%
1276 Number const loanPrincipal{1'000};
1277 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
1278 std::uint32_t const paymentsRemaining = 10;
1279 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
1280
1281 auto const overpaymentComponents = computeOverpaymentComponents(
1282 env.current()->rules(),
1283 asset,
1284 loanScale,
1285 Number{50, 0},
1286 TenthBips32(10'000), // 10% overpayment interest
1287 TenthBips32(0), // 0% overpayment fee
1288 managementFeeRate);
1289
1290 auto const loanProperties = computeLoanProperties(
1291 env.current()->rules(),
1292 asset,
1293 loanPrincipal,
1294 loanInterestRate,
1295 paymentInterval,
1296 paymentsRemaining,
1297 managementFeeRate,
1298 loanScale);
1299
1300 auto const ret = tryOverpayment(
1301 env.current()->rules(),
1302 asset,
1303 loanScale,
1304 overpaymentComponents,
1305 loanProperties.loanState,
1306 loanProperties.periodicPayment,
1307 periodicRate,
1308 paymentsRemaining,
1309 managementFeeRate,
1310 env.journal);
1311
1312 BEAST_EXPECT(ret);
1313
1314 auto const& [actualPaymentParts, newLoanProperties] = *ret;
1315 auto const& newState = newLoanProperties.loanState;
1316
1317 // =========== VALIDATE PAYMENT PARTS ===========
1318
1319 // Since there is loan management fee, the fee is charged against
1320 // overpayment interest portion first, so interest paid remains 4.5
1321 BEAST_EXPECTS(
1322 (actualPaymentParts.interestPaid == Number{45, -1}),
1323 " interestPaid mismatch: expected 4.5, got " +
1324 to_string(actualPaymentParts.interestPaid));
1325
1326 // With overpayment interest portion, value change should equal the
1327 // interest decrease plus overpayment interest portion
1328 BEAST_EXPECTS(
1329 (actualPaymentParts.valueChange ==
1330 Number{-18533, -4} + actualPaymentParts.interestPaid),
1331 " valueChange mismatch: expected " +
1332 to_string(Number{-18533, -4} + actualPaymentParts.interestPaid) + ", got " +
1333 to_string(actualPaymentParts.valueChange));
1334
1335 // While there is no overpayment fee, fee paid should equal the
1336 // management fee charged against the overpayment interest portion
1337 BEAST_EXPECTS(
1338 (actualPaymentParts.feePaid == Number{5, -1}),
1339 " feePaid mismatch: expected 0.5, got " + to_string(actualPaymentParts.feePaid));
1340
1341 BEAST_EXPECTS(
1342 actualPaymentParts.principalPaid == 45,
1343 " principalPaid mismatch: expected 45, got `" +
1344 to_string(actualPaymentParts.principalPaid));
1345
1346 // =========== VALIDATE STATE CHANGES ===========
1347 BEAST_EXPECTS(
1348 actualPaymentParts.principalPaid ==
1349 loanProperties.loanState.principalOutstanding - newState.principalOutstanding,
1350 " principalPaid mismatch: expected " +
1351 to_string(
1352 loanProperties.loanState.principalOutstanding - newState.principalOutstanding) +
1353 ", got " + to_string(actualPaymentParts.principalPaid));
1354
1355 // Note that the management fee value change is not captured, as this
1356 // value is not needed to correctly update the Vault state.
1357 BEAST_EXPECTS(
1358 (newState.managementFeeDue - loanProperties.loanState.managementFeeDue ==
1359 Number{-20592, -5}),
1360 " management fee change mismatch: expected " + to_string(Number{-20592, -5}) +
1361 ", got " +
1362 to_string(newState.managementFeeDue - loanProperties.loanState.managementFeeDue));
1363
1364 BEAST_EXPECTS(
1365 actualPaymentParts.valueChange - actualPaymentParts.interestPaid ==
1366 newState.interestDue - loanProperties.loanState.interestDue,
1367 " valueChange mismatch: expected " +
1368 to_string(newState.interestDue - loanProperties.loanState.interestDue) + ", got " +
1369 to_string(actualPaymentParts.valueChange - actualPaymentParts.interestPaid));
1370 }
1371
1372 void
1374 {
1375 testcase("tryOverpayment - Loan Interest, Fee, Overpayment Interest, Fee");
1376
1377 using namespace jtx;
1378 using namespace xrpl::detail;
1379
1380 Account const issuer{"issuer"};
1381 PrettyAsset const asset = issuer["USD"];
1382 std::int32_t const loanScale = -5;
1383 TenthBips16 const managementFeeRate{10'000}; // 10%
1384 TenthBips32 const loanInterestRate{10'000}; // 10%
1385 Number const loanPrincipal{1'000};
1386 std::uint32_t const paymentInterval = 30 * 24 * 60 * 60;
1387 std::uint32_t const paymentsRemaining = 10;
1388 auto const periodicRate = loanPeriodicRate(loanInterestRate, paymentInterval);
1389
1390 Env const env{*this};
1391 auto const overpaymentComponents = computeOverpaymentComponents(
1392 env.current()->rules(),
1393 asset,
1394 loanScale,
1395 Number{50, 0},
1396 TenthBips32(10'000), // 10% overpayment interest
1397 TenthBips32(10'000), // 10% overpayment fee
1398 managementFeeRate);
1399
1400 struct Outcome
1401 {
1402 LoanPaymentParts parts;
1403 LoanState oldState;
1404 LoanState newState;
1405 };
1406
1407 // Run tryOverpayment under a given amendment set. At this (non-near-zero)
1408 // rate computeLoanProperties is amendment-independent, so the loan state
1409 // is identical across the amendment; only tryOverpayment's fixCleanup3_2_0
1410 // behaviour (the exact-principal pin and the management-fee re-derivation
1411 // from that principal) differs.
1412 auto const run = [&](FeatureBitset features) -> std::optional<Outcome> {
1413 Env const env{*this, features};
1414 auto const loanProperties = computeLoanProperties(
1415 env.current()->rules(),
1416 asset,
1417 loanPrincipal,
1418 loanInterestRate,
1419 paymentInterval,
1420 paymentsRemaining,
1421 managementFeeRate,
1422 loanScale);
1423 auto const ret = tryOverpayment(
1424 env.current()->rules(),
1425 asset,
1426 loanScale,
1427 overpaymentComponents,
1428 loanProperties.loanState,
1429 loanProperties.periodicPayment,
1430 periodicRate,
1431 paymentsRemaining,
1432 managementFeeRate,
1433 env.journal);
1434 if (!BEAST_EXPECT(ret))
1435 return std::nullopt;
1436 return Outcome{
1437 .parts = ret->first,
1438 .oldState = loanProperties.loanState,
1439 .newState = ret->second.loanState,
1440 };
1441 };
1442
1443 auto const fixedOpt = run(testableAmendments());
1444 auto const legacyOpt = run(testableAmendments() - fixCleanup3_2_0);
1445 if (!fixedOpt || !legacyOpt)
1446 {
1447 BEAST_EXPECT(fixedOpt.has_value());
1448 BEAST_EXPECT(legacyOpt.has_value());
1449 return;
1450 }
1451 Outcome const& fixed = *fixedOpt;
1452 Outcome const& legacy = *legacyOpt;
1453
1454 // Components that the amendment does not change. The management fee is
1455 // charged against the overpayment interest portion first, so interest
1456 // paid stays 4.5 and fee paid 5.5; the principal repaid is 40 in both.
1457 auto const checkCommon = [&](Outcome const& o, char const* tag) {
1458 BEAST_EXPECTS(
1459 (o.parts.interestPaid == Number{45, -1}),
1460 std::string(tag) + " interestPaid " + to_string(o.parts.interestPaid));
1461 BEAST_EXPECTS(
1462 (o.parts.feePaid == Number{55, -1}),
1463 std::string(tag) + " feePaid " + to_string(o.parts.feePaid));
1464 BEAST_EXPECTS(
1465 o.parts.principalPaid == 40,
1466 std::string(tag) + " principalPaid " + to_string(o.parts.principalPaid));
1467 BEAST_EXPECT(
1468 o.parts.principalPaid ==
1469 o.oldState.principalOutstanding - o.newState.principalOutstanding);
1470 // v = p + i + m identity: the non-interest part of valueChange equals
1471 // the interest-due change.
1472 BEAST_EXPECT(
1473 o.parts.valueChange - o.parts.interestPaid ==
1474 o.newState.interestDue - o.oldState.interestDue);
1475 };
1476 checkCommon(fixed, "fixed");
1477 checkCommon(legacy, "legacy");
1478
1479 // With fixCleanup3_2_0 the management fee is re-derived from the exact
1480 // principal; without it, from the one-scale-unit-high round-trip
1481 // principal. So the management fee outstanding (and hence the value
1482 // change, via v = p + i + m) differ by exactly one scale-unit (1e-5 at
1483 // loanScale -5) between the two paths.
1484 BEAST_EXPECT((fixed.parts.valueChange == Number{-164738, -5} + fixed.parts.interestPaid));
1485 BEAST_EXPECT(
1486 (fixed.newState.managementFeeDue - fixed.oldState.managementFeeDue ==
1487 Number{-18303, -5}));
1488 BEAST_EXPECT((legacy.parts.valueChange == Number{-164737, -5} + legacy.parts.interestPaid));
1489 BEAST_EXPECT(
1490 (legacy.newState.managementFeeDue - legacy.oldState.managementFeeDue ==
1491 Number{-18304, -5}));
1492 }
1493
1494 void
1496 {
1497 using namespace xrpl::instant_recognition;
1498
1499 struct TestCase
1500 {
1501 std::string name;
1502 Number principalRequested;
1503 Number interestDue;
1504 };
1505
1506 auto const testCases = std::vector<TestCase>{
1507 {
1508 .name = "Zero interest",
1509 .principalRequested = Number{1'000},
1510 .interestDue = Number{0},
1511 },
1512 {
1513 .name = "Nonzero interest",
1514 .principalRequested = Number{1'000},
1515 .interestDue = Number{75},
1516 },
1517 };
1518
1519 for (auto const& tc : testCases)
1520 {
1521 testcase("instant_recognition::loanOriginationDeltas: " + tc.name);
1522
1523 auto const deltas = loanOriginationDeltas(tc.principalRequested, tc.interestDue);
1524 BEAST_EXPECTS(
1525 deltas.assetsTotalDelta == tc.interestDue,
1526 "assetsTotalDelta mismatch: expected " + to_string(tc.interestDue) + ", got " +
1527 to_string(deltas.assetsTotalDelta));
1528 BEAST_EXPECTS(
1529 deltas.debtTotalDelta == tc.principalRequested + tc.interestDue,
1530 "debtTotalDelta mismatch: expected " +
1531 to_string(tc.principalRequested + tc.interestDue) + ", got " +
1532 to_string(deltas.debtTotalDelta));
1533 }
1534 }
1535
1536 void
1538 {
1539 using namespace xrpl::cash_basis;
1540
1541 testcase("cash_basis::loanOriginationDeltas: interestDue is ignored");
1542
1543 Number const principalRequested{1'000};
1544 Number const interestDue{75};
1545
1546 auto const deltas = loanOriginationDeltas(principalRequested);
1547 BEAST_EXPECTS(
1548 deltas.assetsTotalDelta == 0,
1549 "assetsTotalDelta mismatch: expected 0, got " + to_string(deltas.assetsTotalDelta));
1550 BEAST_EXPECTS(
1551 deltas.debtTotalDelta == principalRequested,
1552 "debtTotalDelta mismatch: expected " + to_string(principalRequested) + ", got " +
1553 to_string(deltas.debtTotalDelta));
1554 }
1555
1556 void
1558 {
1559 using namespace xrpl::instant_recognition;
1560
1561 struct TestCase
1562 {
1563 std::string name;
1564 Number vaultMaximum;
1565 Number vaultTotal;
1566 Number interestDue;
1567 bool expected;
1568 };
1569
1570 auto const testCases = std::vector<TestCase>{
1571 {
1572 .name = "No maximum configured",
1573 .vaultMaximum = Number{0},
1574 .vaultTotal = Number{900},
1575 .interestDue = Number{1'000},
1576 .expected = false,
1577 },
1578 {
1579 .name = "Interest fits under headroom",
1580 .vaultMaximum = Number{1'000},
1581 .vaultTotal = Number{900},
1582 .interestDue = Number{50},
1583 .expected = false,
1584 },
1585 {
1586 .name = "Interest exactly fills headroom",
1587 .vaultMaximum = Number{1'000},
1588 .vaultTotal = Number{900},
1589 .interestDue = Number{100},
1590 .expected = false,
1591 },
1592 {
1593 .name = "Interest exceeds headroom",
1594 .vaultMaximum = Number{1'000},
1595 .vaultTotal = Number{900},
1596 .interestDue = Number{101},
1597 .expected = true,
1598 },
1599 };
1600
1601 for (auto const& tc : testCases)
1602 {
1603 testcase("instant_recognition::loanOriginationExceedsVaultMaximum: " + tc.name);
1604 BEAST_EXPECT(
1606 tc.vaultMaximum, tc.vaultTotal, tc.interestDue) == tc.expected);
1607 }
1608 }
1609
1610 // Constructs a minimal ltLOAN SLE with just the fields needed by
1611 // loanVaultExposure. Mirrors the bare-SLE pattern used by
1612 // testCanApplyToBrokerCover for ltLOAN_BROKER.
1615 Number const& totalValueOutstanding,
1616 Number const& principalOutstanding,
1617 Number const& managementFeeOutstanding)
1618 {
1619 auto sle = std::make_shared<SLE>(ltLOAN, UInt256{1u});
1620 sle->at(sfTotalValueOutstanding) = totalValueOutstanding;
1621 sle->at(sfPrincipalOutstanding) = principalOutstanding;
1622 sle->at(sfManagementFeeOutstanding) = managementFeeOutstanding;
1623 return sle;
1624 }
1625
1626 // Constructs a minimal ltVAULT SLE with just LEVersion set (or left
1627 // absent), for exercising the dispatchers' per-Vault gating.
1630 std::optional<VaultVersion> leVersion = std::nullopt,
1631 std::optional<Number> assetsMaximum = std::nullopt,
1632 std::optional<Number> assetsTotal = std::nullopt)
1633 {
1634 auto sle = std::make_shared<SLE>(ltVAULT, UInt256{2u});
1635 if (leVersion)
1636 sle->at(sfLEVersion) = std::to_underlying(*leVersion);
1637 if (assetsMaximum)
1638 sle->at(sfAssetsMaximum) = *assetsMaximum;
1639 if (assetsTotal)
1640 sle->at(sfAssetsTotal) = *assetsTotal;
1641 return sle;
1642 }
1643
1644 void
1646 {
1647 testcase("instant_recognition::loanVaultExposure");
1648
1649 auto const sle = makeLoanSle(Number{1'000}, Number{800}, Number{50});
1650 BEAST_EXPECT(xrpl::instant_recognition::loanVaultExposure(sle) == Number{950});
1651 }
1652
1653 void
1655 {
1656 testcase("cash_basis::loanVaultExposure");
1657
1658 auto const sle = makeLoanSle(Number{1'000}, Number{800}, Number{50});
1659 BEAST_EXPECT(xrpl::cash_basis::loanVaultExposure(sle) == Number{800});
1660 }
1661
1662 void
1664 {
1665 // principalPaid, interestPaid, feePaid, valueChange are all distinct
1666 // and nonzero, with a nonzero valueChange simulating a late-payment
1667 // penalty, so InstantRecognition's formula is meaningfully exercised.
1668 LoanPaymentParts const parts{
1669 .principalPaid = Number{100},
1670 .interestPaid = Number{20},
1671 .valueChange = Number{5},
1672 .feePaid = Number{3},
1673 };
1674
1675 {
1676 testcase("instant_recognition::loanPaymentDeltas: nonzero valueChange");
1677 auto const deltas = xrpl::instant_recognition::loanPaymentDeltas(parts);
1678 BEAST_EXPECT(deltas.assetsTotalDelta == parts.valueChange);
1679 BEAST_EXPECT(
1680 deltas.debtTotalDelta ==
1681 (parts.principalPaid + parts.interestPaid) - parts.valueChange);
1682 }
1683
1684 {
1685 testcase("cash_basis::loanPaymentDeltas: nonzero valueChange ignored");
1686 auto const deltas = xrpl::cash_basis::loanPaymentDeltas(parts);
1687 BEAST_EXPECT(deltas.assetsTotalDelta == parts.interestPaid);
1688 BEAST_EXPECT(deltas.debtTotalDelta == parts.principalPaid);
1689 }
1690 }
1691
1692 void
1694 {
1695 using namespace jtx;
1696
1697 Number const principalRequested{1'000};
1698 Number const interestDue{75};
1699
1700 auto const legacyVault = makeVaultSle();
1701
1702 {
1703 testcase(
1704 "loanOriginationDeltas dispatcher: amendment enabled, legacy vault picks "
1705 "InstantRecognition");
1706 Env const env{*this};
1707 auto const deltas = loanOriginationDeltas(legacyVault, principalRequested, interestDue);
1708 auto const expected =
1709 xrpl::instant_recognition::loanOriginationDeltas(principalRequested, interestDue);
1710 BEAST_EXPECT(deltas.assetsTotalDelta == expected.assetsTotalDelta);
1711 BEAST_EXPECT(deltas.debtTotalDelta == expected.debtTotalDelta);
1712 }
1713
1714 {
1715 testcase(
1716 "loanOriginationDeltas dispatcher: CashBasis and FixedPrecision "
1717 "Vaults pick cash-basis accounting");
1718 Env const env{*this};
1719 for (auto const version : {VaultVersion::CashBasis, VaultVersion::FixedPrecision})
1720 {
1721 auto const deltas =
1722 loanOriginationDeltas(makeVaultSle(version), principalRequested, interestDue);
1723 auto const expected = xrpl::cash_basis::loanOriginationDeltas(principalRequested);
1724 BEAST_EXPECT(deltas.assetsTotalDelta == expected.assetsTotalDelta);
1725 BEAST_EXPECT(deltas.debtTotalDelta == expected.debtTotalDelta);
1726 }
1727 }
1728 }
1729
1730 void
1732 {
1733 using namespace jtx;
1734
1735 Number const vaultMaximum{1'000};
1736 Number const vaultTotal{900};
1737 // Exceeds InstantRecognition's headroom (100), but must never trip CashBasis.
1738 Number const interestDue{101};
1739
1740 auto const legacyVault = makeVaultSle(std::nullopt, vaultMaximum, vaultTotal);
1741
1742 {
1743 testcase(
1744 "loanOriginationExceedsVaultMaximum dispatcher: amendment enabled, legacy vault "
1745 "picks InstantRecognition");
1746 Env const env{*this};
1747 BEAST_EXPECT(
1748 loanOriginationExceedsVaultMaximum(legacyVault, vaultTotal, interestDue) ==
1750 vaultMaximum, vaultTotal, interestDue));
1751 }
1752
1753 {
1754 testcase(
1755 "loanOriginationExceedsVaultMaximum dispatcher: CashBasis and "
1756 "FixedPrecision Vaults pick cash-basis accounting");
1757 Env const env{*this};
1758 for (auto const version : {VaultVersion::CashBasis, VaultVersion::FixedPrecision})
1759 {
1760 BEAST_EXPECT(
1762 makeVaultSle(version, vaultMaximum, vaultTotal), vaultTotal, interestDue) ==
1763 false);
1764 }
1765 }
1766 }
1767
1768 void
1770 {
1771 using namespace jtx;
1772
1773 auto const legacyVault = makeVaultSle();
1774
1775 {
1776 testcase(
1777 "loanVaultExposure dispatcher: amendment enabled, legacy vault picks "
1778 "InstantRecognition");
1779 Env const env{*this};
1780 auto const sle = makeLoanSle(Number{1'000}, Number{800}, Number{50});
1781 BEAST_EXPECT(
1782 loanVaultExposure(legacyVault, sle) ==
1784 }
1785
1786 {
1787 testcase(
1788 "loanVaultExposure dispatcher: CashBasis and FixedPrecision "
1789 "Vaults pick cash-basis accounting");
1790 Env const env{*this};
1791 auto const sle = makeLoanSle(Number{1'000}, Number{800}, Number{50});
1792 for (auto const version : {VaultVersion::CashBasis, VaultVersion::FixedPrecision})
1793 {
1794 BEAST_EXPECT(
1795 loanVaultExposure(makeVaultSle(version), sle) ==
1797 }
1798 }
1799 }
1800
1801 void
1803 {
1804 using namespace jtx;
1805
1806 LoanPaymentParts const parts{
1807 .principalPaid = Number{100},
1808 .interestPaid = Number{20},
1809 .valueChange = Number{5},
1810 .feePaid = Number{3},
1811 };
1812
1813 auto const legacyVault = makeVaultSle();
1814
1815 {
1816 testcase(
1817 "loanPaymentDeltas dispatcher: amendment enabled, legacy vault picks "
1818 "InstantRecognition");
1819 Env const env{*this};
1820 auto const deltas = loanPaymentDeltas(legacyVault, parts);
1821 auto const expected = xrpl::instant_recognition::loanPaymentDeltas(parts);
1822 BEAST_EXPECT(deltas.assetsTotalDelta == expected.assetsTotalDelta);
1823 BEAST_EXPECT(deltas.debtTotalDelta == expected.debtTotalDelta);
1824 }
1825
1826 {
1827 testcase(
1828 "loanPaymentDeltas dispatcher: CashBasis and FixedPrecision "
1829 "Vaults pick cash-basis accounting");
1830 Env const env{*this};
1831 for (auto const version : {VaultVersion::CashBasis, VaultVersion::FixedPrecision})
1832 {
1833 auto const deltas = loanPaymentDeltas(makeVaultSle(version), parts);
1834 auto const expected = xrpl::cash_basis::loanPaymentDeltas(parts);
1835 BEAST_EXPECT(deltas.assetsTotalDelta == expected.assetsTotalDelta);
1836 BEAST_EXPECT(deltas.debtTotalDelta == expected.debtTotalDelta);
1837 }
1838 }
1839 }
1840
1841public:
1842 void
1844 {
1845 using namespace jtx;
1846
1847 Account const issuer{"issuer"};
1848 PrettyAsset const iou = issuer["IOU"];
1849
1850 // sfCoverAvailable = Number{10} on an IOU → STAmount exponent = -14,
1851 // so coverScale = -14. The ULP boundary is 5e-15; anything below
1852 // that rounds to zero at cover scale. Number{1,-16} = 1e-16 is our
1853 // representative sub-ULP probe.
1854 struct TestCase
1855 {
1856 std::string name;
1857 Number coverAvailable;
1858 STAmount amount;
1859 TER expected;
1860 };
1861
1862 auto const testCases = std::vector<TestCase>{
1863 {
1864 .name = "Zero amount",
1865 .coverAvailable = Number{10},
1866 .amount = STAmount{iou, Number{0}},
1867 .expected = tecPRECISION_LOSS,
1868 },
1869 {
1870 .name = "Rounds to zero at cover scale",
1871 .coverAvailable = Number{10},
1872 .amount = STAmount{iou, Number{1, -16}},
1873 .expected = tecPRECISION_LOSS,
1874 },
1875 {
1876 .name = "Zero coverAvailable, whole-unit amount",
1877 // coverScale = 0 (zero STAmount exponent); 1 IOU is not
1878 // zero at integer scale → tesSUCCESS.
1879 .coverAvailable = Number{0},
1880 .amount = STAmount{iou, Number{1}},
1881 .expected = tesSUCCESS,
1882 },
1883 {
1884 .name = "Supra-ULP amount",
1885 .coverAvailable = Number{10},
1886 .amount = STAmount{iou, Number{1, -13}},
1887 .expected = tesSUCCESS,
1888 },
1889 {
1890 // CoverAvailable 1e10 is exponent -5. 1e-6 is non-zero at
1891 // FixedPrecision P=6, but ToNearest at the live cover
1892 // exponent rounds it to zero. Withdraw/clawback skip this
1893 // helper for FixedPrecision so a re-fining outflow can
1894 // succeed.
1895 .name = "Coarsened live scale rejects re-fining amount",
1896 .coverAvailable = Number{1, 10},
1897 .amount = STAmount{iou, Number{1, -6}},
1898 .expected = tecPRECISION_LOSS,
1899 },
1900 };
1901
1902 Env const env{*this};
1903
1904 for (auto const& tc : testCases)
1905 {
1906 testcase("canApplyToBrokerCover: " + tc.name);
1907 auto const sle = std::make_shared<SLE>(ltLOAN_BROKER, UInt256{1u});
1908 sle->at(sfCoverAvailable) = tc.coverAvailable;
1909 BEAST_EXPECT(
1910 canApplyToBrokerCover(*env.current(), sle, iou, tc.amount, env.journal, "test") ==
1911 tc.expected);
1912 }
1913
1914 // Amendment off → guard is bypassed regardless of amount.
1915 {
1916 testcase("canApplyToBrokerCover: amendment disabled");
1917 Env const envOff{*this, testableAmendments() - fixCleanup3_2_0};
1918 auto const sle = std::make_shared<SLE>(ltLOAN_BROKER, UInt256{1u});
1919 sle->at(sfCoverAvailable) = Number{10};
1920 BEAST_EXPECT(
1922 *envOff.current(),
1923 sle,
1924 iou,
1925 STAmount{iou, Number{0}},
1926 envOff.journal,
1927 "test") == tesSUCCESS);
1928 }
1929
1930 testcase("minimumBrokerCover: FixedPrecision uses base scale");
1931 auto const makeVault = [&](VaultVersion version) {
1932 auto vault = std::make_shared<SLE>(ltVAULT, uint256{2u});
1933 vault->setFieldIssue(sfAsset, STIssue{sfAsset, iou});
1934 vault->at(sfAssetsTotal) = Number{1};
1935 vault->at(sfScale) = 6;
1936 vault->at(sfLEVersion) = std::to_underlying(version);
1937 associateAsset(*vault, iou);
1938 return vault;
1939 };
1940
1941 Number const debtTotal{15, -2};
1942 TenthBips32 const coverRate{1};
1943 BEAST_EXPECT(
1945 Number{2, -6}));
1946 BEAST_EXPECT(
1947 (minimumBrokerCover(debtTotal, coverRate, makeVault(VaultVersion::CashBasis)) ==
1948 Number{15, -7}));
1949 }
1950
1951 // Targeted unit test for getLoanDefaultFreezeExemptAccounts(): builds a real
1952 // (XRP, so no trust lines needed) Vault/LoanBroker/Loan chain, then calls
1953 // the function directly against hand-picked, unsubmitted transactions
1954 // (via env.jt(), which never touches the ledger) to exercise every early
1955 // return and the success path precisely.
1956 void
1958 {
1959 using namespace jtx;
1960 using namespace loan;
1961
1962 testcase("getLoanDefaultFreezeExemptAccounts");
1963
1964 Account const lender{"lender"};
1965 Account const borrower{"borrower"};
1966
1967 Env env{*this};
1968 Vault const vault{env};
1969 env.fund(XRP(10'000), lender, borrower);
1970 env.close();
1971
1972 // Under featureLendingProtocolV1_1 LoanBrokerSet::preclaim only
1973 // accepts closed-ended vaults, so build one with a near-future
1974 // SubscriptionDate, deposit while still in the Subscription phase,
1975 // and advance past SubscriptionDate before creating the broker.
1976 auto [vaultTx, vaultKeylet, subscriptionDate] =
1977 vault.createClosedEnded({.owner = lender, .asset = xrpIssue()});
1978 env(vaultTx);
1979 env.close();
1980 env(vault.deposit({.depositor = lender, .id = vaultKeylet.key, .amount = XRP(1'000)}));
1981 env.close();
1982
1983 vault.closePastSubscription(subscriptionDate);
1984
1985 auto const brokerKeylet =
1986 keylet::loanBroker(lender.id(), SeqProxy::rawSequence(env.seq(lender)));
1987 env(loan_broker::set(lender, vaultKeylet.key));
1988 env.close();
1989
1990 env(set(borrower, brokerKeylet.key, Number{200'000}),
1991 Sig(sfCounterpartySignature, lender),
1992 Fee(env.current()->fees().base * 2));
1993 env.close();
1994
1995 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
1996
1997 // Not a LoanManage transaction at all.
1998 {
1999 auto const jt = env.jt(jtx::pay(lender, borrower, XRP(1)));
2000 BEAST_EXPECT(!getLoanDefaultFreezeExemptAccounts(*env.current(), *jt.stx));
2001 }
2002
2003 // LoanManage, but not the tfLoanDefault flag.
2004 {
2005 auto const jt = env.jt(manage(lender, loanKeylet.key, tfLoanImpair));
2006 BEAST_EXPECT(!getLoanDefaultFreezeExemptAccounts(*env.current(), *jt.stx));
2007 }
2008
2009 // tfLoanDefault, but fixCleanup3_4_0 is disabled.
2010 {
2011 env.disableFeature(fixCleanup3_4_0);
2012 auto const jt = env.jt(manage(lender, loanKeylet.key, tfLoanDefault));
2013 BEAST_EXPECT(!getLoanDefaultFreezeExemptAccounts(*env.current(), *jt.stx));
2014 env.enableFeature(fixCleanup3_4_0);
2015 }
2016
2017 // tfLoanDefault, amendment enabled, but the referenced Loan doesn't
2018 // exist (reusing the broker's own ID as a bogus LoanID, same trick
2019 // testInvalidLoanManage-style tests use elsewhere in this suite).
2020 {
2021 auto const jt = env.jt(manage(lender, brokerKeylet.key, tfLoanDefault));
2022 BEAST_EXPECT(!getLoanDefaultFreezeExemptAccounts(*env.current(), *jt.stx));
2023 }
2024
2025 // tfLoanDefault, amendment enabled, Loan/LoanBroker/Vault all exist:
2026 // resolves the issuer, broker, vault accounts, and the vault's asset.
2027 {
2028 auto const jt = env.jt(manage(lender, loanKeylet.key, tfLoanDefault));
2029 auto const result = getLoanDefaultFreezeExemptAccounts(*env.current(), *jt.stx);
2030 auto const brokerSle = env.le(brokerKeylet);
2031 auto const vaultSle = env.le(vaultKeylet);
2032 BEAST_EXPECT(result);
2033 BEAST_EXPECT(brokerSle);
2034 BEAST_EXPECT(vaultSle);
2035 if (result && brokerSle && vaultSle)
2036 {
2037 BEAST_EXPECT(result->issuer == vaultSle->at(sfAsset).getIssuer());
2038 BEAST_EXPECT(result->broker == brokerSle->at(sfAccount));
2039 BEAST_EXPECT(result->vault == vaultSle->at(sfAccount));
2040 BEAST_EXPECT(result->asset == vaultSle->at(sfAsset));
2041 }
2042 }
2043 }
2044
2045 void
2083};
2084
2085BEAST_DEFINE_TESTSUITE(LendingHelpers, app, xrpl);
2086
2087} // namespace xrpl::test
A testsuite class.
Definition suite.h:52
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
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 std::shared_ptr< SLE > makeVaultSle(std::optional< VaultVersion > leVersion=std::nullopt, std::optional< Number > assetsMaximum=std::nullopt, std::optional< Number > assetsTotal=std::nullopt)
static std::shared_ptr< SLE > makeLoanSle(Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding)
void run() override
Runs the suite.
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
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
std::uint32_t seq(Account const &account) const
Returns the next sequence number on account.
Definition Env.cpp:302
JTx jt(JsonValue &&jv, FN const &... fN)
Create a JTx from parameters.
Definition Env.h:723
void disableFeature(UInt256 const feature)
Definition Env.cpp:717
void enableFeature(UInt256 const feature)
Definition Env.cpp:709
beast::Journal const journal
Definition Env.h:204
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
Set the fee on a JTx.
Definition fee.h:20
Set the regular signature on a JTx.
Definition sig.h:19
T make_shared(T... args)
AccountingDeltas loanPaymentDeltas(LoanPaymentParts const &parts)
AccountingDeltas loanOriginationDeltas(Number const &principalRequested)
Number loanVaultExposure(SLE::ConstRef loanSle)
Number computePaymentFactor(Rules const &rules, Number const &periodicRate, std::uint32_t paymentsRemaining)
Number loanPrincipalFromPeriodicPayment(Rules const &rules, Number const &periodicPayment, Number const &periodicRate, std::uint32_t paymentsRemaining)
Number computePowerMinusOneHybrid(Number const &periodicRate, std::uint32_t paymentsRemaining)
Number loanPeriodicPayment(Rules const &rules, Number const &principalOutstanding, Number const &periodicRate, std::uint32_t paymentsRemaining)
Number loanAccruedInterest(Number const &principalOutstanding, Number const &periodicRate, NetClock::time_point parentCloseTime, std::uint32_t startDate, std::uint32_t prevPaymentDate, std::uint32_t paymentInterval)
std::pair< Number, Number > computeInterestAndFeeParts(Asset const &asset, Number const &interest, TenthBips16 managementFeeRate, std::int32_t loanScale)
Number loanLatePaymentInterest(Number const &principalOutstanding, TenthBips32 lateInterestRate, NetClock::time_point parentCloseTime, std::uint32_t nextPaymentDueDate)
std::expected< std::pair< LoanPaymentParts, LoanProperties >, TER > tryOverpayment(Rules const &rules, Asset const &asset, std::int32_t loanScale, ExtendedPaymentComponents const &overpaymentComponents, LoanState const &roundedLoanState, Number const &periodicPayment, Number const &periodicRate, std::uint32_t paymentRemaining, TenthBips16 const managementFeeRate, beast::Journal j)
ExtendedPaymentComponents computeOverpaymentComponents(Rules const &rules, Asset const &asset, int32_t const loanScale, Number const &overpayment, TenthBips32 const overpaymentInterestRate, TenthBips32 const overpaymentFeeRate, TenthBips16 const managementFeeRate)
Number computePowerMinusOne(Number const &periodicRate, std::uint32_t paymentsRemaining)
AccountingDeltas loanPaymentDeltas(LoanPaymentParts const &parts)
Number loanVaultExposure(SLE::ConstRef loanSle)
AccountingDeltas loanOriginationDeltas(Number const &principalRequested, Number const &interestDue)
bool loanOriginationExceedsVaultMaximum(Number const &vaultMaximum, Number const &vaultTotal, Number const &interestDue)
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:565
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:571
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
json::Value set(AccountID const &account, UInt256 const &vaultId, uint32_t flags)
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
XrpT const XRP
Converts to XRP Issue or STAmount.
Definition amount.cpp:92
FeatureBitset testableAmendments()
Definition Env.h:92
BEAST_DEFINE_TESTSUITE(AMMClawback, app, xrpl)
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
Number loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval)
bool loanOriginationExceedsVaultMaximum(SLE::ConstRef vaultSle, Number const &vaultTotal, Number const &interestDue)
std::shared_ptr< SLE > makeVault(Asset const &asset, Number const &assetsTotal, std::optional< VaultVersion > version, std::uint8_t scaleValue=kVaultDefaultIouScale, Number const &assetsDeployed=Number{0}, std::optional< Number > assetsAvailable=std::nullopt)
Number power(Number const &f, unsigned n)
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
static FunctionType fixed(Keylet const &keylet)
TenthBips< std::uint16_t > TenthBips16
Definition Units.h:453
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
BaseUInt< 256 > UInt256
Definition base_uint.h:581
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
VaultVersion
Vault ledger-entry schema versions, persisted as sfLEVersion.
Definition Protocol.h:342
std::optional< LoanDefaultFreezeExemptAccounts > getLoanDefaultFreezeExemptAccounts(ReadView const &view, STTx const &tx)
Resolves the accounts and asset a LoanManage default transaction is exempt from freeze/lock for.
LoanState computeTheoreticalLoanState(Rules const &rules, Number const &periodicPayment, Number const &periodicRate, std::uint32_t const paymentRemaining, TenthBips32 const managementFeeRate)
AccountingDeltas loanPaymentDeltas(SLE::ConstRef vaultSle, LoanPaymentParts const &parts)
constexpr Number abs(Number x) noexcept
Definition Number.h:880
TERSubset< CanCvtToTER > TER
Definition TER.h:657
Number loanVaultExposure(SLE::ConstRef vaultSle, SLE::ConstRef loanSle)
@ tecPRECISION_LOSS
Definition TER.h:374
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
LoanProperties computeLoanProperties(Rules const &rules, Asset const &asset, Number const &principalOutstanding, TenthBips32 interestRate, std::uint32_t paymentInterval, std::uint32_t paymentsRemaining, TenthBips32 managementFeeRate, std::int32_t minimumScale)
AccountingDeltas loanOriginationDeltas(SLE::ConstRef vaultSle, Number const &principalRequested, Number const &interestDue)
TER canApplyToBrokerCover(ReadView const &view, SLE::ConstRef sleBroker, Asset const &vaultAsset, STAmount const &amount, beast::Journal j, std::string_view logPrefix)
Broker cover preclaim precision guard (fixCleanup3_2_0).
@ tesSUCCESS
Definition TER.h:253
UInt256 uint256
Definition base_uint.h:587
Number computeFullPaymentInterest(Number const &theoreticalPrincipalOutstanding, Number const &periodicRate, NetClock::time_point parentCloseTime, std::uint32_t paymentInterval, std::uint32_t prevPaymentDate, std::uint32_t startDate, TenthBips32 closeInterestRate)
This structure captures the parts of a loan state.
T to_string(T... args)