xrpld
Loading...
Searching...
No Matches
LoanPay.cpp
1#include <xrpl/tx/transactors/lending/LoanPay.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/json/to_string.h>
9#include <xrpl/ledger/ReadView.h>
10#include <xrpl/ledger/helpers/LendingHelpers.h>
11#include <xrpl/ledger/helpers/TokenHelpers.h>
12#include <xrpl/ledger/helpers/VaultHelpers.h>
13#include <xrpl/protocol/AccountID.h>
14#include <xrpl/protocol/Asset.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/Indexes.h>
17#include <xrpl/protocol/LedgerFormats.h>
18#include <xrpl/protocol/Protocol.h>
19#include <xrpl/protocol/SField.h>
20#include <xrpl/protocol/STAmount.h>
21#include <xrpl/protocol/STLedgerEntry.h>
22#include <xrpl/protocol/STTakesAsset.h>
23#include <xrpl/protocol/STTx.h>
24#include <xrpl/protocol/TER.h>
25#include <xrpl/protocol/TxFlags.h>
26#include <xrpl/protocol/Units.h>
27#include <xrpl/protocol/XRPAmount.h>
28#include <xrpl/tx/Transactor.h>
29#include <xrpl/tx/transactors/lending/LoanManage.h>
30
31#include <algorithm>
32#include <bit>
33#include <cstdint>
34#include <expected>
35#include <vector>
36
37namespace xrpl {
38
39namespace {
40// Returns true if the transaction's payment amount is malformed. A loan
41// payment must be strictly positive: zero would move nothing, and a negative
42// amount is not a payment at all.
43bool
44isPaymentAmountInvalid(STAmount const& amount)
45{
46 return amount <= beast::kZero;
47}
48
49// Returns the balance stored on the ledger for a holder of `asset`: the raw
50// XRP balance (not xrpLiquid, which subtracts the reserve), or the signed
51// trust line or MPToken balance with no trust limit added. Not meaningful for
52// the issuer, which holds no balance of its own.
54storedBalance(ReadView const& view, AccountID const& id, Asset const& asset, beast::Journal j)
55{
56 if (isXRP(asset))
57 {
58 auto const sle = view.read(keylet::account(id));
59 if (!sle)
60 return STAmount{asset}; // LCOV_EXCL_LINE
61 return view.balanceHookIOU(id, xrpAccount(), sle->getFieldAmount(sfBalance));
62 }
63 return accountHolds(
64 view,
65 id,
66 asset,
69 j,
71}
72
73// Returns the account's balance in `asset`, for use only in fund-conservation
74// checks. A holder's is its stored balance: a spendable balance would add the
75// opposite trust limit, which can hide a small credit in rounding. An issuer
76// has no stored balance, so its spendable balance is used instead.
78conservationBalance(ReadView const& view, AccountID const& id, Asset const& asset, beast::Journal j)
79{
80 if (id != asset.getIssuer())
81 return storedBalance(view, id, asset, j);
82 return accountHolds(
83 view,
84 id,
85 asset,
88 j,
90}
91} // namespace
92
93bool
98
101{
102 return tfLoanPayMask;
103}
104
105NotTEC
107{
108 if (ctx.tx[sfLoanID] == beast::kZero)
109 return temINVALID;
110
111 if (isPaymentAmountInvalid(ctx.tx[sfAmount]))
112 return temBAD_AMOUNT;
113
114 // The loan payment flags are all mutually exclusive. If more than one is
115 // set, the tx is malformed.
116 static_assert(
117 (tfLoanLatePayment | tfLoanFullPayment | tfLoanOverpayment) ==
118 ~(tfLoanPayMask | tfUniversal));
119 auto const flagsSet = ctx.tx.getFlags() & ~(tfLoanPayMask | tfUniversal);
120 if (std::popcount(flagsSet) > 1)
121 {
122 JLOG(ctx.j.warn()) << "Only one LoanPay flag can be set per tx. " << flagsSet
123 << " is too many.";
124 return temINVALID_FLAG;
125 }
126
127 return tesSUCCESS;
128}
129
132{
133 auto const fixEnabled313 = view.rules().enabled(fixCleanup3_1_3);
134 auto const fixEnabled340 = view.rules().enabled(fixCleanup3_4_0);
135
136 using namespace lending;
137
138 auto const normalCost = Transactor::calculateBaseFee(view, tx);
139
140 if (fixEnabled340 && isPaymentAmountInvalid(tx[sfAmount]))
141 {
142 // Let preflight worry about the error for this
143 return normalCost;
144 }
145
146 if (tx.isFlag(tfLoanFullPayment) || tx.isFlag(tfLoanLatePayment))
147 {
148 // The loan will be making one set of calculations for one full or late
149 // payment
150 return normalCost;
151 }
152
153 // The fee is based on the potential number of payments, unless the loan is
154 // being fully paid off.
155 auto const amount = tx[sfAmount];
156 auto const loanID = tx[sfLoanID];
157
158 auto const loanSle = view.read(keylet::loan(loanID));
159 if (!loanSle)
160 {
161 // Let preclaim worry about the error for this
162 return normalCost;
163 }
164
165 if (loanSle->at(sfPaymentRemaining) <= kLoanPaymentsPerFeeIncrement)
166 {
167 // If there are fewer than kLoanPaymentsPerFeeIncrement payments left to
168 // pay, we can skip the computations.
169 return normalCost;
170 }
171
172 if (isPaymentLate(view, loanSle))
173 {
174 // If the payment is late, and the late payment flag is not set, it'll
175 // fail. Uses isPaymentLate() so the fee matches apply at the exact
176 // NextPaymentDueDate boundary (Exclusive once fixCleanup3_4_0 is
177 // enabled): a catch-up at that instant can still process up to
178 // kLoanMaximumPaymentsPerTransaction payments.
179 return normalCost;
180 }
181
182 auto const brokerSle = view.read(keylet::loanBroker(loanSle->at(sfLoanBrokerID)));
183 if (!brokerSle)
184 {
185 // Let preclaim worry about the error for this
186 return normalCost;
187 }
188 auto const vaultSle = view.read(keylet::vault(brokerSle->at(sfVaultID)));
189 if (!vaultSle)
190 {
191 // Let preclaim worry about the error for this
192 return normalCost;
193 }
194
195 auto const asset = vaultSle->at(sfAsset);
196
197 if (asset != amount.asset())
198 {
199 // Let preclaim worry about the error for this
200 return normalCost;
201 }
202
203 auto const scale = loanSle->at(sfLoanScale);
204
205 auto const regularPayment = roundPeriodicPayment(asset, loanSle->at(sfPeriodicPayment), scale) +
206 loanSle->at(sfLoanServiceFee);
207
208 // If making an overpayment, count it as a full payment because it will do
209 // about the same amount of work, if not more.
210 NumberRoundModeGuard const mg(
211 tx.isFlag(tfLoanOverpayment) ? Number::RoundingMode::Upward
213
214 static_assert(kLoanMaximumPaymentsPerTransaction % kLoanPaymentsPerFeeIncrement == 0);
215 static constexpr std::int64_t kMaxFeeIncrements =
216 kLoanMaximumPaymentsPerTransaction / kLoanPaymentsPerFeeIncrement;
217
218 if (fixEnabled313 && amount >= regularPayment * kLoanMaximumPaymentsPerTransaction)
219 {
220 // The payment handler will never process more than
221 // loanMaximumPaymentsPerTransaction payments (including overpayments),
222 // and one fee increment is charged for every
223 // loanPaymentsPerFeeIncrement, so don't charge more than
224 // loanMaximumPaymentsPerTransaction / loanPaymentsPerFeeIncrement fee
225 // increments.
226 return kMaxFeeIncrements * normalCost;
227 }
228
229 // Estimate how many payments will be made
230 Number const numPaymentEstimate = static_cast<std::int64_t>(amount / regularPayment);
231
232 // Charge one base fee per paymentsPerFeeIncrement payments, rounding up.
233 // This set round is safe because there's a mode guard just above
235 auto const feeIncrements = std::max(
236 std::int64_t(1),
237 static_cast<std::int64_t>(numPaymentEstimate / kLoanPaymentsPerFeeIncrement));
238 XRPL_ASSERT(
239 !view.rules().enabled(fixCleanup3_1_3) || feeIncrements <= kMaxFeeIncrements,
240 "xrpl::LoanPay::calculateBaseFee : number of fee increments is in "
241 "range");
242
243 return feeIncrements * normalCost;
244}
245
246TER
248{
249 auto const& tx = ctx.tx;
250
251 auto const account = tx[sfAccount];
252 auto const loanID = tx[sfLoanID];
253 auto const amount = tx[sfAmount];
254
255 auto const loanSle = ctx.view.read(keylet::loan(loanID));
256 if (!loanSle)
257 {
258 JLOG(ctx.j.warn()) << "Loan does not exist.";
259 return tecNO_ENTRY;
260 }
261
262 if (loanSle->at(sfBorrower) != account)
263 {
264 JLOG(ctx.j.warn()) << "Loan does not belong to the account.";
265 return tecNO_PERMISSION;
266 }
267
268 if (tx.isFlag(tfLoanOverpayment) && !loanSle->isFlag(lsfLoanOverpayment))
269 {
270 JLOG(ctx.j.warn()) << "Requested overpayment on a loan that doesn't allow it";
271 return ctx.view.rules().enabled(fixCleanup3_1_3) ? TER{tecNO_PERMISSION} : temINVALID_FLAG;
272 }
273
274 auto const principalOutstanding = loanSle->at(sfPrincipalOutstanding);
275 auto const paymentRemaining = loanSle->at(sfPaymentRemaining);
276
277 if (paymentRemaining == 0 || principalOutstanding == 0)
278 {
279 JLOG(ctx.j.warn()) << "Loan is already paid off.";
280 return tecKILLED;
281 }
282
283 auto const loanBrokerID = loanSle->at(sfLoanBrokerID);
284 auto const loanBrokerSle = ctx.view.read(keylet::loanBroker(loanBrokerID));
285 if (!loanBrokerSle)
286 {
287 // This should be impossible
288 // LCOV_EXCL_START
289 JLOG(ctx.j.fatal()) << "LoanBroker does not exist.";
290 return tefBAD_LEDGER;
291 // LCOV_EXCL_STOP
292 }
293 auto const vaultID = loanBrokerSle->at(sfVaultID);
294 auto const vaultSle = ctx.view.read(keylet::vault(vaultID));
295 if (!vaultSle)
296 {
297 // This should be impossible
298 // LCOV_EXCL_START
299 JLOG(ctx.j.fatal()) << "Vault does not exist.";
300 return tefBAD_LEDGER;
301 // LCOV_EXCL_STOP
302 }
303 auto const asset = vaultSle->at(sfAsset);
304 auto const vaultPseudoAccount = vaultSle->at(sfAccount);
305
306 if (amount.asset() != asset)
307 {
308 JLOG(ctx.j.warn()) << "Loan amount does not match the Vault asset.";
309 return tecWRONG_ASSET;
310 }
311
312 if (auto const ret = checkFrozen(ctx.view, account, asset))
313 {
314 JLOG(ctx.j.warn()) << "Borrower account is frozen.";
315 return ret;
316 }
317 if (auto const ret = checkDeepFrozen(ctx.view, vaultPseudoAccount, asset))
318 {
319 JLOG(ctx.j.warn()) << "Vault pseudo-account can not receive funds (deep frozen).";
320 return ret;
321 }
322 if (auto const ret = requireAuth(ctx.view, asset, account))
323 {
324 JLOG(ctx.j.warn()) << "Borrower account is not authorized.";
325 return ret;
326 }
327 // Make sure the borrower has enough funds to make the payment!
328 // Do not support "partial payments" - if the transaction says to pay X,
329 // then the account must have X available, even if the loan payment takes
330 // less.
331 if (auto const balance = accountHolds(
332 ctx.view,
333 account,
334 asset,
337 ctx.j,
339 balance < amount)
340 {
341 JLOG(ctx.j.warn()) << "Payment amount too large. Amount: " << to_string(amount.getJson())
342 << ". Balance: " << to_string(balance.getJson());
344 }
345
346 return tesSUCCESS;
347}
348
349TER
351{
352 auto const& tx = ctx_.tx;
353 auto& view = ctx_.view();
354
355 auto const amount = tx[sfAmount];
356
357 auto const loanID = tx[sfLoanID];
358 auto const loanSle = view.peek(keylet::loan(loanID));
359 if (!loanSle)
360 return tefBAD_LEDGER; // LCOV_EXCL_LINE
361 std::int32_t const loanScale = loanSle->at(sfLoanScale);
362
363 auto const brokerID = loanSle->at(sfLoanBrokerID);
364 auto const brokerSle = view.peek(keylet::loanBroker(brokerID));
365 if (!brokerSle)
366 return tefBAD_LEDGER; // LCOV_EXCL_LINE
367 auto const brokerOwner = brokerSle->at(sfOwner);
368 auto const brokerPseudoAccount = brokerSle->at(sfAccount);
369 auto const vaultID = brokerSle->at(sfVaultID);
370 auto const vaultSle = view.peek(keylet::vault(vaultID));
371 if (!vaultSle)
372 return tefBAD_LEDGER; // LCOV_EXCL_LINE
373 auto const vaultPseudoAccount = vaultSle->at(sfAccount);
374 auto const asset = *vaultSle->at(sfAsset);
375
376 // Determine where to send the broker's fee
377 TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)};
378 auto debtTotalProxy = brokerSle->at(sfDebtTotal);
379
380 bool const fixedPrecision = getVaultVersion(vaultSle) == VaultVersion::FixedPrecision;
381 auto const vaultScale = getVaultScale(vaultSle);
382
383 // Send the broker fee to the owner if they have sufficient cover available,
384 // _and_ if the owner can receive funds
385 // _and_ if the broker is authorized to hold funds. If not, so as not to
386 // block the payment, add it to the cover balance (send it to the broker
387 // pseudo account).
388 //
389 // Normally freeze status is checked in preclaim, but we do it here to
390 // avoid duplicating the check. It'll claim a fee either way.
391 bool const sendBrokerFeeToOwner = [&] {
392 // In the fixCleanup3_2_0 path, vault-related values (for example,
393 // DebtTotal) use vaultScale. The legacy path below intentionally retains
394 // its pre-amendment loanScale behavior.
395 auto const minCover = [&] {
396 if (view.rules().enabled(fixCleanup3_2_0))
397 {
398 return minimumBrokerCover(debtTotalProxy.value(), coverRateMinimum, vaultSle);
399 }
400 // Round the minimum required cover up to be conservative. This ensures
401 // CoverAvailable never drops below the theoretical minimum, protecting
402 // the broker's solvency.
404 return roundToAsset(
405 asset, tenthBipsOfValue(debtTotalProxy.value(), coverRateMinimum), loanScale);
406 }();
407 return brokerSle->at(sfCoverAvailable) >= minCover &&
408 !isDeepFrozen(view, brokerOwner, asset) &&
409 !requireAuth(view, asset, brokerOwner, AuthType::StrongAuth);
410 }();
411
412 auto const brokerPayee = sendBrokerFeeToOwner ? brokerOwner : brokerPseudoAccount;
413 auto const brokerPayeeSle = view.peek(keylet::account(brokerPayee));
414 if (!sendBrokerFeeToOwner)
415 {
416 // If we can't send the fee to the owner, and the pseudo-account is
417 // frozen, then we have to fail the payment.
418 if (auto const ret = checkDeepFrozen(view, brokerPayee, asset))
419 {
420 JLOG(j_.warn()) << "Both Loan Broker and Loan Broker pseudo-account "
421 "can not receive funds (deep frozen).";
422 return ret;
423 }
424 }
425
426 //------------------------------------------------------
427 // Loan object state changes
428
429 // Unimpair the loan if it was impaired. Do this before the payment is
430 // attempted, so the original values can be used. If the payment fails, this
431 // change will be discarded.
432 if (loanSle->isFlag(lsfLoanImpaired))
433 {
434 if (auto const ret = LoanManage::unimpairLoan(view, loanSle, vaultSle, asset, j_))
435 {
436 JLOG(j_.fatal()) << "Failed to unimpair loan before payment.";
437 return ret; // LCOV_EXCL_LINE
438 }
439 }
440
441 auto const scheduledInterest = [&loanSle] {
442 return loanSle->at(sfTotalValueOutstanding) - loanSle->at(sfPrincipalOutstanding) -
443 loanSle->at(sfManagementFeeOutstanding);
444 };
445 Number const scheduledInterestBefore = fixedPrecision ? scheduledInterest() : kNumZero;
446
447 LoanPaymentType const paymentType = [&tx] {
448 // preflight already checked that at most one flag is set.
449 if (tx.isFlag(tfLoanLatePayment))
451 if (tx.isFlag(tfLoanFullPayment))
453 if (tx.isFlag(tfLoanOverpayment))
456 }();
457
458 std::expected<LoanPaymentParts, TER> const paymentParts =
459 loanMakePayment(asset, view, loanSle, brokerSle, amount, paymentType, j_);
460 if (!paymentParts)
461 {
462 XRPL_ASSERT_PARTS(
463 paymentParts.error(), "xrpl::LoanPay::doApply", "payment error is an error");
464 return paymentParts.error();
465 }
466
467 // If the payment computation completed without error, the loanSle object has been modified.
468 view.update(loanSle);
469
470 Number const scheduledInterestDelta =
471 fixedPrecision ? scheduledInterest() - scheduledInterestBefore : kNumZero;
472
473 XRPL_ASSERT_PARTS(
474 // It is possible to pay 0 principal
475 paymentParts->principalPaid >= 0,
476 "xrpl::LoanPay::doApply",
477 "valid principal paid");
478 XRPL_ASSERT_PARTS(
479 // It is possible to pay 0 interest
480 paymentParts->interestPaid >= 0,
481 "xrpl::LoanPay::doApply",
482 "valid interest paid");
483 XRPL_ASSERT_PARTS(
484 // It should not be possible to pay 0 total
485 paymentParts->principalPaid + paymentParts->interestPaid > 0,
486 "xrpl::LoanPay::doApply",
487 "valid total paid");
488 XRPL_ASSERT_PARTS(paymentParts->feePaid >= 0, "xrpl::LoanPay::doApply", "valid fee paid");
489
490 if (paymentParts->principalPaid < 0 || paymentParts->interestPaid < 0 ||
491 paymentParts->feePaid < 0)
492 {
493 // LCOV_EXCL_START
494 JLOG(j_.fatal()) << "Loan payment computation returned invalid values.";
495 return tecLIMIT_EXCEEDED;
496 // LCOV_EXCL_STOP
497 }
498
499 //------------------------------------------------------
500 // LoanBroker object state changes
501 view.update(brokerSle);
502
503 Number const assetsAvailableBefore = *vaultSle->at(sfAssetsAvailable);
504 Number const assetsTotalBefore = vaultSle->at(sfAssetsTotal);
505
506 auto const totalPaidToVaultRaw = paymentParts->principalPaid + paymentParts->interestPaid;
507 auto const deltas = loanPaymentDeltas(vaultSle, *paymentParts);
508 // FixedPrecision never writes sfAssetsTotal directly, so assetsTotalDelta
509 // (cash_basis's interestPaid) is unused here and only meaningful for
510 // Legacy/CashBasis below.
511 Number const assetsTotalDelta = fixedPrecision ? kNumZero : deltas.assetsTotalDelta;
512 Number const debtTotalDelta = deltas.debtTotalDelta;
513 STAmount const totalPaidToVaultRounded = fixedPrecision
514 // Pass the exact Number sum: rounding it to 16 digits first could drop
515 // a tail that moves floor16(AssetsAvailable + sum).
517 vaultSle, totalPaidToVaultRaw, Number::RoundingMode::Downward)
518 : STAmount{
519 asset,
520 roundToAsset(asset, totalPaidToVaultRaw, vaultScale, Number::RoundingMode::Downward)};
521 XRPL_ASSERT_PARTS(
522 !asset.integral() || totalPaidToVaultRaw == Number(totalPaidToVaultRounded),
523 "xrpl::LoanPay::doApply",
524 "rounding does nothing for integral asset");
525 Number const totalPaidToBrokerRaw = paymentParts->feePaid;
526 // Fee redirect into cover is an inflow to CoverAvailable, so it must
527 // floor the sum (see creditToPosteriorBrokerCoverScale's doc), not just
528 // the delta. Legacy/CashBasis keeps the fee as the original, unrounded
529 // Number: only the FixedPrecision path is 16-digit-rounded via STAmount.
530 Number const totalPaidToBroker = fixedPrecision && !sendBrokerFeeToOwner
531 // The exact fee, for the same reason as totalPaidToVaultRounded.
533 vaultSle, brokerSle, totalPaidToBrokerRaw, Number::RoundingMode::Downward))
534 : totalPaidToBrokerRaw;
535
536 JLOG(j_.debug()) << "Loan Pay: principal paid: " << paymentParts->principalPaid
537 << ", interest paid: " << paymentParts->interestPaid
538 << ", fee paid: " << paymentParts->feePaid
539 << ", assets total delta: " << assetsTotalDelta
540 << ", debt total delta: " << debtTotalDelta
541 << ", scheduled interest delta: " << scheduledInterestDelta;
542
543 // Decrease LoanBroker Debt by the amount paid, add the Loan value change
544 // (which might be negative). debtTotalDelta may be negative, increasing the
545 // debt
546 XRPL_ASSERT_PARTS(
547 isRounded(asset, debtTotalDelta, loanScale),
548 "xrpl::LoanPay::doApply",
549 "debtTotalDelta rounding good");
550 // Despite our best efforts, it's possible for rounding errors to accumulate
551 // in the loan broker's debt total on Legacy/CashBasis Vaults. This is because
552 // the broker may have more than one loan with significantly different scales.
553 adjustBrokerDebtTotal(brokerSle, vaultSle, -debtTotalDelta, vaultScale);
554
555 //------------------------------------------------------
556 // Vault object state changes
557 view.update(vaultSle);
558
559 if (fixedPrecision)
560 {
561 // AssetsDeployed drops by exactly the principal paid this payment,
562 // taken from the Loan's own payment split rather than the
563 // broker-side debtTotalDelta.
564 if (auto const ter = adjustVaultBalances(
565 vaultSle,
566 {
567 .cash = totalPaidToVaultRounded,
568 .deployed = -paymentParts->principalPaid,
569 .yield = scheduledInterestDelta,
570 },
571 j_);
572 !isTesSuccess(ter))
573 return ter;
574 }
575 else
576 {
577 vaultSle->at(sfAssetsAvailable) += totalPaidToVaultRounded;
578 vaultSle->at(sfAssetsTotal) += assetsTotalDelta;
579 }
580
581 // Move funds
582 XRPL_ASSERT_PARTS(
583 totalPaidToVaultRounded + totalPaidToBroker <= amount,
584 "xrpl::LoanPay::doApply",
585 "amount is sufficient");
586
587 if (!sendBrokerFeeToOwner)
588 {
589 // If there is not enough first-loss capital, add the fee to First Loss
590 // Cover Pool. FixedPrecision rounds the redirected fee at the
591 // posterior cover scale; any sub-unit remainder is forgiven. The
592 // broker can Withdraw the credited amount later or leave it for future
593 // needs.
594 brokerSle->at(sfCoverAvailable) += totalPaidToBroker;
595 }
596
597 associateAsset(*loanSle, asset);
598 associateAsset(*brokerSle, asset);
599 associateAsset(*vaultSle, asset);
600
601 // Duplicate some checks after rounding
602 Number const assetsAvailableAfter = vaultSle->at(sfAssetsAvailable);
603 Number const assetsTotalAfter = vaultSle->at(sfAssetsTotal);
604
605 if (assetsAvailableAfter == assetsAvailableBefore)
606 {
607 // Credit rounded to zero. On FixedPrecision, if this payment also
608 // closes the Loan (XLS-66 section 3.2.8's terminal exception), let
609 // it through: AssetsDeployed (vault) and DebtTotal (broker) already
610 // dropped by the exact remaining principal, and YieldUnrealized was already
611 // reduced by this payment's scheduled interest, above. No cash moves for the sub-unit
612 // remainder; the Vault forgives it. A non-terminal zero-credit payment is still rejected:
613 // letting it through would change the Loan's schedule with no cash movement at all.
614 if (fixedPrecision && loanSle->at(sfPaymentRemaining) == 0)
615 {
616 JLOG(j_.debug()) << "LoanPay: terminal payment closed the Loan with a zero cash "
617 "credit; the sub-unit remainder is forgiven. Principal: "
618 << paymentParts->principalPaid
619 << ", Interest: " << paymentParts->interestPaid;
620
621 // Nothing moves for this terminal close when the sub-unit remainder is forgiven and
622 // either no fee is owed or the fee goes to the broker owner who is also the borrower,
623 // i.e. the owner would pay itself. Return before the transfer and its conservation
624 // checks, since they assume some transfer happens.
625 if (totalPaidToVaultRounded == beast::kZero &&
626 (totalPaidToBroker == beast::kZero || brokerPayee == accountID_))
627 {
628 return tesSUCCESS;
629 }
630 }
631 else
632 {
633 JLOG(j_.warn()) << "LoanPay: Vault assets available unchanged after rounding: " //
634 << "Before: " << assetsAvailableBefore //
635 << ", After: " << assetsAvailableAfter //
636 << ", Credit: " << totalPaidToVaultRounded //
637 << ", Principal: " << paymentParts->principalPaid //
638 << ", Interest: " << paymentParts->interestPaid;
639 return tecPRECISION_LOSS;
640 }
641 }
642 if (!fixedPrecision && assetsTotalDelta != beast::kZero &&
643 assetsTotalAfter == assetsTotalBefore)
644 {
645 // Non-zero assetsTotalDelta with an unchanged assetsTotal indicates that
646 // the actual value change rounded to zero. That should be impossible, but
647 // I can't rule it out for extreme edge cases, so fail gracefully if it
648 // happens.
649 //
650 // LCOV_EXCL_START
651 JLOG(j_.warn())
652 << "LoanPay: Vault assets expected change, but unchanged after rounding: " //
653 << "Before: " << assetsTotalBefore //
654 << ", After: " << assetsTotalAfter //
655 << ", AssetsTotalDelta: " << assetsTotalDelta;
656 return tecPRECISION_LOSS;
657 // LCOV_EXCL_STOP
658 }
659 if (!fixedPrecision && assetsTotalDelta == beast::kZero &&
660 assetsTotalAfter != assetsTotalBefore)
661 {
662 // A change in assetsTotal when there was no assetsTotalDelta indicates
663 // that something really weird happened. That should be flat out
664 // impossible.
665 //
666 // LCOV_EXCL_START
667 JLOG(j_.fatal()) << "LoanPay: Vault assets changed unexpectedly after rounding: " //
668 << "Before: " << assetsTotalBefore //
669 << ", After: " << assetsTotalAfter //
670 << ", AssetsTotalDelta: " << assetsTotalDelta;
671 return tecINTERNAL;
672 // LCOV_EXCL_STOP
673 }
674 if (assetsAvailableAfter > assetsTotalAfter)
675 {
676 // Assets available are not allowed to be larger than assets total.
677 // LCOV_EXCL_START
678 JLOG(j_.fatal()) << "LoanPay: Vault assets available must not be greater "
679 "than assets outstanding. Available: "
680 << assetsAvailableAfter << ", Total: " << assetsTotalAfter;
681 return tecINTERNAL;
682 // LCOV_EXCL_STOP
683 }
684
685 // These three values are used to check that funds are conserved after the transfers
686 auto const accountBalanceBefore = conservationBalance(view, accountID_, asset, j_);
687 auto const vaultBalanceBefore = accountID_ == vaultPseudoAccount
688 ? STAmount{asset, 0}
689 : conservationBalance(view, vaultPseudoAccount, asset, j_);
690 auto const brokerBalanceBefore = accountID_ == brokerPayee
691 ? STAmount{asset, 0}
692 : conservationBalance(view, brokerPayee, asset, j_);
693
694 // Only ledgers without the rule below reach these payee checks. Once it is in force
695 // requireAuth can no longer reject a pseudo-account, so the whole block goes away with the
696 // gate.
697 bool const skipPayeeAuth = view.rules().enabled(fixCleanup3_4_0);
698
699 if (!skipPayeeAuth && totalPaidToVaultRounded != beast::kZero)
700 {
701 if (auto const ter = requireAuth(view, asset, vaultPseudoAccount, AuthType::StrongAuth))
702 return ter;
703 }
704
705 if (totalPaidToBroker != beast::kZero)
706 {
707 if (brokerPayee == accountID_)
708 {
709 // The broker may have deleted their holding. Recreate it if needed
710 if (auto const ter = addEmptyHolding(
711 ctx_.getApplyViewContext(),
712 brokerPayee,
713 brokerPayeeSle->at(sfBalance).value().xrp(),
714 asset,
715 j_);
716 ter && ter != tecDUPLICATE)
717 {
718 // ignore tecDUPLICATE. That means the holding already exists,
719 // and is fine here
720 return ter;
721 }
722 }
723 if (!skipPayeeAuth)
724 {
725 if (auto const ter = requireAuth(view, asset, brokerPayee, AuthType::StrongAuth))
726 return ter;
727 }
728 }
729
730 if (auto const ter = accountSendMulti(
731 view,
733 asset,
734 {{vaultPseudoAccount, totalPaidToVaultRounded}, {brokerPayee, totalPaidToBroker}},
735 j_,
737 return ter;
738
739 // Check that funds are conserved
740 auto const accountBalanceAfter = conservationBalance(view, accountID_, asset, j_);
741 auto const vaultBalanceAfter = accountID_ == vaultPseudoAccount
742 ? STAmount{asset, 0}
743 : conservationBalance(view, vaultPseudoAccount, asset, j_);
744 auto const brokerBalanceAfter = accountID_ == brokerPayee
745 ? STAmount{asset, 0}
746 : conservationBalance(view, brokerPayee, asset, j_);
747 auto const balanceScale = [&] {
748 // Find a reasonable scale to use for the balance comparisons.
749 //
750 // First find the minimum and maximum exponent of all the non-zero balances, before and
751 // after. If min and max are equal, use that value. If they are not, use "max + 1" to reduce
752 // rounding discrepancies without making the result meaningless. Cap the scale at
753 // STAmount::kMaxOffset, just in case the numbers are all very large.
754 std::vector<int> exponents;
755 exponents.reserve(6);
756
757 for (auto const& a : {
758 accountBalanceBefore,
759 vaultBalanceBefore,
760 brokerBalanceBefore,
761 accountBalanceAfter,
762 vaultBalanceAfter,
763 brokerBalanceAfter,
764 })
765 {
766 // Exclude zeroes
767 if (a != beast::kZero)
768 exponents.push_back(a.exponent());
769 }
770 if (exponents.empty())
771 {
772 UNREACHABLE("xrpl::LoanPay::doApply : all zeroes");
773 return 0;
774 }
775 auto const [minItr, maxItr] = std::ranges::minmax_element(exponents);
776 auto const min = *minItr;
777 auto const max = *maxItr;
778 JLOG(j_.trace()) << "Min scale: " << min << ", max scale: " << max;
779 // IOU rounding can be interesting. We want all the balance checks to agree, but don't want
780 // to round to such an extreme that it becomes meaningless. e.g. Everything rounds to one
781 // digit. So add 1 to the max (reducing the number of digits after the decimal point by 1)
782 // if the scales are not already all the same.
783 return std::min(min == max ? max : max + 1, STAmount::kMaxOffset);
784 }();
785
786 // No object changes are made below this point
788
789 auto const accountBalanceBeforeRounded = roundToScale(accountBalanceBefore, balanceScale);
790 auto const vaultBalanceBeforeRounded = roundToScale(vaultBalanceBefore, balanceScale);
791 auto const brokerBalanceBeforeRounded = roundToScale(brokerBalanceBefore, balanceScale);
792
793 auto const totalBalanceBefore = accountBalanceBefore + vaultBalanceBefore + brokerBalanceBefore;
794 auto const totalBalanceBeforeRounded = roundToScale(totalBalanceBefore, balanceScale);
795
796 JLOG(j_.trace()) << "Before: " //
797 << "account " << Number(accountBalanceBeforeRounded) << " ("
798 << Number(accountBalanceBefore) << ")"
799 << ", vault " << Number(vaultBalanceBeforeRounded) << " ("
800 << Number(vaultBalanceBefore) << ")"
801 << ", broker " << Number(brokerBalanceBeforeRounded) << " ("
802 << Number(brokerBalanceBefore) << ")"
803 << ", total " << Number(totalBalanceBeforeRounded) << " ("
804 << Number(totalBalanceBefore) << ")";
805
806 auto const accountBalanceAfterRounded = roundToScale(accountBalanceAfter, balanceScale);
807 auto const vaultBalanceAfterRounded = roundToScale(vaultBalanceAfter, balanceScale);
808 auto const brokerBalanceAfterRounded = roundToScale(brokerBalanceAfter, balanceScale);
809
810 auto const totalBalanceAfter = accountBalanceAfter + vaultBalanceAfter + brokerBalanceAfter;
811 auto const totalBalanceAfterRounded = roundToScale(totalBalanceAfter, balanceScale);
812
813 JLOG(j_.trace()) << "After: " //
814 << "account " << Number(accountBalanceAfterRounded) << " ("
815 << Number(accountBalanceAfter) << ")"
816 << ", vault " << Number(vaultBalanceAfterRounded) << " ("
817 << Number(vaultBalanceAfter) << ")"
818 << ", broker " << Number(brokerBalanceAfterRounded) << " ("
819 << Number(brokerBalanceAfter) << ")"
820 << ", total " << Number(totalBalanceAfterRounded) << " ("
821 << Number(totalBalanceAfter) << ")";
822
823 auto const accountBalanceChange = accountBalanceAfter - accountBalanceBefore;
824 auto const vaultBalanceChange = vaultBalanceAfter - vaultBalanceBefore;
825 auto const brokerBalanceChange = brokerBalanceAfter - brokerBalanceBefore;
826
827 auto const totalBalanceChange = accountBalanceChange + vaultBalanceChange + brokerBalanceChange;
828 auto const totalBalanceChangeRounded = roundToScale(totalBalanceChange, balanceScale);
829
830 JLOG(j_.trace()) << "Changes: " //
831 << "account " << to_string(accountBalanceChange) //
832 << ", vault " << to_string(vaultBalanceChange) //
833 << ", broker " << to_string(brokerBalanceChange) //
834 << ", total " << to_string(totalBalanceChangeRounded) << " ("
835 << Number(totalBalanceChange) << ")";
836
837 // Each trust line rounds its own change to 16 digits, so a side can move by up to one unit
838 // of its balance less or more than was sent. Integral assets move exactly.
839 auto const roundingUnit = [&](STAmount const& before, STAmount const& after) {
840 Number unit{0};
841 if (asset.integral())
842 return unit;
843 for (auto const& balance : {before, after})
844 {
845 if (balance != beast::kZero)
846 unit = std::max(unit, Number{1, balance.exponent()});
847 }
848 return unit;
849 };
850 Number const accountUnit = roundingUnit(accountBalanceBefore, accountBalanceAfter);
851 Number const vaultUnit = roundingUnit(vaultBalanceBefore, vaultBalanceAfter);
852 Number const brokerUnit = roundingUnit(brokerBalanceBefore, brokerBalanceAfter);
853
854 bool const goodRounding = totalBalanceBeforeRounded == totalBalanceAfterRounded ||
855 totalBalanceChangeRounded == beast::kZero ||
856 abs(Number(totalBalanceChange)) <= accountUnit + vaultUnit + brokerUnit;
857 if (totalBalanceBeforeRounded != totalBalanceAfterRounded)
858 {
859 JLOG((goodRounding ? j_.debug() : j_.warn()))
860 << "Total rounded balances don't match"
861 << (totalBalanceChangeRounded == beast::kZero ? ", but total changes do" : "");
862 }
863 if (totalBalanceChangeRounded != beast::kZero)
864 {
865 JLOG((goodRounding ? j_.debug() : j_.warn()))
866 << "Total balance changes don't match"
867 << (totalBalanceBeforeRounded == totalBalanceAfterRounded ? ", but total balances do"
868 : "");
869 }
870
871 // Rounding for IOUs can be weird, so check a few different ways to show
872 // that funds are conserved.
873 XRPL_ASSERT_PARTS(
874 goodRounding, "xrpl::LoanPay::doApply", "funds are conserved (with rounding)");
875
876 XRPL_ASSERT_PARTS(
877 // A payment below one unit of the payer's balance can round away on its trust line. A fee
878 // the owner-borrower pays to itself does not leave its balance.
879 accountBalanceAfter < accountBalanceBefore || accountID_ == asset.getIssuer() ||
880 (accountBalanceAfter == accountBalanceBefore &&
881 totalPaidToVaultRounded +
882 (brokerPayee == accountID_ ? Number{0} : totalPaidToBroker) <=
883 accountUnit),
884 "xrpl::LoanPay::doApply",
885 "account balance decreased");
886 XRPL_ASSERT_PARTS(
887 // A broker owner may owe the issuer on a reciprocal IOU trust line, so
888 // its stored balance can be negative. Pseudo-accounts cannot.
889 vaultBalanceAfter >= beast::kZero &&
890 (brokerBalanceAfter >= beast::kZero || (sendBrokerFeeToOwner && !asset.integral())),
891 "xrpl::LoanPay::doApply",
892 "non-negative vault and broker balances");
893 XRPL_ASSERT_PARTS(
894 vaultBalanceAfter >= vaultBalanceBefore,
895 "xrpl::LoanPay::doApply",
896 "vault balance did not decrease");
897 XRPL_ASSERT_PARTS(
898 brokerBalanceAfter >= brokerBalanceBefore,
899 "xrpl::LoanPay::doApply",
900 "broker balance did not decrease");
901 XRPL_ASSERT_PARTS(
902 // An IOU issuer's spendable balance does not change when it is paid, and a credit below
903 // one unit of the payee's balance can round away on its trust line.
904 vaultBalanceAfter > vaultBalanceBefore || brokerBalanceAfter > brokerBalanceBefore ||
905 brokerPayee == asset.getIssuer() ||
906 (Number(totalPaidToVaultRounded) <= vaultUnit && totalPaidToBroker <= brokerUnit),
907 "xrpl::LoanPay::doApply",
908 "vault and/or broker balance increased");
909
910 return tesSUCCESS;
911}
912
913void
915{
916 // No transaction-specific invariants yet (future work).
917}
918
919bool
921{
922 // No transaction-specific invariants yet (future work).
923 return true;
924}
925
926//------------------------------------------------------------------------------
927
928} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream warn() const
Definition Journal.h:356
static TER unimpairLoan(ApplyView &view, SLE::Ref loanSle, SLE::Ref vaultSle, Asset const &vaultAsset, beast::Journal j)
Helper function that might be needed by other transactors.
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
Definition LoanPay.cpp:920
static TER preclaim(PreclaimContext const &ctx)
Definition LoanPay.cpp:247
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
Definition LoanPay.cpp:100
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Definition LoanPay.cpp:131
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition LoanPay.cpp:94
TER doApply() override
Definition LoanPay.cpp:350
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Definition LoanPay.cpp:914
static NotTEC preflight(PreflightContext const &ctx)
Definition LoanPay.cpp:106
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static RoundingMode setround(RoundingMode inMode)
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
static constexpr int kMaxOffset
Definition STAmount.h:62
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFlag(std::uint32_t) const
Definition STObject.cpp:511
std::uint32_t getFlags() const
Definition STObject.cpp:517
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
AccountID const accountID_
Definition Transactor.h:166
ApplyContext & ctx_
Definition Transactor.h:162
T empty(T... args)
T max(T... args)
T min(T... args)
T minmax_element(T... args)
constexpr Zero kZero
Definition Zero.h:30
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 account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
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
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...
TER checkDeepFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
bool isXRP(AccountID const &c)
Definition AccountID.h:84
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
@ tefBAD_LEDGER
Definition TER.h:164
TER addEmptyHolding(ApplyViewContext ctx, AccountID const &accountID, XRPAmount priorBalance, MPTIssue const &mptIssue, beast::Journal journal)
int getVaultScale(SLE::ConstRef vault)
Return the Vault's current live exponent.
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)
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
bool isDeepFrozen(ReadView const &view, AccountID const &account, Currency const &currency, AccountID const &issuer)
constexpr FlagValue tfUniversal
Definition TxFlags.h:45
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
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.
TER adjustVaultBalances(SLE::Ref vault, VaultBalanceChange const &change, beast::Journal j)
Apply a balance change to a FixedPrecision Vault.
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
bool isPaymentLate(ReadView const &view, SLE::ConstRef loanSle)
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
AccountingDeltas loanPaymentDeltas(SLE::ConstRef vaultSle, LoanPaymentParts const &parts)
constexpr Number abs(Number x) noexcept
Definition Number.h:880
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
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
Number roundPeriodicPayment(Asset const &asset, Number const &periodicPayment, std::int32_t scale)
Ensure the periodic payment is always rounded consistently.
@ temINVALID
Definition TER.h:98
@ temINVALID_FLAG
Definition TER.h:99
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
AccountID const & xrpAccount()
Compute AccountID from public key.
@ tecWRONG_ASSET
Definition TER.h:371
@ tecNO_ENTRY
Definition TER.h:317
@ tecINTERNAL
Definition TER.h:321
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecKILLED
Definition TER.h:327
@ tecLIMIT_EXCEEDED
Definition TER.h:372
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDUPLICATE
Definition TER.h:326
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
TER accountSendMulti(ApplyView &view, AccountID const &senderID, Asset const &asset, MultiplePaymentDestinations const &receivers, beast::Journal j, WaiveTransferFee waiveFee=WaiveTransferFee::No)
Like accountSend, except one account is sending multiple payments (with the same asset!...
VaultVersion getVaultVersion(SLE::ConstRef vault)
Resolves a Vault's LEVersion.
STAmount creditToPosteriorAvailableScale(SLE::ConstRef vault, Number const &raw, Number::RoundingMode roundingMode)
Round a FixedPrecision cash inflow (LoanPay's credit, LoanManage's default cover credit) into AssetsA...
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const &currency, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
@ tesSUCCESS
Definition TER.h:253
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)
T popcount(T... args)
T push_back(T... args)
T reserve(T... args)
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46