xrpld
Loading...
Searching...
No Matches
LendingHelpers.cpp
1#include <xrpl/ledger/helpers/LendingHelpers.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/chrono.h>
6#include <xrpl/beast/utility/Journal.h>
7#include <xrpl/beast/utility/Zero.h>
8#include <xrpl/beast/utility/instrumentation.h>
9#include <xrpl/ledger/ApplyView.h>
10#include <xrpl/ledger/ReadView.h>
11#include <xrpl/ledger/View.h>
12#include <xrpl/ledger/helpers/VaultHelpers.h>
13#include <xrpl/protocol/Asset.h>
14#include <xrpl/protocol/Feature.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/LedgerFormats.h>
17#include <xrpl/protocol/Protocol.h>
18#include <xrpl/protocol/Rules.h>
19#include <xrpl/protocol/SField.h>
20#include <xrpl/protocol/STAmount.h>
21#include <xrpl/protocol/STLedgerEntry.h>
22#include <xrpl/protocol/STTx.h>
23#include <xrpl/protocol/TER.h>
24#include <xrpl/protocol/TxFlags.h>
25#include <xrpl/protocol/TxFormats.h>
26#include <xrpl/protocol/Units.h>
27
28#include <algorithm>
29#include <cstddef>
30#include <cstdint>
31#include <expected>
32#include <optional>
33#include <string_view>
34#include <utility>
35
36namespace xrpl {
37
38[[nodiscard]] TER
40 ReadView const& view,
41 SLE::ConstRef sleBroker,
42 Asset const& vaultAsset,
43 STAmount const& amount,
45 std::string_view logPrefix)
46{
47 XRPL_ASSERT(
48 sleBroker && sleBroker->getType() == ltLOAN_BROKER,
49 "xrpl::canApplyToBrokerCover : valid LoanBroker sle");
50 XRPL_ASSERT(vaultAsset == amount.asset(), "xrpl::canApplyToBrokerCover : valid asset");
51
52 if (!view.rules().enabled(fixCleanup3_2_0))
53 return tesSUCCESS;
54
55 if (amount == beast::kZero)
56 return tecPRECISION_LOSS;
57
58 int const coverScale = scale(sleBroker->at(sfCoverAvailable), vaultAsset);
59 if (amount.isZeroAtScale(coverScale))
60 {
61 JLOG(j.warn()) << logPrefix << ": amount " << amount.getFullText()
62 << " rounds to zero at cover scale " << coverScale;
63 return tecPRECISION_LOSS;
64 }
65
66 return tesSUCCESS;
67}
68
69namespace detail {
70
71[[nodiscard]] int
73{
74 XRPL_ASSERT(
75 vault && vault->getType() == ltVAULT,
76 "xrpl::detail::getPosteriorBrokerCoverScale : valid Vault sle");
77 XRPL_ASSERT(
78 broker && broker->getType() == ltLOAN_BROKER,
79 "xrpl::detail::getPosteriorBrokerCoverScale : valid LoanBroker sle");
80
82 getVaultVersion(vault),
83 vault->at(sfAsset),
84 getVaultBaseScale(vault),
85 broker->at(sfCoverAvailable),
86 delta);
87}
88
89[[nodiscard]] STAmount
91 SLE::ConstRef vault,
92 SLE::ConstRef broker,
93 STAmount const& delta,
94 Number::RoundingMode roundingMode)
95{
96 XRPL_ASSERT(
97 vault && vault->getType() == ltVAULT,
98 "xrpl::detail::roundToPosteriorBrokerCoverScale : valid Vault sle");
99 XRPL_ASSERT(
100 broker && broker->getType() == ltLOAN_BROKER,
101 "xrpl::detail::roundToPosteriorBrokerCoverScale : valid LoanBroker sle");
102 XRPL_ASSERT(
103 delta.asset() == vault->at(sfAsset),
104 "xrpl::detail::roundToPosteriorBrokerCoverScale : delta and Vault asset match");
105 if (delta.integral())
106 return delta;
107 return roundToScale(delta, getPosteriorBrokerCoverScale(vault, broker, delta), roundingMode);
108}
109
110} // namespace detail
111
112[[nodiscard]] STAmount
114 SLE::ConstRef vault,
115 SLE::ConstRef broker,
116 Number const& raw,
117 Number::RoundingMode roundingMode)
118{
119 XRPL_ASSERT(
120 vault && vault->getType() == ltVAULT,
121 "xrpl::creditToPosteriorBrokerCoverScale : valid Vault sle");
122 XRPL_ASSERT(
123 broker && broker->getType() == ltLOAN_BROKER,
124 "xrpl::creditToPosteriorBrokerCoverScale : valid LoanBroker sle");
125 Asset const asset = vault->at(sfAsset);
126 if (asset.integral())
127 {
128 NumberRoundModeGuard const rg(roundingMode);
129 return STAmount{asset, raw};
130 }
131
132 Number const reference = broker->at(sfCoverAvailable);
134 asset, reference, getVaultBaseScale(vault), raw, roundingMode);
135}
136
137[[nodiscard]] STAmount
139 SLE::ConstRef vault,
140 SLE::ConstRef broker,
141 STAmount const& amount,
142 Number::RoundingMode roundingMode)
143{
144 XRPL_ASSERT(
145 vault && vault->getType() == ltVAULT,
146 "xrpl::debitToPosteriorBrokerCoverScale : valid Vault sle");
147 XRPL_ASSERT(
148 broker && broker->getType() == ltLOAN_BROKER,
149 "xrpl::debitToPosteriorBrokerCoverScale : valid LoanBroker sle");
150 XRPL_ASSERT(
151 amount.asset() == vault->at(sfAsset),
152 "xrpl::debitToPosteriorBrokerCoverScale : amount and Vault asset match");
153 XRPL_ASSERT(!amount.negative(), "xrpl::debitToPosteriorBrokerCoverScale : non-negative amount");
154 return -detail::roundToPosteriorBrokerCoverScale(vault, broker, -amount, roundingMode);
155}
156
157[[nodiscard]] TER
159{
160 XRPL_ASSERT(
161 vault && vault->getType() == ltVAULT,
162 "xrpl::checkOptionalBrokerCoverInflow : valid Vault sle");
163 XRPL_ASSERT(
164 broker && broker->getType() == ltLOAN_BROKER,
165 "xrpl::checkOptionalBrokerCoverInflow : valid LoanBroker sle");
166 XRPL_ASSERT(
167 amount.asset() == vault->at(sfAsset),
168 "xrpl::checkOptionalBrokerCoverInflow : amount and Vault asset match");
169 XRPL_ASSERT(!amount.negative(), "xrpl::checkOptionalBrokerCoverInflow : non-negative amount");
171 return tesSUCCESS;
172
173 // amount is the effective credit (already floored on the posterior
174 // CoverAvailable grid by creditToPosteriorBrokerCoverScale); rounding it
175 // again as a standalone delta could hide a crossing.
176 STAmount const& rounded = amount;
177 int const baseScale = getVaultBaseScale(vault);
178 // Keep this explicit even though the Open-limit capacity check below rejects
179 // every coarsening transition too. The protocol defines both conditions
180 // independently.
181 if (detail::getPosteriorBrokerCoverScale(vault, broker, rounded) != baseScale)
182 return tecLIMIT_EXCEEDED;
183
184 Number const posterior = [&] {
186 return broker->at(sfCoverAvailable) + rounded;
187 }();
188 if (posterior > getVaultOpenLimit(vault))
189 return tecLIMIT_EXCEEDED;
190 return tesSUCCESS;
191}
192
193void
195 SLE::Ref brokerSle,
196 SLE::ConstRef vaultSle,
197 Number const& delta,
198 int vaultScale)
199{
200 // On FixedPrecision Vaults, LoanSet adds principal to DebtTotal exactly, LoanPay and default
201 // subtract exact amounts. Thus DebtTotal must not be rounded coarser than the base scale.
203 {
204 brokerSle->at(sfDebtTotal) += delta;
205 }
206 else
207 {
208 adjustImpreciseNumber(brokerSle->at(sfDebtTotal), delta, vaultSle->at(sfAsset), vaultScale);
209 }
210}
211
212Number
213minimumBrokerCover(Number const& debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
214{
215 XRPL_ASSERT(
216 vaultSle && vaultSle->getType() == ltVAULT, "xrpl::minimumBrokerCover : valid Vault sle");
218 return roundToAsset(
219 vaultSle->at(sfAsset),
220 tenthBipsOfValue(debtTotal, coverRateMinimum),
221 getVaultBaseScale(vaultSle));
222}
223
224bool
226{
227 if (!rules.enabled(featureSingleAssetVault))
228 return false;
229
230 if (!rules.enabled(featureMPTokensV1))
231 return false;
232
233 if (tx.isFieldPresent(sfDomainID) && !rules.enabled(featurePermissionedDomains))
234 return false;
235
236 return true;
237}
238
241{
242 if (tx.getTxnType() != ttLOAN_MANAGE || !tx.isFlag(tfLoanDefault) ||
243 !view.rules().enabled(fixCleanup3_4_0))
244 return std::nullopt;
245
246 // Unlike the broker/vault lookups below, the submitter picks the LoanID,
247 // so a nonexistent Loan is an ordinary (if unusual) input, not a
248 // structural impossibility -- exercised directly in LendingHelpers_test.
249 auto const loanSle = view.read(keylet::loan(tx[sfLoanID]));
250 if (!loanSle)
251 return std::nullopt;
252
253 // A Loan can't outlive its LoanBroker (LoanBrokerDelete's preclaim
254 // rejects deletion while DebtTotal != 0), and a LoanBroker can't outlive
255 // its Vault (VaultDelete's preclaim has the equivalent guard) -- so these
256 // two lookups are structurally guaranteed to succeed here.
257 auto const brokerSle = view.read(keylet::loanBroker(loanSle->at(sfLoanBrokerID)));
258 if (!brokerSle)
259 return std::nullopt; // LCOV_EXCL_LINE
260
261 auto const vaultSle = view.read(keylet::vault(brokerSle->at(sfVaultID)));
262 if (!vaultSle)
263 return std::nullopt; // LCOV_EXCL_LINE
264
265 Asset const vaultAsset = vaultSle->at(sfAsset);
267 .issuer = vaultAsset.getIssuer(),
268 .broker = brokerSle->at(sfAccount),
269 .vault = vaultSle->at(sfAccount),
270 .asset = vaultAsset,
271 };
272}
273
274LoanPaymentParts&
276{
277 XRPL_ASSERT(
278
280 "xrpl::LoanPaymentParts::operator+= : other principal "
281 "non-negative");
282 XRPL_ASSERT(
283 other.interestPaid >= beast::kZero,
284 "xrpl::LoanPaymentParts::operator+= : other interest paid "
285 "non-negative");
286 XRPL_ASSERT(
287 other.feePaid >= beast::kZero,
288 "xrpl::LoanPaymentParts::operator+= : other fee paid "
289 "non-negative");
290
292 interestPaid += other.interestPaid;
293 valueChange += other.valueChange;
294 feePaid += other.feePaid;
295 return *this;
296}
297
298bool
300{
301 return principalPaid == other.principalPaid && interestPaid == other.interestPaid &&
302 valueChange == other.valueChange && feePaid == other.feePaid;
303}
304
305/* Converts annualized interest rate to per-payment-period rate.
306 * The rate is prorated based on the payment interval in seconds.
307 *
308 * Equation (1) from XLS-66 spec, Section A-2 Equation Glossary
309 */
310Number
311loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval)
312{
313 // Need floating point math, since we're dividing by a large number
314 return tenthBipsOfValue(Number(paymentInterval), interestRate) / kSecondsInYear;
315}
316
317/* Checks if a value is already rounded to the specified scale.
318 * Returns true if rounding down and rounding up produce the same result,
319 * indicating no further precision exists beyond the scale.
320 */
321bool
322isRounded(Asset const& asset, Number const& value, std::int32_t scale)
323{
324 return roundToAsset(asset, value, scale, Number::RoundingMode::Downward) ==
326}
327
328[[nodiscard]] bool
330{
331 return hasExpired(
332 view,
333 loanSle->at(sfNextPaymentDueDate),
334 view.rules().enabled(fixCleanup3_4_0) ? ExpiryComparison::Exclusive
336}
337
338namespace instant_recognition {
339
340AccountingDeltas
341loanOriginationDeltas(Number const& principalRequested, Number const& interestDue)
342{
343 return {.assetsTotalDelta = interestDue, .debtTotalDelta = principalRequested + interestDue};
344}
345
346bool
348 Number const& vaultMaximum,
349 Number const& vaultTotal,
350 Number const& interestDue)
351{
352 return vaultMaximum != 0 && interestDue > vaultMaximum - vaultTotal;
353}
354
355/*
356XLS-66 section 3.2.3.2, defines the default amount as
357
358DefaultAmount = (Loan.PrincipalOutstanding + Loan.InterestOutstanding)
359
360Which is equivalent to (Loan.TotalValueOutstanding - Loan.ManagementFeeOutstanding)
361*/
362Number
364{
365 return loanSle->at(sfTotalValueOutstanding) - loanSle->at(sfManagementFeeOutstanding);
366}
367
370{
371 return {
372 .assetsTotalDelta = parts.valueChange,
373 .debtTotalDelta = (parts.principalPaid + parts.interestPaid) - parts.valueChange,
374 };
375}
376
377} // namespace instant_recognition
378
379namespace cash_basis {
380
381AccountingDeltas
382loanOriginationDeltas(Number const& principalRequested)
383{
384 return {.assetsTotalDelta = kNumZero, .debtTotalDelta = principalRequested};
385}
386
387/*
388 * Under CashBasis accounting, Loan default amount is:
389 *
390 * DefaultAmount = Loan.PrincipalOutstanding
391 */
392Number
394{
395 return loanSle->at(sfPrincipalOutstanding);
396}
397
400{
401 return {.assetsTotalDelta = parts.interestPaid, .debtTotalDelta = parts.principalPaid};
402}
403
404} // namespace cash_basis
405
406namespace {
407
408// Cash-basis accounting applies to Vaults created under
409// featureLendingProtocolV1_1 or a later version. Vaults created before
410// activation keep instant interest recognition forever.
411bool
412cashBasisEnabled(SLE::ConstRef vaultSle)
413{
414 return getVaultVersion(vaultSle) >= VaultVersion::CashBasis;
415}
416
417} // namespace
418
421 SLE::ConstRef vaultSle,
422 Number const& principalRequested,
423 Number const& interestDue)
424{
425 return cashBasisEnabled(vaultSle)
426 ? cash_basis::loanOriginationDeltas(principalRequested)
427 : instant_recognition::loanOriginationDeltas(principalRequested, interestDue);
428}
429
430bool
432 SLE::ConstRef vaultSle,
433 Number const& vaultTotal,
434 Number const& interestDue)
435{
436 // Cash-basis origination doesn't recognize interest into AssetsTotal, so
437 // interest due can never push the vault past AssetsMaximum at origination.
438 if (cashBasisEnabled(vaultSle))
439 return false;
440
441 auto const vaultMaximum = vaultSle->at(sfAssetsMaximum);
443 vaultMaximum, vaultTotal, interestDue);
444}
445
446Number
448{
449 return cashBasisEnabled(vaultSle) ? cash_basis::loanVaultExposure(loanSle)
451}
452
453AccountingDeltas
455{
456 return cashBasisEnabled(vaultSle) ? cash_basis::loanPaymentDeltas(parts)
458}
459
460namespace detail {
461
462void
472
473/* Computes (1 + r)^n - 1 accurately even for near-zero r, where direct
474 * subtraction of `power(1 + r, n) - 1` suffers catastrophic cancellation.
475 *
476 * The binomial expansion gives
477 * (1 + r)^n - 1 = sum_{k=1}^{n} C(n,k) r^k
478 * = nr + C(n,2) r^2 + ... + r^n
479 * which is a sum of positive terms when r >= 0, avoiding cancellation.
480 * Each term is computed from the previous via
481 * term_{k+1} = term_k * r * (n - k) / (k + 1)
482 *
483 * The loop terminates early once the next term is below Number precision.
484 */
485Number
486computePowerMinusOne(Number const& periodicRate, std::uint32_t paymentsRemaining)
487{
488 XRPL_ASSERT_PARTS(
489 periodicRate >= beast::kZero,
490 "xrpl::detail::computePowerMinusOne",
491 "periodicRate is non-negative");
492
493 if (paymentsRemaining == 0 || periodicRate == beast::kZero)
494 return kNumZero;
495
496 // k = 1 term: C(n, 1) * r = n * r
497 Number term = paymentsRemaining * periodicRate;
498 Number sum = term;
499 for (std::uint32_t k = 1; k < paymentsRemaining; ++k)
500 {
501 // term_{k+1} from term_k: multiply by r * (n - k) / (k + 1)
502 term = term * periodicRate * (paymentsRemaining - k) / (k + 1);
503 Number const next = sum + term;
504 // adding this term fell below Number's precision
505 if (next == sum)
506 break;
507 sum = next;
508 }
509 return sum;
510}
511
512/* Hybrid evaluator of (1 + r)^n - 1.
513 *
514 * The closed-form `power(1 + r, n) - 1` loses sig digits to cancellation
515 * when `r * n` is small: the result `~r*n` sits well below the `1` that
516 * dominates `(1+r)^n`, so most of Number's stored precision is consumed
517 * by the leading `1`.
518 *
519 * A threshold of `1e-9` preserves the closed-form path for any rate the
520 * lending code actually sees in practice (fixtures at moderate rates are bit-exact),
521 * while routing the pathological near-zero regime through the binomial
522 * expansion where cancellation is severe.
523 */
524Number
525computePowerMinusOneHybrid(Number const& periodicRate, std::uint32_t paymentsRemaining)
526{
527 XRPL_ASSERT_PARTS(
528 periodicRate >= beast::kZero,
529 "xrpl::detail::computePowerMinusOneHybrid",
530 "periodicRate is non-negative");
531
532 if (paymentsRemaining == 0 || periodicRate == beast::kZero)
533 return kNumZero;
534
535 // Threshold 1e-9 retains ~10 sig digits of (1+r)^n - 1 against
536 // Number's 19-digit mantissa: the leading "1" of (1+r)^n consumes
537 // ~log10(1/(r*n)) digits before the subtraction. Above this point
538 // closed form is accurate and ~30-500x faster than the binomial
539 // expansion.
540 Number const cancellationThreshold{1, -9};
541 if (paymentsRemaining * periodicRate >= cancellationThreshold)
542 return power(1 + periodicRate, paymentsRemaining) - 1;
543
544 return computePowerMinusOne(periodicRate, paymentsRemaining);
545}
546
547/* Computes the payment factor used in standard amortization formulas.
548 * This factor converts principal to periodic payment amount.
549 *
550 * Equation (6) from XLS-66 spec, Section A-2 Equation Glossary
551 */
552Number
554 Rules const& rules,
555 Number const& periodicRate,
556 std::uint32_t paymentsRemaining)
557{
558 if (paymentsRemaining == 0)
559 return kNumZero;
560
561 // For zero interest, payment factor is simply 1/paymentsRemaining
562 if (periodicRate == beast::kZero)
563 return Number{1} / paymentsRemaining;
564
565 if (rules.enabled(fixCleanup3_2_0))
566 {
567 Number const raisedRateMinusOne =
568 computePowerMinusOneHybrid(periodicRate, paymentsRemaining);
569 Number const raisedRate = 1 + raisedRateMinusOne;
570
571 return (periodicRate * raisedRate) / raisedRateMinusOne;
572 }
573
574 // Pre-fixCleanup3_2_0: direct subtraction `(1+r)^n - 1` suffers
575 // catastrophic cancellation at near-zero rates. Retained for
576 // amendment-gated bit-exact pre-fix behavior.
577 Number const raisedRate = power(1 + periodicRate, paymentsRemaining);
578
579 return (periodicRate * raisedRate) / (raisedRate - 1);
580}
581
582/* Calculates the periodic payment amount using standard amortization formula.
583 * For interest-free loans, returns principal divided equally across payments.
584 *
585 * Equation (7) from XLS-66 spec, Section A-2 Equation Glossary
586 */
587Number
589 Rules const& rules,
590 Number const& principalOutstanding,
591 Number const& periodicRate,
592 std::uint32_t paymentsRemaining)
593{
594 if (principalOutstanding == 0 || paymentsRemaining == 0)
595 return 0;
596
597 // Interest-free loans: equal principal payments
598 if (periodicRate == beast::kZero)
599 return principalOutstanding / paymentsRemaining;
600
601 return principalOutstanding * computePaymentFactor(rules, periodicRate, paymentsRemaining);
602}
603
604/* Reverse-calculates principal from periodic payment amount.
605 * Used to determine theoretical principal at any point in the schedule.
606 *
607 * Equation (10) from XLS-66 spec, Section A-2 Equation Glossary
608 */
609Number
611 Rules const& rules,
612 Number const& periodicPayment,
613 Number const& periodicRate,
614 std::uint32_t paymentsRemaining)
615{
616 if (paymentsRemaining == 0)
617 return kNumZero;
618
619 if (periodicRate == 0)
620 return periodicPayment * paymentsRemaining;
621
622 return periodicPayment / computePaymentFactor(rules, periodicRate, paymentsRemaining);
623}
624
625/*
626 * Computes the interest and management fee parts from interest amount.
627 *
628 * Equation (33) from XLS-66 spec, Section A-2 Equation Glossary
629 */
632 Asset const& asset,
633 Number const& interest,
634 TenthBips16 managementFeeRate,
635 std::int32_t loanScale)
636{
637 auto const fee = computeManagementFee(asset, interest, managementFeeRate, loanScale);
638
639 return std::make_pair(interest - fee, fee);
640}
641
642/* Rounds a raw (unrounded) interest amount to the loan's scale, then splits
643 * the rounded amount into net interest (to the vault) and management fee (to
644 * the broker).
645 *
646 * This is the common "round then split" step shared by late payment, full
647 * payment, and overpayment interest calculations.
648 */
651 Asset const& asset,
652 Number const& rawInterest,
653 TenthBips16 managementFeeRate,
654 std::int32_t loanScale,
656{
657 auto const interest = roundToAsset(asset, rawInterest, loanScale, mode);
658 return computeInterestAndFeeParts(asset, interest, managementFeeRate, loanScale);
659}
660
661/* Calculates penalty interest accrued on overdue payments.
662 * Returns 0 if payment is not late.
663 *
664 * Equation (16) from XLS-66 spec, Section A-2 Equation Glossary
665 */
666Number
668 Number const& principalOutstanding,
669 TenthBips32 lateInterestRate,
670 NetClock::time_point parentCloseTime,
671 std::uint32_t nextPaymentDueDate)
672{
673 if (principalOutstanding == beast::kZero)
674 return kNumZero;
675
676 if (lateInterestRate == TenthBips32{0})
677 return kNumZero;
678
679 auto const now = parentCloseTime.time_since_epoch().count();
680
681 // If the payment is not late by any amount of time, then there's no late
682 // interest
683 if (now <= nextPaymentDueDate)
684 return kNumZero;
685
686 // Equation (3) from XLS-66 spec, Section A-2 Equation Glossary
687 auto const secondsOverdue = now - nextPaymentDueDate;
688
689 auto const rate = loanPeriodicRate(lateInterestRate, secondsOverdue);
690
691 return principalOutstanding * rate;
692}
693
694/* Calculates interest accrued since the last payment based on time elapsed.
695 * Returns 0 if loan is paid ahead of schedule.
696 *
697 * Equation (27) from XLS-66 spec, Section A-2 Equation Glossary
698 */
699Number
701 Number const& principalOutstanding,
702 Number const& periodicRate,
703 NetClock::time_point parentCloseTime,
704 std::uint32_t startDate,
705 std::uint32_t prevPaymentDate,
706 std::uint32_t paymentInterval)
707{
708 if (periodicRate == beast::kZero)
709 return kNumZero;
710
711 if (paymentInterval == 0)
712 return kNumZero;
713
714 auto const lastPaymentDate = std::max(prevPaymentDate, startDate);
715 auto const now = parentCloseTime.time_since_epoch().count();
716
717 // If the loan has been paid ahead, then "lastPaymentDate" is in the future,
718 // and no interest has accrued.
719 if (now <= lastPaymentDate)
720 return kNumZero;
721
722 // Equation (4) from XLS-66 spec, Section A-2 Equation Glossary
723 auto const secondsSinceLastPayment = now - lastPaymentDate;
724
725 // Division is more likely to introduce rounding errors, which will then get
726 // amplified by multiplication. Therefore, we first multiply, and only then
727 // divide.
728 return principalOutstanding * periodicRate * secondsSinceLastPayment / paymentInterval;
729}
730
731/* Applies a payment to the loan state and returns the breakdown of amounts
732 * paid.
733 *
734 * This is the core function that updates the Loan ledger object fields based on
735 * a computed payment.
736 */
739{
740 auto totalValueOutstandingProxy = loan->at(sfTotalValueOutstanding);
741 auto principalOutstandingProxy = loan->at(sfPrincipalOutstanding);
742 auto managementFeeOutstandingProxy = loan->at(sfManagementFeeOutstanding);
743 auto paymentRemainingProxy = loan->at(sfPaymentRemaining);
744 auto prevPaymentDateProxy = loan->at(sfPreviousPaymentDueDate);
745 auto nextDueDateProxy = loan->at(sfNextPaymentDueDate);
746 std::uint32_t const paymentInterval = loan->at(sfPaymentInterval);
747
748 XRPL_ASSERT_PARTS(nextDueDateProxy, "xrpl::detail::doPayment", "Next due date proxy set");
749
751 {
752 XRPL_ASSERT_PARTS(
753 principalOutstandingProxy == payment.trackedPrincipalDelta,
754 "xrpl::detail::doPayment",
755 "Full principal payment");
756 XRPL_ASSERT_PARTS(
757 totalValueOutstandingProxy == payment.trackedValueDelta,
758 "xrpl::detail::doPayment",
759 "Full value payment");
760 XRPL_ASSERT_PARTS(
761 managementFeeOutstandingProxy == payment.trackedManagementFeeDelta,
762 "xrpl::detail::doPayment",
763 "Full management fee payment");
764
765 // Mark the loan as complete
766 paymentRemainingProxy = 0;
767
768 // Record when the final payment was made
769 prevPaymentDateProxy = *nextDueDateProxy;
770
771 // Clear the next due date. Setting it to 0 causes
772 // it to be removed from the Loan ledger object, saving space.
773 nextDueDateProxy = 0;
774
775 // Zero out all tracked loan balances to mark the loan as paid off.
776 // These will be removed from the Loan object since they're default
777 // values.
778 principalOutstandingProxy = 0;
779 totalValueOutstandingProxy = 0;
780 managementFeeOutstandingProxy = 0;
781 }
782 else
783 {
784 // For regular payments (not overpayments), advance the payment schedule
786 {
787 paymentRemainingProxy -= 1;
788
789 prevPaymentDateProxy = nextDueDateProxy;
790 nextDueDateProxy += paymentInterval;
791 }
792 XRPL_ASSERT_PARTS(
793 principalOutstandingProxy > payment.trackedPrincipalDelta,
794 "xrpl::detail::doPayment",
795 "Partial principal payment");
796 XRPL_ASSERT_PARTS(
797 totalValueOutstandingProxy > payment.trackedValueDelta,
798 "xrpl::detail::doPayment",
799 "Partial value payment");
800 // Management fees are expected to be relatively small, and could get to
801 // zero before the loan is paid off
802 XRPL_ASSERT_PARTS(
803 managementFeeOutstandingProxy >= payment.trackedManagementFeeDelta,
804 "xrpl::detail::doPayment",
805 "Valid management fee");
806
807 // Apply the payment deltas to reduce the outstanding balances
808 principalOutstandingProxy -= payment.trackedPrincipalDelta;
809 totalValueOutstandingProxy -= payment.trackedValueDelta;
810 managementFeeOutstandingProxy -= payment.trackedManagementFeeDelta;
811 }
812
813 // Principal can never exceed total value (principal is part of total value)
814 XRPL_ASSERT_PARTS(
815 static_cast<Number>(principalOutstandingProxy) <=
816 static_cast<Number>(totalValueOutstandingProxy),
817 "xrpl::detail::doPayment",
818 "principal does not exceed total");
819
820 XRPL_ASSERT_PARTS(
821 static_cast<Number>(managementFeeOutstandingProxy) >= beast::kZero,
822 "xrpl::detail::doPayment",
823 "fee outstanding stays valid");
824
825 return LoanPaymentParts{
826 // Principal paid is straightforward - it's the tracked delta
827 .principalPaid = payment.trackedPrincipalDelta,
828
829 // Interest paid combines:
830 // 1. Tracked interest from the amortization schedule
831 // (derived from the tracked deltas)
832 // 2. Untracked interest (e.g., late payment penalties)
833 .interestPaid = payment.trackedInterestPart() + payment.untrackedInterest,
834
835 // Value change represents how the loan's total value changed beyond
836 // normal amortization.
837 .valueChange = payment.untrackedInterest,
838
839 // Fee paid combines:
840 // 1. Tracked management fees from the amortization schedule
841 // 2. Untracked fees (e.g., late payment fees, service fees)
842 .feePaid = payment.trackedManagementFeeDelta + payment.untrackedManagementFee,
843 };
844}
845
846/* Simulates an overpayment to validate it won't break the loan's amortization.
847 *
848 * When a borrower pays more than the scheduled amount, the loan needs to be
849 * re-amortized with a lower principal. This function performs that calculation
850 * in a "sandbox" using temporary variables, allowing the caller to validate
851 * the result before committing changes to the actual ledger.
852 *
853 * The function preserves accumulated rounding errors across the re-amortization
854 * to ensure the loan state remains consistent with its payment history.
855 */
856std::expected<std::pair<LoanPaymentParts, LoanProperties>, TER>
858 Rules const& rules,
859 Asset const& asset,
860 std::int32_t loanScale,
861 ExtendedPaymentComponents const& overpaymentComponents,
862 LoanState const& roundedOldState,
863 Number const& periodicPayment,
864 Number const& periodicRate,
865 std::uint32_t paymentRemaining,
866 TenthBips16 const managementFeeRate,
868{
869 // Calculate what the loan state SHOULD be theoretically (at full precision)
870 auto const theoreticalState = computeTheoreticalLoanState(
871 rules, periodicPayment, periodicRate, paymentRemaining, managementFeeRate);
872
873 // Calculate the accumulated rounding errors. These need to be preserved
874 // across the re-amortization to maintain consistency with the loan's
875 // payment history. Without preserving these errors, the loan could end
876 // up with a different total value than what the borrower has actually paid.
877 auto const errors = roundedOldState - theoreticalState;
878
879 // Compute the new principal by applying the overpayment to the theoretical
880 // principal. Use max with 0 to ensure we never go negative.
881 auto const newTheoreticalPrincipal = std::max(
882 theoreticalState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta,
883 Number{0});
884
885 // Compute new loan properties based on the reduced principal. This
886 // recalculates the periodic payment, total value, and management fees
887 // for the remaining payment schedule.
888 auto newLoanProperties = computeLoanProperties(
889 rules,
890 asset,
891 newTheoreticalPrincipal,
892 periodicRate,
893 paymentRemaining,
894 managementFeeRate,
895 loanScale);
896
897 JLOG(j.debug()) << "new periodic payment: " << newLoanProperties.periodicPayment
898 << ", new total value: " << newLoanProperties.loanState.valueOutstanding
899 << ", first payment principal: " << newLoanProperties.firstPaymentPrincipal;
900
901 // Calculate what the new loan state should be with the new periodic payment,
902 // including the preserved rounding errors.
903
904 auto const newTheoreticalState = [&] {
905 auto const state = computeTheoreticalLoanState(
906 rules,
907 newLoanProperties.periodicPayment,
908 periodicRate,
909 paymentRemaining,
910 managementFeeRate) +
911 errors;
912
913 if (!rules.enabled(fixCleanup3_2_0))
914 return state;
915
916 // The new principal is known exactly: it is reduced by the overpayment's
917 // principal portion. computeTheoreticalLoanState instead derives the
918 // principal -- and, from it, the management fee and interest -- via a
919 // lossy (P * factor) / factor round-trip. Pin the principal to the exact
920 // value and re-derive the management fee from the exact interest gross
921 // (value - principal), so the intermediate state is fully consistent with
922 // the exact principal rather than the one-scale-unit-high round-trip.
923 Number const principal =
924 roundedOldState.principalOutstanding - overpaymentComponents.trackedPrincipalDelta;
925 Number const managementFee =
926 tenthBipsOfValue(state.valueOutstanding - principal, managementFeeRate);
927 return constructLoanState(state.valueOutstanding, principal, managementFee);
928 }();
929
930 JLOG(j.debug()) << "new theoretical value: " << newTheoreticalState.valueOutstanding
931 << ", principal: " << newTheoreticalState.principalOutstanding
932 << ", interest gross: " << newTheoreticalState.interestOutstanding();
933
934 // Update the loan state variables with the new values that include the
935 // preserved rounding errors. This ensures the loan's tracked state remains
936 // consistent with its payment history.
937 auto const principalOutstanding = std::clamp(
939 asset,
940 newTheoreticalState.principalOutstanding,
941 loanScale,
943 kNumZero,
944 roundedOldState.principalOutstanding);
945 auto const totalValueOutstanding = std::clamp(
947 asset,
948 principalOutstanding + newTheoreticalState.interestOutstanding(),
949 loanScale,
951 kNumZero,
952 roundedOldState.valueOutstanding);
953 auto const managementFeeOutstanding = std::clamp(
954 roundToAsset(asset, newTheoreticalState.managementFeeDue, loanScale),
955 kNumZero,
956 roundedOldState.managementFeeDue);
957
958 auto const roundedNewState =
959 constructLoanState(totalValueOutstanding, principalOutstanding, managementFeeOutstanding);
960
961 // Update newLoanProperties so that checkLoanGuards can make an accurate
962 // evaluation.
963 newLoanProperties.loanState = roundedNewState;
964
965 JLOG(j.debug()) << "new rounded value: " << roundedNewState.valueOutstanding
966 << ", principal: " << roundedNewState.principalOutstanding
967 << ", interest gross: " << roundedNewState.interestOutstanding();
968
969 // check that the loan is still valid
970 if (auto const ter = checkLoanGuards(
971 asset,
972 principalOutstanding,
973 // The loan may have been created with interest, but for
974 // small interest amounts, that may have already been paid
975 // off. Check what's still outstanding. This should
976 // guarantee that the interest checks pass.
977 roundedNewState.interestOutstanding() != beast::kZero,
978 paymentRemaining,
979 newLoanProperties,
980 j))
981 {
982 JLOG(j.warn()) << "Principal overpayment would cause the loan to be in "
983 "an invalid state. Ignore the overpayment";
984
986 }
987
988 // Validate that all computed properties are reasonable. These checks should
989 // never fail under normal circumstances, but we validate defensively.
990 if (newLoanProperties.periodicPayment <= 0 ||
991 newLoanProperties.loanState.valueOutstanding <= 0 ||
992 newLoanProperties.loanState.managementFeeDue < 0)
993 {
994 // LCOV_EXCL_START
995 JLOG(j.warn()) << "Overpayment not allowed: Computed loan "
996 "properties are invalid. Does "
997 "not compute. TotalValueOutstanding: "
998 << newLoanProperties.loanState.valueOutstanding
999 << ", PeriodicPayment : " << newLoanProperties.periodicPayment
1000 << ", ManagementFeeOwedToBroker: "
1001 << newLoanProperties.loanState.managementFeeDue;
1003 // LCOV_EXCL_STOP
1004 }
1005
1006 auto const deltas = roundedOldState - roundedNewState;
1007
1008 // The change in loan management fee is equal to the change between the old
1009 // and the new outstanding management fees
1010 XRPL_ASSERT_PARTS(
1011 deltas.managementFee == roundedOldState.managementFeeDue - managementFeeOutstanding,
1012 "xrpl::detail::tryOverpayment",
1013 "no fee change");
1014
1015 // Calculate how the loan's value changed due to the overpayment.
1016 // This should be negative (value decreased) or zero. A principal
1017 // overpayment should never increase the loan's value.
1018 // The value change is derived from the reduction in interest due to
1019 // the lower principal.
1020 // We do not consider the change in management fee here, since
1021 // management fees are excluded from the valueOutstanding.
1022 auto const valueChange = -deltas.interest;
1023 if (valueChange > 0)
1024 {
1025 JLOG(j.warn()) << "Principal overpayment would increase the value of "
1026 "the loan. Ignore the overpayment";
1028 }
1029
1030 return std::make_pair(
1032 // Principal paid is the reduction in principal outstanding
1033 .principalPaid = deltas.principal,
1034 // Interest paid is the reduction in interest due
1035 .interestPaid = overpaymentComponents.untrackedInterest,
1036 // Value change includes both the reduction from paying down
1037 // principal (negative) and any untracked interest penalties
1038 // (positive, e.g., if the overpayment itself incurs a fee)
1039 .valueChange = valueChange + overpaymentComponents.untrackedInterest,
1040 // Fee paid includes both the reduction in tracked management fees
1041 // and any untracked fees on the overpayment itself
1042 .feePaid = overpaymentComponents.untrackedManagementFee +
1043 overpaymentComponents.trackedManagementFeeDelta,
1044 },
1045 newLoanProperties);
1046}
1047
1048/* Validates and applies an overpayment to the loan state.
1049 *
1050 * This function acts as a wrapper around tryOverpayment(), performing the
1051 * re-amortization calculation in a sandbox (using temporary copies of the
1052 * loan state), then validating the results before committing them to the
1053 * actual ledger via the proxy objects.
1054 *
1055 * The two-step process (try in sandbox, then commit) ensures that if the
1056 * overpayment would leave the loan in an invalid state, we can reject it
1057 * gracefully without corrupting the ledger data.
1058 */
1059std::expected<LoanPaymentParts, TER>
1061 Rules const& rules,
1062 Asset const& asset,
1063 std::int32_t loanScale,
1064 ExtendedPaymentComponents const& overpaymentComponents,
1065 SLE::Ref loan,
1066 Number const& periodicRate,
1067 TenthBips16 const managementFeeRate,
1069{
1070 auto totalValueOutstandingProxy = loan->at(sfTotalValueOutstanding);
1071 auto principalOutstandingProxy = loan->at(sfPrincipalOutstanding);
1072 auto managementFeeOutstandingProxy = loan->at(sfManagementFeeOutstanding);
1073 auto periodicPaymentProxy = loan->at(sfPeriodicPayment);
1074 auto const paymentsRemaining = loan->at(sfPaymentRemaining);
1075
1076 auto const loanState = constructLoanState(
1077 totalValueOutstandingProxy, principalOutstandingProxy, managementFeeOutstandingProxy);
1078 auto const periodicPayment = periodicPaymentProxy;
1079 JLOG(j.debug()) << "overpayment components:"
1080 << ", totalValue before: " << *totalValueOutstandingProxy
1081 << ", valueDelta: " << overpaymentComponents.trackedValueDelta
1082 << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta
1083 << ", managementFeeDelta: " << overpaymentComponents.trackedManagementFeeDelta
1084 << ", interestPart: " << overpaymentComponents.trackedInterestPart()
1085 << ", untrackedInterest: " << overpaymentComponents.untrackedInterest
1086 << ", totalDue: " << overpaymentComponents.totalDue
1087 << ", payments remaining :" << paymentsRemaining;
1088
1089 // Attempt to re-amortize the loan with the overpayment applied.
1090 // This modifies the temporary copies, leaving the proxies unchanged.
1091 auto const ret = tryOverpayment(
1092 rules,
1093 asset,
1094 loanScale,
1095 overpaymentComponents,
1096 loanState,
1097 periodicPayment,
1098 periodicRate,
1099 paymentsRemaining,
1100 managementFeeRate,
1101 j);
1102 if (!ret)
1103 return std::unexpected(ret.error());
1104
1105 auto const& [loanPaymentParts, newLoanProperties] = *ret;
1106 auto const newRoundedLoanState = newLoanProperties.loanState;
1107
1108 // Safety check: the principal must have decreased. If it didn't (or
1109 // increased!), something went wrong in the calculation and we should
1110 // reject the overpayment.
1111 if (principalOutstandingProxy <= newRoundedLoanState.principalOutstanding)
1112 {
1113 // LCOV_EXCL_START
1114 JLOG(j.warn()) << "Overpayment not allowed: principal "
1115 << "outstanding did not decrease. Before: " << *principalOutstandingProxy
1116 << ". After: " << newRoundedLoanState.principalOutstanding;
1118 // LCOV_EXCL_STOP
1119 }
1120
1121 // The proxies still hold the original (pre-overpayment) values, which
1122 // allows us to compute deltas and verify they match what we expect
1123 // from the overpaymentComponents and loanPaymentParts.
1124 JLOG(j.debug()) << "valueChange: " << loanPaymentParts.valueChange
1125 << ", totalValue before: " << *totalValueOutstandingProxy
1126 << ", totalValue after: " << newRoundedLoanState.valueOutstanding
1127 << ", totalValue delta: "
1128 << (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding)
1129 << ", principalDelta: " << overpaymentComponents.trackedPrincipalDelta
1130 << ", principalPaid: " << loanPaymentParts.principalPaid
1131 << ", Computed difference: "
1132 << overpaymentComponents.trackedPrincipalDelta -
1133 (totalValueOutstandingProxy - newRoundedLoanState.valueOutstanding);
1134
1135 // The three assertions below are invariants that only hold once
1136 // fixCleanup3_2_0 pins the new principal to the exact reduction
1137 // (oldPrincipal - trackedPrincipalDelta). Before the amendment, the lossy
1138 // (P * factor) / factor round-trip can leave the new principal one
1139 // scale-unit high, so these equalities do not hold on the pre-amendment
1140 // code path and must be gated to match the fix they verify.
1141 //
1142 // The valueChange returned by tryOverpayment satisfies
1143 // valueChange = (newInterestDue - oldInterestDue) + untrackedInterest.
1144 // Using the loan-state identity v = p + i + m and the adjacent
1145 // `principal change agrees` assertion (dp = oldP - newP), this
1146 // rearranges into three independently-computable terms:
1147 //
1148 // 1. TVO change beyond what principal repayment alone explains:
1149 // newTVO - (oldTVO - dp)
1150 // 2. Management fee released by re-amortization (positive when
1151 // mfee decreased; zero when managementFeeRate == 0):
1152 // oldMfee - newMfee
1153 // 3. The overpayment's penalty interest part (= untrackedInterest
1154 // for the overpayment path; see computeOverpaymentComponents):
1155 // trackedInterestPart()
1156 [[maybe_unused]] bool const fix320Enabled = rules.enabled(fixCleanup3_2_0);
1157 XRPL_ASSERT_IF(
1158 fix320Enabled,
1159 overpaymentComponents.trackedPrincipalDelta ==
1160 principalOutstandingProxy - newRoundedLoanState.principalOutstanding,
1161 "xrpl::detail::doOverpayment : principal change agrees");
1162
1163 XRPL_ASSERT_IF(
1164 fix320Enabled,
1165 [&] {
1166 Number const tvoChange = newRoundedLoanState.valueOutstanding -
1167 (totalValueOutstandingProxy - overpaymentComponents.trackedPrincipalDelta);
1168 Number const managementFeeReleased =
1169 managementFeeOutstandingProxy - newRoundedLoanState.managementFeeDue;
1170 Number const interestPart = overpaymentComponents.trackedInterestPart();
1171 return loanPaymentParts.valueChange == tvoChange + managementFeeReleased + interestPart;
1172 }(),
1173 "xrpl::detail::doOverpayment : interest paid agrees");
1174
1175 XRPL_ASSERT_IF(
1176 fix320Enabled,
1177 overpaymentComponents.trackedPrincipalDelta == loanPaymentParts.principalPaid,
1178 "xrpl::detail::doOverpayment : principal payment matches");
1179
1180 // All validations passed, so update the proxy objects (which will
1181 // modify the actual Loan ledger object)
1182 totalValueOutstandingProxy = newRoundedLoanState.valueOutstanding;
1183 principalOutstandingProxy = newRoundedLoanState.principalOutstanding;
1184 managementFeeOutstandingProxy = newRoundedLoanState.managementFeeDue;
1185 periodicPaymentProxy = newLoanProperties.periodicPayment;
1186
1187 return loanPaymentParts;
1188}
1189
1190/* Computes the payment components for a late payment.
1191 *
1192 * A late payment is made after the grace period has expired and includes:
1193 * 1. All components of a regular periodic payment
1194 * 2. Late payment penalty interest (accrued since the due date)
1195 * 3. Late payment fee charged by the broker
1196 *
1197 * The late penalty interest increases the loan's total value (the borrower
1198 * owes more than scheduled), while the regular payment components follow
1199 * the normal amortization schedule.
1200 *
1201 * Implements equation (15) from XLS-66 spec, Section A-2 Equation Glossary
1202 */
1203std::expected<ExtendedPaymentComponents, TER>
1205 Asset const& asset,
1206 ReadView const& view,
1207 SLE::ConstRef loan,
1208 ExtendedPaymentComponents const& periodic,
1209 STAmount const& amount,
1210 TenthBips16 managementFeeRate,
1212{
1213 std::int32_t const nextDueDate = loan->at(sfNextPaymentDueDate);
1214 std::int32_t const loanScale = loan->at(sfLoanScale);
1215
1216 // Check if the due date has passed. If not, reject the payment as
1217 // being too soon. Uses isPaymentLate() so this agrees with the
1218 // regular payment path on whether the loan is actually late at the
1219 // exact due date boundary (amendment-gated: Exclusive once
1220 // fixCleanup3_4_0 is enabled, Inclusive otherwise).
1221 if (!isPaymentLate(view, loan))
1223
1224 // Calculate the penalty interest based on how long the payment is overdue.
1225 auto const latePaymentInterest = loanLatePaymentInterest(
1226 loan->at(sfPrincipalOutstanding),
1227 TenthBips32{loan->at(sfLateInterestRate)},
1228 view.parentCloseTime(),
1229 nextDueDate);
1230
1231 // Round the late interest and split it between the vault (net interest)
1232 // and the broker (management fee portion).
1233 auto const [roundedLateInterest, roundedLateManagementFee] =
1234 roundAndSplitInterest(asset, latePaymentInterest, managementFeeRate, loanScale);
1235
1236 XRPL_ASSERT(roundedLateInterest >= 0, "xrpl::detail::computeLatePayment : valid late interest");
1237 XRPL_ASSERT_PARTS(
1239 "xrpl::detail::computeLatePayment",
1240 "no extra parts to this payment");
1241
1242 // Create the late payment components by copying the regular periodic
1243 // payment and adding the late penalties. We use a lambda to construct
1244 // this to keep the logic clear. This preserves all the other fields without
1245 // having to enumerate them.
1246
1247 ExtendedPaymentComponents const late{
1248 periodic,
1249 // Untracked management fee includes:
1250 // 1. Regular service fee (from periodic.untrackedManagementFee)
1251 // 2. Late payment fee (fixed penalty)
1252 // 3. Management fee portion of late interest
1253 periodic.untrackedManagementFee + loan->at(sfLatePaymentFee) + roundedLateManagementFee,
1254
1255 // Untracked interest includes:
1256 // 1. Any untracked interest from the regular payment (usually 0)
1257 // 2. Late penalty interest (increases loan value)
1258 // This positive value indicates the loan's value increased due
1259 // to the late payment.
1260 periodic.untrackedInterest + roundedLateInterest};
1261
1262 XRPL_ASSERT_PARTS(
1263 isRounded(asset, late.totalDue, loanScale),
1264 "xrpl::detail::computeLatePayment",
1265 "total due is rounded");
1266
1267 // Check that the borrower provided enough funds to cover the late payment.
1268 // The late payment is more expensive than a regular payment due to the
1269 // penalties.
1270 if (amount < late.totalDue)
1271 {
1272 JLOG(j.warn()) << "Late loan payment amount is insufficient. Due: " << late.totalDue
1273 << ", paid: " << amount;
1275 }
1276
1277 return late;
1278}
1279
1280/* Computes payment components for paying off a loan early (before final
1281 * payment).
1282 *
1283 * A full payment closes the loan immediately, paying off all outstanding
1284 * balances plus a prepayment penalty and any accrued interest since the last
1285 * payment. This is different from the final scheduled payment, which has no
1286 * prepayment penalty.
1287 *
1288 * The function calculates:
1289 * - Accrued interest since last payment (time-based)
1290 * - Prepayment penalty (percentage of remaining principal)
1291 * - Close payment fee (fixed fee for early closure)
1292 * - All remaining principal and outstanding fees
1293 *
1294 * The loan's value may increase or decrease depending on whether the prepayment
1295 * penalty exceeds the scheduled interest that would have been paid.
1296 *
1297 * Implements equation (26) from XLS-66 spec, Section A-2 Equation Glossary
1298 */
1299std::expected<ExtendedPaymentComponents, TER>
1301 Asset const& asset,
1302 ReadView const& view,
1303 SLE::ConstRef loan,
1304 Number const& periodicRate,
1305 STAmount const& amount,
1306 TenthBips16 managementFeeRate,
1308{
1309 std::uint32_t const paymentRemaining = loan->at(sfPaymentRemaining);
1310 std::int32_t const loanScale = loan->at(sfLoanScale);
1311
1312 // Full payment must be made before the final scheduled payment.
1313 if (paymentRemaining <= 1)
1314 {
1315 // If this is the last payment, it has to be a regular payment
1316 JLOG(j.warn()) << "Last payment cannot be a full payment.";
1317 return std::unexpected(tecKILLED);
1318 }
1319
1320 // Calculate the theoretical principal based on the payment schedule.
1321 // This theoretical (unrounded) value is used to compute interest and
1322 // penalties accurately.
1323 Number const theoreticalPrincipalOutstanding = loanPrincipalFromPeriodicPayment(
1324 view.rules(), loan->at(sfPeriodicPayment), periodicRate, paymentRemaining);
1325
1326 // Full payment interest includes both accrued interest (time since last
1327 // payment) and prepayment penalty (for closing early).
1328 auto const fullPaymentInterest = computeFullPaymentInterest(
1329 theoreticalPrincipalOutstanding,
1330 periodicRate,
1331 view.parentCloseTime(),
1332 loan->at(sfPaymentInterval),
1333 loan->at(sfPreviousPaymentDueDate),
1334 loan->at(sfStartDate),
1335 TenthBips32{loan->at(sfCloseInterestRate)});
1336
1337 // Split the full payment interest into net interest (to vault) and management fee (to broker),
1338 // applying proper rounding.
1339 auto const [roundedFullInterest, roundedFullManagementFee] = roundAndSplitInterest(
1340 asset, fullPaymentInterest, managementFeeRate, loanScale, Number::RoundingMode::Downward);
1341
1342 LoanState const loanState = constructLoanState(loan);
1343 Number const principalOutstanding = loanState.principalOutstanding;
1344 Number const managementFeeOutstanding = loanState.managementFeeDue;
1345 Number const totalInterestOutstanding = loanState.interestDue;
1346 Number const closePaymentFee = roundToAsset(asset, loan->at(sfClosePaymentFee), loanScale);
1347
1348 ExtendedPaymentComponents const full{
1350 // Pay off all tracked outstanding balances: principal, interest,
1351 // and fees.
1352 // This marks the loan as complete (final payment).
1353 .trackedValueDelta =
1354 principalOutstanding + totalInterestOutstanding + managementFeeOutstanding,
1355 .trackedPrincipalDelta = principalOutstanding,
1356
1357 // All outstanding management fees are paid. This zeroes out the
1358 // tracked fee balance.
1359 .trackedManagementFeeDelta = managementFeeOutstanding,
1360 .specialCase = PaymentSpecialCase::Final,
1361 },
1362
1363 // Untracked management fee includes:
1364 // 1. Close payment fee (fixed fee for early closure)
1365 // 2. Management fee on the full payment interest
1366 // 3. Minus the outstanding tracked fee (already accounted for above)
1367 // This can be negative because the outstanding fee is subtracted, but
1368 // it gets combined with trackedManagementFeeDelta in the final
1369 // accounting.
1370 closePaymentFee + roundedFullManagementFee - managementFeeOutstanding,
1371
1372 // Value change represents the difference between what the loan was
1373 // expected to earn (totalInterestOutstanding) and what it actually
1374 // earns (roundedFullInterest with prepayment penalty).
1375 // - Positive: Prepayment penalty exceeds scheduled interest (loan value
1376 // increases)
1377 // - Negative: Prepayment penalty is less than scheduled interest (loan
1378 // value decreases)
1379 roundedFullInterest - totalInterestOutstanding,
1380 };
1381
1382 XRPL_ASSERT_PARTS(
1383 isRounded(asset, full.totalDue, loanScale),
1384 "xrpl::detail::computeFullPayment",
1385 "total due is rounded");
1386
1387 JLOG(j.trace()) << "computeFullPayment result: periodicRate: " << periodicRate
1388 << ", paymentRemaining: " << paymentRemaining
1389 << ", theoreticalPrincipalOutstanding: " << theoreticalPrincipalOutstanding
1390 << ", fullPaymentInterest: " << fullPaymentInterest
1391 << ", roundedFullInterest: " << roundedFullInterest
1392 << ", roundedFullManagementFee: " << roundedFullManagementFee
1393 << ", untrackedInterest: " << full.untrackedInterest;
1394
1395 if (amount < full.totalDue)
1396 {
1397 // If the payment is less than the full payment amount, it's not
1398 // sufficient to be a full payment.
1400 }
1401
1402 return full;
1403}
1404
1405Number
1410
1411/* Computes the breakdown of a regular periodic payment into principal,
1412 * interest, and management fee components.
1413 *
1414 * This function determines how a single scheduled payment should be split among
1415 * the three tracked loan components. The calculation accounts for accumulated
1416 * rounding errors.
1417 *
1418 * The algorithm:
1419 * 1. Calculate what the loan state SHOULD be after this payment (target)
1420 * 2. Compare current state to target to get deltas
1421 * 3. Adjust deltas to handle rounding artifacts and edge cases
1422 * 4. Ensure deltas don't exceed available balances or payment amount
1423 *
1424 * Special handling for the final payment: all remaining balances are paid off
1425 * regardless of the periodic payment amount.
1426 *
1427 * Implements the pseudo-code function `compute_payment_due()`.
1428 */
1431 Rules const& rules,
1432 Asset const& asset,
1434 Number const& totalValueOutstanding,
1435 Number const& principalOutstanding,
1436 Number const& managementFeeOutstanding,
1437 Number const& periodicPayment,
1438 Number const& periodicRate,
1439 std::uint32_t paymentRemaining,
1440 TenthBips16 managementFeeRate)
1441{
1442 XRPL_ASSERT_PARTS(
1443 isRounded(asset, totalValueOutstanding, scale) &&
1444 isRounded(asset, principalOutstanding, scale) &&
1445 isRounded(asset, managementFeeOutstanding, scale),
1446 "xrpl::detail::computePaymentComponents",
1447 "Outstanding values are rounded");
1448 XRPL_ASSERT_PARTS(
1449 paymentRemaining > 0, "xrpl::detail::computePaymentComponents", "some payments remaining");
1450
1451 auto const roundedPeriodicPayment = roundPeriodicPayment(asset, periodicPayment, scale);
1452
1453 // Final payment: pay off everything remaining, ignoring the normal
1454 // periodic payment amount. This ensures the loan completes cleanly.
1455 if (paymentRemaining == 1 || totalValueOutstanding <= roundedPeriodicPayment)
1456 {
1457 // If there's only one payment left, we need to pay off each of the loan
1458 // parts.
1459 return PaymentComponents{
1460 .trackedValueDelta = totalValueOutstanding,
1461 .trackedPrincipalDelta = principalOutstanding,
1462 .trackedManagementFeeDelta = managementFeeOutstanding,
1463 .specialCase = PaymentSpecialCase::Final,
1464 };
1465 }
1466
1467 // Calculate what the loan state SHOULD be after this payment (the target).
1468 // This is computed at full precision using the theoretical amortization.
1469 LoanState const trueTarget = computeTheoreticalLoanState(
1470 rules, periodicPayment, periodicRate, paymentRemaining - 1, managementFeeRate);
1471
1472 // Round the target to the loan's scale to match how actual loan values
1473 // are stored. With fixCleanup3_2_0 enabled, principal is rounded upward
1474 // and interest downward so that at coarse scale principal sticks at the
1475 // floor (until the final payment clears it) while interest absorbs each
1476 // periodic payment. Without the amendment the pre-existing round-to-
1477 // nearest behavior is preserved (which can hit the "Partial principal
1478 // payment" assertion on degenerate integer-scale loans).
1479 bool const fixCleanup320Enabled = rules.enabled(fixCleanup3_2_0);
1480 Number::RoundingMode const principalRounding =
1481 fixCleanup320Enabled ? Number::RoundingMode::Upward : Number::getround();
1482 Number::RoundingMode const interestRounding =
1483 fixCleanup320Enabled ? Number::RoundingMode::Downward : Number::getround();
1484 LoanState const roundedTarget = LoanState{
1485 .valueOutstanding = roundToAsset(asset, trueTarget.valueOutstanding, scale),
1486 .principalOutstanding =
1487 roundToAsset(asset, trueTarget.principalOutstanding, scale, principalRounding),
1488 .interestDue = roundToAsset(asset, trueTarget.interestDue, scale, interestRounding),
1489 .managementFeeDue = roundToAsset(asset, trueTarget.managementFeeDue, scale),
1490 };
1491
1492 // Get the current actual loan state from the ledger values
1493 LoanState const currentLedgerState =
1494 constructLoanState(totalValueOutstanding, principalOutstanding, managementFeeOutstanding);
1495
1496 // The difference between current and target states gives us the payment
1497 // components. Any discrepancies from accumulated rounding are captured
1498 // here.
1499
1500 LoanStateDeltas deltas = currentLedgerState - roundedTarget;
1501
1502 // Rounding can occasionally produce negative deltas. Zero them out.
1503 deltas.nonNegative();
1504
1505 XRPL_ASSERT_PARTS(
1506 deltas.principal <= currentLedgerState.principalOutstanding,
1507 "xrpl::detail::computePaymentComponents",
1508 "principal delta not greater than outstanding");
1509
1510 // Cap each component to never exceed what's actually outstanding
1511 deltas.principal = std::min(deltas.principal, currentLedgerState.principalOutstanding);
1512
1513 if (fixCleanup320Enabled)
1514 {
1515 XRPL_ASSERT_PARTS(
1516 deltas.interest <= currentLedgerState.interestDue,
1517 "xrpl::detail::computePaymentComponents",
1518 "interest due delta not greater than outstanding");
1519 }
1520 // Cap interest to both the outstanding amount AND what's left of the
1521 // periodic payment after principal is paid
1522 deltas.interest = std::min({
1523 deltas.interest,
1524 std::max(kNumZero, roundedPeriodicPayment - deltas.principal),
1525 currentLedgerState.interestDue,
1526 });
1527
1528 XRPL_ASSERT_PARTS(
1529 deltas.managementFee <= currentLedgerState.managementFeeDue,
1530 "xrpl::detail::computePaymentComponents",
1531 "management fee due delta not greater than outstanding");
1532
1533 // Cap management fee to both the outstanding amount AND what's left of the
1534 // periodic payment after principal and interest are paid
1535 deltas.managementFee = std::min({
1536 deltas.managementFee,
1537 roundedPeriodicPayment - (deltas.principal + deltas.interest),
1538 currentLedgerState.managementFeeDue,
1539 });
1540
1541 // The shortage must never be negative, which indicates that the parts are
1542 // trying to take more than the whole payment. The excess can be positive,
1543 // which indicates that we're not going to take the whole payment amount,
1544 // but if so, it must be small.
1545 auto takeFrom = [](Number& component, Number& excess) {
1546 if (excess > beast::kZero)
1547 {
1548 auto const part = std::min(component, excess);
1549 component -= part;
1550 excess -= part;
1551 }
1552 XRPL_ASSERT_PARTS(
1553 excess >= beast::kZero,
1554 "xrpl::detail::computePaymentComponents",
1555 "excess non-negative");
1556 };
1557 // Helper to reduce deltas when they collectively exceed a limit.
1558 // Order matters: we prefer to reduce interest first (most flexible),
1559 // then management fee, then principal (least flexible).
1560 auto const addressExcess = [&takeFrom](LoanStateDeltas& deltas, Number& excess) {
1561 // This order is based on where errors are the least problematic
1562 takeFrom(deltas.interest, excess);
1563 takeFrom(deltas.managementFee, excess);
1564 takeFrom(deltas.principal, excess);
1565 };
1566
1567 // Check if deltas exceed the total outstanding value. This should never
1568 // happen due to earlier caps, but handle it defensively.
1569 Number totalOverpayment = deltas.total() - currentLedgerState.valueOutstanding;
1570
1571 if (totalOverpayment > beast::kZero)
1572 {
1573 // LCOV_EXCL_START
1574 UNREACHABLE(
1575 "xrpl::detail::computePaymentComponents : payment exceeded loan "
1576 "state");
1577 addressExcess(deltas, totalOverpayment);
1578 // LCOV_EXCL_STOP
1579 }
1580
1581 // Check if deltas exceed the periodic payment amount. Reduce if needed.
1582 Number shortage = roundedPeriodicPayment - deltas.total();
1583
1584 XRPL_ASSERT_PARTS(
1585 isRounded(asset, shortage, scale),
1586 "xrpl::detail::computePaymentComponents",
1587 "shortage is rounded");
1588
1589 if (shortage < beast::kZero)
1590 {
1591 // Deltas exceed payment amount - reduce them proportionally
1592 Number excess = -shortage;
1593 addressExcess(deltas, excess);
1594 shortage = -excess;
1595 }
1596
1597 // At this point, shortage >= 0 means we're paying less than the full
1598 // periodic payment (due to rounding or component caps).
1599 // shortage < 0 would mean we're trying to pay more than allowed (bug).
1600 XRPL_ASSERT_PARTS(
1601 shortage >= beast::kZero,
1602 "xrpl::detail::computePaymentComponents",
1603 "no shortage or excess");
1604
1605 // Final validation that all components are valid
1606 XRPL_ASSERT_PARTS(
1607 deltas.total() == deltas.principal + deltas.interest + deltas.managementFee,
1608 "xrpl::detail::computePaymentComponents",
1609 "total value adds up");
1610
1611 XRPL_ASSERT_PARTS(
1612 deltas.principal >= beast::kZero &&
1613 deltas.principal <= currentLedgerState.principalOutstanding,
1614 "xrpl::detail::computePaymentComponents",
1615 "valid principal result");
1616 XRPL_ASSERT_PARTS(
1617 deltas.interest >= beast::kZero && deltas.interest <= currentLedgerState.interestDue,
1618 "xrpl::detail::computePaymentComponents",
1619 "valid interest result");
1620 XRPL_ASSERT_PARTS(
1621 deltas.managementFee >= beast::kZero &&
1622 deltas.managementFee <= currentLedgerState.managementFeeDue,
1623 "xrpl::detail::computePaymentComponents",
1624 "valid fee result");
1625
1626 XRPL_ASSERT_PARTS(
1627 deltas.principal + deltas.interest + deltas.managementFee > beast::kZero,
1628 "xrpl::detail::computePaymentComponents",
1629 "payment parts add to payment");
1630
1631 // Final safety clamp to ensure no value exceeds its outstanding balance
1632 return PaymentComponents{
1633 .trackedValueDelta =
1634 std::clamp(deltas.total(), kNumZero, currentLedgerState.valueOutstanding),
1635 .trackedPrincipalDelta =
1636 std::clamp(deltas.principal, kNumZero, currentLedgerState.principalOutstanding),
1637 .trackedManagementFeeDelta =
1638 std::clamp(deltas.managementFee, kNumZero, currentLedgerState.managementFeeDue),
1639 };
1640}
1641
1642/* Thin overload of computePaymentComponents() that unwraps the tracked
1643 * fields directly from the Loan ledger object. `periodicRate` is derived
1644 * rather than stored, and `managementFeeRate` comes from the LoanBroker, not
1645 * the Loan, so both remain explicit parameters. Kept separate from the
1646 * value-based overload above, which is exercised directly by unit tests
1647 * against simulated (non-ledger) loan states.
1648 */
1649PaymentComponents
1651 Rules const& rules,
1652 Asset const& asset,
1653 SLE::Ref loan,
1654 Number const& periodicRate,
1655 TenthBips16 managementFeeRate)
1656{
1658 rules,
1659 asset,
1660 loan->at(sfLoanScale),
1661 loan->at(sfTotalValueOutstanding),
1662 loan->at(sfPrincipalOutstanding),
1663 loan->at(sfManagementFeeOutstanding),
1664 loan->at(sfPeriodicPayment),
1665 periodicRate,
1666 loan->at(sfPaymentRemaining),
1667 managementFeeRate);
1668}
1669
1670/* Computes payment components for an overpayment scenario.
1671 *
1672 * An overpayment occurs when a borrower pays more than the scheduled periodic
1673 * payment amount. The overpayment is treated as extra principal reduction,
1674 * but incurs a fee and potentially a penalty interest charge.
1675 *
1676 * The calculation (Section 3.2.4.2.3 from XLS-66 spec):
1677 * 1. Calculate gross penalty interest on the overpayment amount
1678 * 2. Split the gross interest into net interest and management fee
1679 * 3. Calculate the penalty fee
1680 * 4. Determine the principal portion by subtracting the interest (gross) and
1681 * management fee from the overpayment amount
1682 *
1683 * Unlike regular payments which follow the amortization schedule, overpayments
1684 * apply to principal, reducing the loan balance and future interest costs.
1685 *
1686 * Equations (20), (21) and (22) from XLS-66 spec, Section A-2 Equation Glossary
1687 */
1688ExtendedPaymentComponents
1690 Rules const& rules,
1691 Asset const& asset,
1692 int32_t const loanScale,
1693 Number const& overpayment,
1694 TenthBips32 const overpaymentInterestRate,
1695 TenthBips32 const overpaymentFeeRate,
1696 TenthBips16 const managementFeeRate)
1697{
1698 XRPL_ASSERT_IF(
1699 rules.enabled(fixCleanup3_2_0),
1700 overpayment > 0 && isRounded(asset, overpayment, loanScale),
1701 "xrpl::detail::computeOverpaymentComponents : valid overpayment "
1702 "amount");
1703
1704 // First, deduct the fixed overpayment fee from the total amount.
1705 // This reduces the effective payment that will be applied to the loan.
1706 // Equation (22) from XLS-66 spec, Section A-2 Equation Glossary
1707 Number const overpaymentFee =
1708 roundToAsset(asset, tenthBipsOfValue(overpayment, overpaymentFeeRate), loanScale);
1709
1710 // Calculate the penalty interest on the effective payment amount.
1711 // This interest doesn't follow the normal amortization schedule - it's
1712 // a one-time charge for paying early.
1713 // Equation (20) and (21) from XLS-66 spec, Section A-2 Equation Glossary
1714 auto const [roundedOverpaymentInterest, roundedOverpaymentManagementFee] =
1716 asset,
1717 tenthBipsOfValue(overpayment, overpaymentInterestRate),
1718 managementFeeRate,
1719 loanScale);
1720
1721 auto const result = detail::ExtendedPaymentComponents{
1722 // Build the payment components, after fees and penalty
1723 // interest are deducted, the remainder goes entirely to principal
1724 // reduction.
1726 .trackedValueDelta = overpayment - overpaymentFee,
1727 .trackedPrincipalDelta = overpayment - roundedOverpaymentInterest -
1728 roundedOverpaymentManagementFee - overpaymentFee,
1729 .trackedManagementFeeDelta = roundedOverpaymentManagementFee,
1730 .specialCase = detail::PaymentSpecialCase::Extra,
1731 },
1732 // Untracked management fee is the fixed overpayment fee
1733 overpaymentFee,
1734 // Untracked interest is the penalty interest charged for overpaying.
1735 // This is positive, representing a one-time cost, but it's typically
1736 // much smaller than the interest savings from reducing principal.
1737 // It is equal to the paymentComponents.trackedInterestPart()
1738 // but is kept separate for clarity.
1739 roundedOverpaymentInterest};
1740 XRPL_ASSERT_PARTS(
1741 result.trackedInterestPart() == roundedOverpaymentInterest,
1742 "xrpl::detail::computeOverpaymentComponents",
1743 "valid interest computation");
1744 return result;
1745}
1746
1747/* Derives the two rate values every make*Payment() helper needs: the
1748 * broker's management fee rate, and the loan's periodic (per-payment-period)
1749 * interest rate.
1750 */
1753{
1754 TenthBips16 const managementFeeRate{brokerSle->at(sfManagementFeeRate)};
1755 TenthBips32 const interestRate{loan->at(sfInterestRate)};
1756 Number const periodicRate = loanPeriodicRate(interestRate, loan->at(sfPaymentInterval));
1757 XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::detail::loanRatesFor : valid rate");
1758 return {managementFeeRate, periodicRate};
1759}
1760
1761/* Handles a full (early payoff) payment. Implements the "full payment"
1762 * branch of the make_payment function from the XLS-66 spec, Section
1763 * 3.2.4.4.
1764 */
1765std::expected<LoanPaymentParts, TER>
1767 Asset const& asset,
1768 ApplyView const& view,
1769 SLE::Ref loan,
1770 SLE::ConstRef brokerSle,
1771 STAmount const& amount,
1773{
1774 auto const [managementFeeRate, periodicRate] = loanRatesFor(loan, brokerSle);
1775
1776 auto const fullPaymentComponents =
1777 computeFullPayment(asset, view, loan, periodicRate, amount, managementFeeRate, j);
1778
1779 // computeFullPayment only ever fails with a genuine error TER (never
1780 // tesSUCCESS), so there is no separate "no-op" outcome to handle here.
1781 if (fullPaymentComponents.has_value())
1782 return doPayment(*fullPaymentComponents, loan);
1783 return std::unexpected(fullPaymentComponents.error());
1784}
1785
1786/* Handles a late payment (past due date, with the late-payment flag set).
1787 * Implements the "late payment" branch of the make_payment function from
1788 * the XLS-66 spec, Section 3.2.4.4.
1789 */
1790std::expected<LoanPaymentParts, TER>
1792 Asset const& asset,
1793 ApplyView const& view,
1794 SLE::Ref loan,
1795 SLE::ConstRef brokerSle,
1796 STAmount const& amount,
1798{
1799 auto const [managementFeeRate, periodicRate] = loanRatesFor(loan, brokerSle);
1800
1801 Number const serviceFee = loan->at(sfLoanServiceFee);
1802 ExtendedPaymentComponents const periodic{
1803 computePaymentComponents(view.rules(), asset, loan, periodicRate, managementFeeRate),
1804 serviceFee};
1805 XRPL_ASSERT_PARTS(
1806 periodic.trackedPrincipalDelta >= 0,
1807 "xrpl::detail::makeLatePayment",
1808 "regular payment valid principal");
1809
1810 auto const latePaymentComponents =
1811 computeLatePayment(asset, view, loan, periodic, amount, managementFeeRate, j);
1812
1813 // computeLatePayment only ever fails with a genuine error TER (never
1814 // tesSUCCESS), so there is no separate "no-op" outcome to handle here.
1815 if (latePaymentComponents.has_value())
1816 return doPayment(*latePaymentComponents, loan);
1817 return std::unexpected(latePaymentComponents.error());
1818}
1819
1820/* Handles regular scheduled payments, including an optional overpayment tail.
1821 * Implements the "regular" and "overpayment" branches of the make_payment
1822 * function from the XLS-66 spec, Section 3.2.4.4.
1823 */
1824std::expected<LoanPaymentParts, TER>
1826 Asset const& asset,
1827 ApplyView const& view,
1828 SLE::Ref loan,
1829 SLE::ConstRef brokerSle,
1830 STAmount const& amount,
1831 LoanPaymentType const paymentType,
1833{
1834 using namespace lending;
1835
1836 XRPL_ASSERT_PARTS(
1837 paymentType == LoanPaymentType::Regular || paymentType == LoanPaymentType::Overpayment,
1838 "xrpl::detail::makeRegularPayment",
1839 "regular payment type");
1840
1841 auto const [managementFeeRate, periodicRate] = loanRatesFor(loan, brokerSle);
1842
1843 std::int32_t const loanScale = loan->at(sfLoanScale);
1844 Number const serviceFee = loan->at(sfLoanServiceFee);
1845
1847 computePaymentComponents(view.rules(), asset, loan, periodicRate, managementFeeRate),
1848 serviceFee};
1849 XRPL_ASSERT_PARTS(
1850 periodic.trackedPrincipalDelta >= 0,
1851 "xrpl::detail::makeRegularPayment",
1852 "regular payment valid principal");
1853
1854 // Keep a running total of the actual parts paid
1855 LoanPaymentParts totalParts;
1856 Number totalPaid = kNumZero;
1857 std::size_t numPayments = 0;
1858
1859 // Cached here (rather than re-looking up loan->at(sfPaymentRemaining) at each use) since it's
1860 // read multiple times below. It's a write-through proxy, so it still reflects doPayment's
1861 // mutations each iteration.
1862 auto const paymentRemainingProxy = loan->at(sfPaymentRemaining);
1863
1864 while ((amount >= (totalPaid + periodic.totalDue)) && paymentRemainingProxy > 0 &&
1865 numPayments < kLoanMaximumPaymentsPerTransaction)
1866 {
1867 // Try to make more payments
1868 XRPL_ASSERT_PARTS(
1869 periodic.trackedPrincipalDelta >= 0,
1870 "xrpl::detail::makeRegularPayment",
1871 "payment pays non-negative principal");
1872
1873 totalPaid += periodic.totalDue;
1874 totalParts += doPayment(periodic, loan);
1875 ++numPayments;
1876
1877 XRPL_ASSERT_PARTS(
1878 (periodic.specialCase == PaymentSpecialCase::Final) == (paymentRemainingProxy == 0),
1879 "xrpl::detail::makeRegularPayment",
1880 "final payment is the final payment");
1881
1882 // Don't compute the next payment if this was the last payment
1883 if (periodic.specialCase == PaymentSpecialCase::Final)
1884 break;
1885
1886 periodic = ExtendedPaymentComponents{
1887 computePaymentComponents(view.rules(), asset, loan, periodicRate, managementFeeRate),
1888 serviceFee};
1889 }
1890
1891 if (numPayments == 0)
1892 {
1893 JLOG(j.warn()) << "Regular loan payment amount is insufficient. Due: " << periodic.totalDue
1894 << ", paid: " << amount;
1896 }
1897
1898 XRPL_ASSERT_PARTS(
1899 totalParts.principalPaid + totalParts.interestPaid + totalParts.feePaid == totalPaid,
1900 "xrpl::detail::makeRegularPayment",
1901 "payment parts add up");
1902 XRPL_ASSERT_PARTS(
1903 totalParts.valueChange == 0, "xrpl::detail::makeRegularPayment", "no value change");
1904
1905 // -------------------------------------------------------------
1906 // overpayment handling
1907 //
1908 // If the "fixCleanup3_1_3" amendment is enabled, truncate "amount",
1909 // at the loan scale. If the raw value is used, the overpayment
1910 // amount could be meaningless dust. Trying to process such a small
1911 // amount will, at best, waste time when all the result values round
1912 // to zero. At worst, it can cause logical errors with tiny amounts
1913 // of interest that don't add up correctly.
1914 auto const roundedAmount = view.rules().enabled(fixCleanup3_1_3)
1915 ? roundToAsset(asset, amount, loanScale, Number::RoundingMode::TowardsZero)
1916 : amount;
1917
1918 bool const overpaymentSupported =
1919 paymentType == LoanPaymentType::Overpayment && loan->isFlag(lsfLoanOverpayment);
1920
1921 bool const overpaymentAllowed = //
1922 paymentRemainingProxy > 0 && //
1923 totalPaid < roundedAmount && //
1924 numPayments < kLoanMaximumPaymentsPerTransaction;
1925
1926 if (overpaymentSupported && overpaymentAllowed)
1927 {
1928 TenthBips32 const overpaymentInterestRate{loan->at(sfOverpaymentInterestRate)};
1929 TenthBips32 const overpaymentFeeRate{loan->at(sfOverpaymentFee)};
1930
1931 // It shouldn't be possible for the overpayment to be greater than
1932 // totalValueOutstanding, because that would have been processed as
1933 // another normal payment. But cap it just in case.
1934 Number const overpaymentRaw =
1935 std::min(roundedAmount - totalPaid, *loan->at(sfTotalValueOutstanding));
1936
1937 bool const fixEnabled = view.rules().enabled(fixCleanup3_2_0);
1938 Number const overpayment = fixEnabled
1939 ? roundToAsset(asset, overpaymentRaw, loanScale, Number::RoundingMode::Downward)
1940 : overpaymentRaw;
1941
1942 // Post-amendment, the rounded overpayment can be zero; pre-amendment
1943 // it's always positive given the surrounding guards.
1944 if (!fixEnabled || overpayment > 0)
1945 {
1946 ExtendedPaymentComponents const overpaymentComponents = computeOverpaymentComponents(
1947 view.rules(),
1948 asset,
1949 loanScale,
1950 overpayment,
1951 overpaymentInterestRate,
1952 overpaymentFeeRate,
1953 managementFeeRate);
1954
1955 // Don't process an overpayment if the whole amount (or more!)
1956 // gets eaten by fees and interest.
1957 if (overpaymentComponents.trackedPrincipalDelta > 0)
1958 {
1959 XRPL_ASSERT_PARTS(
1960 overpaymentComponents.untrackedInterest >= beast::kZero,
1961 "xrpl::detail::makeRegularPayment",
1962 "overpayment penalty did not reduce value of loan");
1963 if (auto const overResult = doOverpayment(
1964 view.rules(),
1965 asset,
1966 loanScale,
1967 overpaymentComponents,
1968 loan,
1969 periodicRate,
1970 managementFeeRate,
1971 j))
1972 {
1973 totalParts += *overResult;
1974 }
1975 else if (overResult.error())
1976 {
1977 // error() will be the TER returned if a payment is not
1978 // made. It will only evaluate to true if it's unsuccessful.
1979 // Otherwise, tesSUCCESS means nothing was done, so
1980 // continue.
1981 return std::unexpected(overResult.error());
1982 }
1983 }
1984 }
1985 }
1986
1987 // Check the final results are rounded, to double-check that the
1988 // intermediate steps were rounded.
1989 XRPL_ASSERT(
1990 isRounded(asset, totalParts.principalPaid, loanScale) &&
1991 totalParts.principalPaid >= beast::kZero,
1992 "xrpl::detail::makeRegularPayment : total principal paid is valid");
1993 XRPL_ASSERT(
1994 isRounded(asset, totalParts.interestPaid, loanScale) &&
1995 totalParts.interestPaid >= beast::kZero,
1996 "xrpl::detail::makeRegularPayment : total interest paid is valid");
1997 XRPL_ASSERT(
1998 isRounded(asset, totalParts.valueChange, loanScale),
1999 "xrpl::detail::makeRegularPayment : loan value change is valid");
2000 XRPL_ASSERT(
2001 isRounded(asset, totalParts.feePaid, loanScale) && totalParts.feePaid >= beast::kZero,
2002 "xrpl::detail::makeRegularPayment : fee paid is valid");
2003 return totalParts;
2004}
2005
2006} // namespace detail
2007
2008detail::LoanStateDeltas
2009operator-(LoanState const& lhs, LoanState const& rhs)
2010{
2012 .principal = lhs.principalOutstanding - rhs.principalOutstanding,
2013 .interest = lhs.interestDue - rhs.interestDue,
2014 .managementFee = lhs.managementFeeDue - rhs.managementFeeDue,
2015 };
2016
2017 return result;
2018}
2019
2020LoanState
2022{
2023 LoanState result{
2024 .valueOutstanding = lhs.valueOutstanding - rhs.total(),
2025 .principalOutstanding = lhs.principalOutstanding - rhs.principal,
2026 .interestDue = lhs.interestDue - rhs.interest,
2027 .managementFeeDue = lhs.managementFeeDue - rhs.managementFee,
2028 };
2029
2030 return result;
2031}
2032
2033LoanState
2035{
2036 LoanState result{
2037 .valueOutstanding = lhs.valueOutstanding + rhs.total(),
2038 .principalOutstanding = lhs.principalOutstanding + rhs.principal,
2039 .interestDue = lhs.interestDue + rhs.interest,
2040 .managementFeeDue = lhs.managementFeeDue + rhs.managementFee,
2041 };
2042
2043 return result;
2044}
2045
2046TER
2048 Asset const& vaultAsset,
2049 Number const& principalRequested,
2050 bool expectInterest,
2051 std::uint32_t paymentTotal,
2052 LoanProperties const& properties,
2054{
2055 auto const totalInterestOutstanding =
2056 properties.loanState.valueOutstanding - principalRequested;
2057 // Guard 1: if there is no computed total interest over the life of the
2058 // loan for a non-zero interest rate, we cannot properly amortize the
2059 // loan
2060 if (expectInterest && totalInterestOutstanding <= 0)
2061 {
2062 // Unless this is a zero-interest loan, there must be some interest
2063 // due on the loan, even if it's (measurable) dust
2064 JLOG(j.warn()) << "Loan for " << principalRequested << " with interest has no interest due";
2065 return tecPRECISION_LOSS;
2066 }
2067 // Guard 1a: If there is any interest computed over the life of the
2068 // loan, for a zero interest rate, something went sideways.
2069 if (!expectInterest && totalInterestOutstanding > 0)
2070 {
2071 // LCOV_EXCL_START
2072 JLOG(j.warn()) << "Loan for " << principalRequested << " with no interest has interest due";
2073 return tecINTERNAL;
2074 // LCOV_EXCL_STOP
2075 }
2076
2077 // Guard 2: if the principal portion of the first periodic payment is
2078 // too small to be accurately represented with the given rounding mode,
2079 // raise an error
2080 if (properties.firstPaymentPrincipal <= 0)
2081 {
2082 // Check that some true (unrounded) principal is paid each period.
2083 // Since the first payment pays the least principal, if it's good,
2084 // they'll all be good. Note that the outstanding principal is
2085 // rounded, and may not change right away.
2086 JLOG(j.warn()) << "Loan is unable to pay principal.";
2087 return tecPRECISION_LOSS;
2088 }
2089
2090 // Guard 3: If the periodic payment is so small that it can't even be
2091 // rounded to a representable value, then the loan can't be paid. Also,
2092 // avoids dividing by 0.
2093 auto const roundedPayment =
2094 roundPeriodicPayment(vaultAsset, properties.periodicPayment, properties.loanScale);
2095 if (roundedPayment == beast::kZero)
2096 {
2097 JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment
2098 << ") rounds to 0. ";
2099 return tecPRECISION_LOSS;
2100 }
2101
2102 // Guard 4: if the rounded periodic payment is large enough that the
2103 // loan can't be amortized in the specified number of payments, raise an
2104 // error
2105 {
2107
2108 if (std::int64_t const computedPayments{
2109 properties.loanState.valueOutstanding / roundedPayment,
2110 };
2111 computedPayments != paymentTotal)
2112 {
2113 JLOG(j.warn()) << "Loan Periodic payment (" << properties.periodicPayment
2114 << ") rounding (" << roundedPayment << ") on a total value of "
2115 << properties.loanState.valueOutstanding
2116 << " can not complete the loan in the specified "
2117 "number of payments ("
2118 << computedPayments << " != " << paymentTotal << ")";
2119 return tecPRECISION_LOSS;
2120 }
2121 }
2122 return tesSUCCESS;
2123}
2124
2125/*
2126 * This function calculates the full payment interest accrued since the last
2127 * payment, plus any prepayment penalty.
2128 *
2129 * Equations (27) and (28) from XLS-66 spec, Section A-2 Equation Glossary
2130 */
2131Number
2133 Number const& theoreticalPrincipalOutstanding,
2134 Number const& periodicRate,
2135 NetClock::time_point parentCloseTime,
2136 std::uint32_t paymentInterval,
2137 std::uint32_t prevPaymentDate,
2138 std::uint32_t startDate,
2139 TenthBips32 closeInterestRate)
2140{
2141 auto const accruedInterest = detail::loanAccruedInterest(
2142 theoreticalPrincipalOutstanding,
2143 periodicRate,
2144 parentCloseTime,
2145 startDate,
2146 prevPaymentDate,
2147 paymentInterval);
2148 XRPL_ASSERT(
2149 accruedInterest >= 0,
2150 "xrpl::detail::computeFullPaymentInterest : valid accrued "
2151 "interest");
2152
2153 // Equation (28) from XLS-66 spec, Section A-2 Equation Glossary
2154 auto const prepaymentPenalty = closeInterestRate == beast::kZero
2155 ? Number{}
2156 : tenthBipsOfValue(theoreticalPrincipalOutstanding, closeInterestRate);
2157
2158 XRPL_ASSERT(
2159 prepaymentPenalty >= 0,
2160 "xrpl::detail::computeFullPaymentInterest : valid prepayment "
2161 "interest");
2162
2163 // Part of equation (27) from XLS-66 spec, Section A-2 Equation Glossary
2164 return accruedInterest + prepaymentPenalty;
2165}
2166
2167/* Calculates the theoretical loan state at maximum precision for a given point
2168 * in the amortization schedule.
2169 *
2170 * This function computes what the loan's outstanding balances should be based
2171 * on the periodic payment amount and number of payments remaining,
2172 * without considering any rounding that may have been applied to the actual
2173 * Loan object's state. This "theoretical" (unrounded) state is used as a target
2174 * for computing payment components and validating that the loan's tracked state
2175 * hasn't drifted too far from the theoretical values.
2176 *
2177 * The theoretical state serves several purposes:
2178 * 1. Computing the expected payment breakdown (principal, interest, fees)
2179 * 2. Detecting and correcting rounding errors that accumulate over time
2180 * 3. Validating that overpayments are calculated correctly
2181 * 4. Ensuring the loan will be fully paid off at the end of its term
2182 *
2183 * If paymentRemaining is 0, returns a fully zeroed-out LoanState,
2184 * representing a completely paid-off loan.
2185 *
2186 * Implements the `calculate_true_loan_state` function from the XLS-66 spec
2187 * section 3.2.4.4 Transaction Pseudo-code
2188 */
2189LoanState
2191 Rules const& rules,
2192 Number const& periodicPayment,
2193 Number const& periodicRate,
2194 std::uint32_t const paymentRemaining,
2195 TenthBips32 const managementFeeRate)
2196{
2197 if (paymentRemaining == 0)
2198 {
2199 return LoanState{
2200 .valueOutstanding = 0,
2201 .principalOutstanding = 0,
2202 .interestDue = 0,
2203 .managementFeeDue = 0,
2204 };
2205 }
2206
2207 // Equation (30) from XLS-66 spec, Section A-2 Equation Glossary
2208 Number const totalValueOutstanding = periodicPayment * paymentRemaining;
2209
2210 Number const principalOutstanding = detail::loanPrincipalFromPeriodicPayment(
2211 rules, periodicPayment, periodicRate, paymentRemaining);
2212
2213 // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary
2214 Number const interestOutstandingGross = totalValueOutstanding - principalOutstanding;
2215
2216 // Equation (32) from XLS-66 spec, Section A-2 Equation Glossary
2217 Number const managementFeeOutstanding =
2218 tenthBipsOfValue(interestOutstandingGross, managementFeeRate);
2219
2220 // Equation (33) from XLS-66 spec, Section A-2 Equation Glossary
2221 Number const interestOutstandingNet = interestOutstandingGross - managementFeeOutstanding;
2222
2223 return LoanState{
2224 .valueOutstanding = totalValueOutstanding,
2225 .principalOutstanding = principalOutstanding,
2226 .interestDue = interestOutstandingNet,
2227 .managementFeeDue = managementFeeOutstanding,
2228 };
2229};
2230
2231/* Constructs a LoanState from rounded Loan ledger object values.
2232 *
2233 * This function creates a LoanState structure from the three tracked values
2234 * stored in a Loan ledger object. Unlike calculateTheoreticalLoanState(), which
2235 * computes theoretical unrounded values, this function works with values
2236 * that have already been rounded to the loan's scale.
2237 *
2238 * The key difference from calculateTheoreticalLoanState():
2239 * - calculateTheoreticalLoanState: Computes theoretical values at full
2240 * precision
2241 * - constructRoundedLoanState: Builds state from actual rounded ledger values
2242 *
2243 * The interestDue field is derived from the other three values rather than
2244 * stored directly, since it can be calculated as:
2245 * interestDue = totalValueOutstanding - principalOutstanding -
2246 * managementFeeOutstanding
2247 *
2248 * This ensures consistency across the codebase and prevents copy-paste errors
2249 * when creating LoanState objects from Loan ledger data.
2250 */
2251LoanState
2253 Number const& totalValueOutstanding,
2254 Number const& principalOutstanding,
2255 Number const& managementFeeOutstanding)
2256{
2257 // This implementation is pretty trivial, but ensures the calculations
2258 // are consistent everywhere, and reduces copy/paste errors.
2259 return LoanState{
2260 .valueOutstanding = totalValueOutstanding,
2261 .principalOutstanding = principalOutstanding,
2262 .interestDue = totalValueOutstanding - principalOutstanding - managementFeeOutstanding,
2263 .managementFeeDue = managementFeeOutstanding,
2264 };
2265}
2266
2267LoanState
2269{
2270 XRPL_ASSERT(loan && loan->getType() == ltLOAN, "xrpl::constructLoanState : valid loan SLE");
2271
2272 return constructLoanState(
2273 loan->at(sfTotalValueOutstanding),
2274 loan->at(sfPrincipalOutstanding),
2275 loan->at(sfManagementFeeOutstanding));
2276}
2277
2278/*
2279 * This function calculates the fee owed to the broker based on the asset,
2280 * value, and management fee rate.
2281 *
2282 * Equation (32) from XLS-66 spec, Section A-2 Equation Glossary
2283 */
2284Number
2286 Asset const& asset,
2287 Number const& value,
2288 TenthBips32 managementFeeRate,
2290{
2291 return roundToAsset(
2292 asset, tenthBipsOfValue(value, managementFeeRate), scale, Number::RoundingMode::Downward);
2293}
2294
2295/*
2296 * Given the loan parameters, compute the derived properties of the loan.
2297 *
2298 * Pulls together several formulas from the XLS-66 spec, which are noted at each
2299 * step, plus the concepts from 3.2.4.3 Conceptual Loan Value. They are used for
2300 * to check some of the conditions in 3.2.1.5 Failure Conditions for the LoanSet
2301 * transaction.
2302 */
2303LoanProperties
2305 Rules const& rules,
2306 Asset const& asset,
2307 Number const& principalOutstanding,
2308 TenthBips32 interestRate,
2309 std::uint32_t paymentInterval,
2310 std::uint32_t paymentsRemaining,
2311 TenthBips32 managementFeeRate,
2312 std::int32_t minimumScale)
2313{
2314 auto const periodicRate = loanPeriodicRate(interestRate, paymentInterval);
2315 XRPL_ASSERT(interestRate == 0 || periodicRate > 0, "xrpl::computeLoanProperties : valid rate");
2316 return computeLoanProperties(
2317 rules,
2318 asset,
2319 principalOutstanding,
2320 periodicRate,
2321 paymentsRemaining,
2322 managementFeeRate,
2323 minimumScale);
2324}
2325
2326/*
2327 * Given the loan parameters, compute the derived properties of the loan.
2328 *
2329 * Pulls together several formulas from the XLS-66 spec, which are noted at each
2330 * step, plus the concepts from 3.2.4.3 Conceptual Loan Value. They are used for
2331 * to check some of the conditions in 3.2.1.5 Failure Conditions for the LoanSet
2332 * transaction.
2333 */
2334LoanProperties
2336 Rules const& rules,
2337 Asset const& asset,
2338 Number const& principalOutstanding,
2339 Number const& periodicRate,
2340 std::uint32_t paymentsRemaining,
2341 TenthBips32 managementFeeRate,
2342 std::int32_t minimumScale)
2343{
2344 auto const periodicPayment =
2345 detail::loanPeriodicPayment(rules, principalOutstanding, periodicRate, paymentsRemaining);
2346
2347 auto const [totalValueOutstanding, loanScale] = [&] {
2348 // only round up if there should be interest
2349 NumberRoundModeGuard const mg(
2351 // Use STAmount's internal rounding instead of roundToAsset, because
2352 // we're going to use this result to determine the scale for all the
2353 // other rounding.
2354
2355 // Equation (30) from XLS-66 spec, Section A-2 Equation Glossary
2356 STAmount amount{asset, periodicPayment * paymentsRemaining};
2357
2358 // Base the loan scale on the total value, since that's going to be
2359 // the biggest number involved (barring unusual parameters for late,
2360 // full, or over payments)
2361 auto const loanScale = std::max(minimumScale, amount.exponent());
2362 XRPL_ASSERT_PARTS(
2363 (amount.integral() && loanScale == 0) ||
2364 (!amount.integral() && loanScale >= static_cast<Number>(amount).exponent()),
2365 "xrpl::computeLoanProperties",
2366 "loanScale value fits expectations");
2367
2368 // We may need to truncate the total value because of the minimum
2369 // scale
2370 amount = roundToAsset(asset, amount, loanScale);
2371
2372 return std::make_pair(amount, loanScale);
2373 }();
2374
2375 // Since we just figured out the loan scale, we haven't been able to
2376 // validate that the principal fits in it, so to allow this function to
2377 // succeed, round it here, and let the caller do the validation.
2378 auto const roundedPrincipalOutstanding =
2379 roundToAsset(asset, principalOutstanding, loanScale, Number::RoundingMode::ToNearest);
2380
2381 // Equation (31) from XLS-66 spec, Section A-2 Equation Glossary
2382 auto const totalInterestOutstanding = totalValueOutstanding - roundedPrincipalOutstanding;
2383 auto const feeOwedToBroker =
2384 computeManagementFee(asset, totalInterestOutstanding, managementFeeRate, loanScale);
2385
2386 // Compute the principal part of the first payment. This is needed
2387 // because the principal part may be rounded down to zero, which
2388 // would prevent the principal from ever being paid down.
2389 auto const firstPaymentPrincipal = [&] {
2390 // Compute the parts for the first payment. Ensure that the
2391 // principal payment will actually change the principal.
2392 auto const startingState = computeTheoreticalLoanState(
2393 rules, periodicPayment, periodicRate, paymentsRemaining, managementFeeRate);
2394
2395 auto const firstPaymentState = computeTheoreticalLoanState(
2396 rules, periodicPayment, periodicRate, paymentsRemaining - 1, managementFeeRate);
2397
2398 // The unrounded principal part needs to be large enough to affect
2399 // the principal. What to do if not is left to the caller
2400 return startingState.principalOutstanding - firstPaymentState.principalOutstanding;
2401 }();
2402
2403 return LoanProperties{
2404 .periodicPayment = periodicPayment,
2405 .loanState =
2406 constructLoanState(totalValueOutstanding, roundedPrincipalOutstanding, feeOwedToBroker),
2407 .loanScale = loanScale,
2408 .firstPaymentPrincipal = firstPaymentPrincipal,
2409 };
2410}
2411
2412/*
2413 * This is the main function to make a loan payment.
2414 * This function handles regular, late, full, and overpayments.
2415 * It is an implementation of the make_payment function from the XLS-66
2416 * spec. Section 3.2.4.4
2417 */
2418std::expected<LoanPaymentParts, TER>
2420 Asset const& asset,
2421 ApplyView& view,
2422 SLE::Ref loan,
2423 SLE::ConstRef brokerSle,
2424 STAmount const& amount,
2425 LoanPaymentType const paymentType,
2427{
2428 if (loan->at(sfPaymentRemaining) == 0 || loan->at(sfPrincipalOutstanding) == 0)
2429 {
2430 // Loan complete this is already checked in LoanPay::preclaim()
2431 // LCOV_EXCL_START
2432 JLOG(j.warn()) << "Loan is already paid off.";
2433 return std::unexpected(tecKILLED);
2434 // LCOV_EXCL_STOP
2435 }
2436
2437 // Next payment due date must be set unless the loan is complete
2438 auto const nextDueDateProxy = loan->at(sfNextPaymentDueDate);
2439 if (*nextDueDateProxy == 0)
2440 {
2441 JLOG(j.warn()) << "Loan next payment due date is not set.";
2443 }
2444
2445 XRPL_ASSERT(
2446 *loan->at(sfTotalValueOutstanding) > 0, "xrpl::loanMakePayment : valid total value");
2447
2448 view.update(loan);
2449
2450 // -------------------------------------------------------------
2451 // A late payment not flagged as late overrides all other options.
2452 if (paymentType != LoanPaymentType::Late && isPaymentLate(view, loan))
2453 {
2454 // If the payment is late, and the late flag was not set, it's not
2455 // valid
2456 JLOG(j.warn()) << "Loan payment is overdue. Use the tfLoanLatePayment transaction flag to "
2457 "make a late payment. Loan was created on "
2458 << loan->at(sfStartDate) << ", prev payment due date is "
2459 << loan->at(sfPreviousPaymentDueDate) << ", next payment due date is "
2460 << nextDueDateProxy << ", ledger time is "
2461 << view.parentCloseTime().time_since_epoch().count();
2463 }
2464
2465 switch (paymentType)
2466 {
2468 return detail::makeFullPayment(asset, view, loan, brokerSle, amount, j);
2470 return detail::makeLatePayment(asset, view, loan, brokerSle, amount, j);
2473 return detail::makeRegularPayment(asset, view, loan, brokerSle, amount, paymentType, j);
2474 }
2475
2476 // LCOV_EXCL_START
2477 UNREACHABLE("xrpl::loanMakePayment : invalid payment type");
2479 // LCOV_EXCL_STOP
2480}
2481} // namespace xrpl
T clamp(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
Stream trace() const
Severity stream access functions.
Definition Journal.h:338
Stream warn() const
Definition Journal.h:356
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
AccountID const & getIssuer() const
Definition Asset.cpp:21
bool integral() const
Definition Asset.h:133
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static RoundingMode getround()
constexpr int exponent() const noexcept
Returns the exponent of the external view of the Number.
Definition Number.h:718
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
NetClock::time_point parentCloseTime() const
Returns the close time of the previous ledger.
Definition ReadView.h:106
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
Rules controlling protocol behavior.
Definition Rules.h:40
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
std::string getFullText() const override
bool negative() const noexcept
Definition STAmount.h:484
bool integral() const noexcept
Definition STAmount.h:465
Asset const & asset() const
Definition STAmount.h:496
int exponent() const noexcept
Definition STAmount.h:459
bool isZeroAtScale(int scale) const
Checks if this amount evaluates to zero when constrained to a specific accounting scale.
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
bool isFlag(std::uint32_t) const
Definition STObject.cpp:511
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
TxType getTxnType() const
Definition STTx.h:250
T make_pair(T... args)
T max(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
AccountingDeltas loanPaymentDeltas(LoanPaymentParts const &parts)
AccountingDeltas loanOriginationDeltas(Number const &principalRequested)
Number loanVaultExposure(SLE::ConstRef loanSle)
std::expected< LoanPaymentParts, TER > makeFullPayment(Asset const &asset, ApplyView const &view, SLE::Ref loan, SLE::ConstRef brokerSle, STAmount const &amount, beast::Journal j)
Number computePaymentFactor(Rules const &rules, Number const &periodicRate, std::uint32_t paymentsRemaining)
LoanPaymentParts doPayment(ExtendedPaymentComponents const &payment, SLE::Ref loan)
std::pair< TenthBips16, Number > loanRatesFor(SLE::ConstRef loan, SLE::ConstRef brokerSle)
Number loanPrincipalFromPeriodicPayment(Rules const &rules, Number const &periodicPayment, Number const &periodicRate, std::uint32_t paymentsRemaining)
std::expected< ExtendedPaymentComponents, TER > computeLatePayment(Asset const &asset, ReadView const &view, SLE::ConstRef loan, ExtendedPaymentComponents const &periodic, STAmount const &amount, TenthBips16 managementFeeRate, beast::Journal j)
Number computePowerMinusOneHybrid(Number const &periodicRate, std::uint32_t paymentsRemaining)
Number loanPeriodicPayment(Rules const &rules, Number const &principalOutstanding, Number const &periodicRate, std::uint32_t paymentsRemaining)
int posteriorAssetScale(VaultVersion version, Asset const &asset, int baseScale, Number const &reference, Number const &delta)
Shared core of getPosteriorVaultScale and getPosteriorBrokerCoverScale: the exponent reference + delt...
std::expected< ExtendedPaymentComponents, TER > computeFullPayment(Asset const &asset, ReadView const &view, SLE::ConstRef loan, Number const &periodicRate, STAmount const &amount, TenthBips16 managementFeeRate, beast::Journal j)
Number loanAccruedInterest(Number const &principalOutstanding, Number const &periodicRate, NetClock::time_point parentCloseTime, std::uint32_t startDate, std::uint32_t prevPaymentDate, std::uint32_t paymentInterval)
STAmount roundToPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, STAmount const &delta, Number::RoundingMode roundingMode)
Round a cover outflow delta (cover withdraw, cover clawback, the broker-side decrease of a default's ...
int getPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, Number const &delta)
Return a LoanBroker's posterior live cover exponent after applying an unrounded delta.
std::pair< Number, Number > roundAndSplitInterest(Asset const &asset, Number const &rawInterest, TenthBips16 managementFeeRate, std::int32_t loanScale, Number::RoundingMode mode=Number::getround())
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)
STAmount creditToPosteriorScale(Asset const &asset, Number const &reference, int baseScale, Number const &raw, Number::RoundingMode roundingMode)
Shared core of creditToPosteriorAvailableScale and creditToPosteriorBrokerCoverScale: floors referenc...
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)
std::expected< LoanPaymentParts, TER > makeLatePayment(Asset const &asset, ApplyView const &view, SLE::Ref loan, SLE::ConstRef brokerSle, STAmount const &amount, beast::Journal j)
std::expected< LoanPaymentParts, TER > doOverpayment(Rules const &rules, Asset const &asset, std::int32_t loanScale, ExtendedPaymentComponents const &overpaymentComponents, SLE::Ref loan, Number const &periodicRate, 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)
std::expected< LoanPaymentParts, TER > makeRegularPayment(Asset const &asset, ApplyView const &view, SLE::Ref loan, SLE::ConstRef brokerSle, STAmount const &amount, LoanPaymentType const paymentType, beast::Journal j)
Number computePowerMinusOne(Number const &periodicRate, std::uint32_t paymentsRemaining)
PaymentComponents computePaymentComponents(Rules const &rules, Asset const &asset, std::int32_t scale, Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding, Number const &periodicPayment, Number const &periodicRate, std::uint32_t paymentRemaining, TenthBips16 managementFeeRate)
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
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static constexpr Number kNumZero
Definition Number.h:667
constexpr BaseUInt< Bits, Tag > operator+(BaseUInt< Bits, Tag > const &a, BaseUInt< Bits, Tag > const &b)
Definition base_uint.h:650
void adjustBrokerDebtTotal(SLE::Ref brokerSle, SLE::ConstRef vaultSle, Number const &delta, int vaultScale)
Apply a signed delta to a LoanBroker's DebtTotal: on FixedPrecision Vaults, add the exact delta (Debt...
Number loanPeriodicRate(TenthBips32 interestRate, std::uint32_t paymentInterval)
static auto sum(TCollection const &col)
bool loanOriginationExceedsVaultMaximum(SLE::ConstRef vaultSle, Number const &vaultTotal, Number const &interestDue)
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp, ExpiryComparison comparison=ExpiryComparison::Inclusive)
Determines whether the given expiration time has passed.
Definition View.cpp:52
STAmount debitToPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, STAmount const &amount, Number::RoundingMode roundingMode)
Round a cover debit (cover withdraw, cover clawback, the broker-side decrease of a default's cover cr...
Number operator-(Number const &x, Number const &y)
Definition Number.h:793
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
void adjustImpreciseNumber(NumberProxy value, Number const &adjustment, Asset const &asset, int vaultScale)
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
std::expected< LoanPaymentParts, TER > loanMakePayment(Asset const &asset, ApplyView &view, SLE::Ref loan, SLE::ConstRef brokerSle, STAmount const &amount, LoanPaymentType const paymentType, beast::Journal j)
Number power(Number const &f, unsigned n)
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
TenthBips< std::uint16_t > TenthBips16
Definition Units.h:453
TER checkLoanGuards(Asset const &vaultAsset, Number const &principalRequested, bool expectInterest, std::uint32_t paymentTotal, LoanProperties const &properties, beast::Journal j)
STAmount roundToScale(STAmount const &value, std::int32_t scale, Number::RoundingMode rounding=Number::getround())
Round an arbitrary precision Amount to the precision of an STAmount that has a given exponent.
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
bool isPaymentLate(ReadView const &view, SLE::ConstRef loanSle)
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.
int getVaultBaseScale(SLE::ConstRef vault)
Return the Vault's base exponent.
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)
TER checkOptionalBrokerCoverInflow(SLE::ConstRef vault, SLE::ConstRef broker, STAmount const &amount)
Check whether amount is an admissible optional cover inflow.
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:745
Number roundPeriodicPayment(Asset const &asset, Number const &periodicPayment, std::int32_t scale)
Ensure the periodic payment is always rounded consistently.
Number computeManagementFee(Asset const &asset, Number const &interest, TenthBips32 managementFeeRate, std::int32_t scale)
Number getVaultOpenLimit(SLE::ConstRef vault)
Open-zone capacity ceiling: 9 * 10^(15 + baseScale).
TERSubset< CanCvtToTER > TER
Definition TER.h:657
Number loanVaultExposure(SLE::ConstRef vaultSle, SLE::ConstRef loanSle)
@ tecINTERNAL
Definition TER.h:321
@ tecTOO_SOON
Definition TER.h:329
@ tecEXPIRED
Definition TER.h:325
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecKILLED
Definition TER.h:327
@ tecLIMIT_EXCEEDED
Definition TER.h:372
@ tecINSUFFICIENT_PAYMENT
Definition TER.h:338
static constexpr std::uint32_t kSecondsInYear
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)
VaultVersion getVaultVersion(SLE::ConstRef vault)
Resolves a Vault's LEVersion.
AccountingDeltas loanOriginationDeltas(SLE::ConstRef vaultSle, Number const &principalRequested, Number const &interestDue)
LoanState constructLoanState(Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding)
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
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)
bool checkLendingProtocolDependencies(Rules const &rules, STTx const &tx)
STAmount creditToPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, Number const &raw, Number::RoundingMode roundingMode)
Round a cover inflow (cover deposit, LoanPay's fee redirect into cover) into CoverAvailable by floori...
bool isRounded(Asset const &asset, Number const &value, std::int32_t scale)
The accounts and asset that LoanManage::defaultLoan's fixCleanup3_4_0 freeze/lock exemption applies t...
bool operator==(LoanPaymentParts const &other) const
LoanPaymentParts & operator+=(LoanPaymentParts const &other)
This structure captures the parts of a loan state.
Number principalOutstanding
Number total() const
Calculates the total change across all components.
Number trackedInterestPart() const
Calculates the tracked interest portion of this payment.
T time_since_epoch(T... args)
T unexpected(T... args)