xrpld
Loading...
Searching...
No Matches
LoanSet.cpp
1#include <xrpl/tx/transactors/lending/LoanSet.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/core/ServiceRegistry.h>
8#include <xrpl/ledger/ApplyView.h>
9#include <xrpl/ledger/View.h>
10#include <xrpl/ledger/helpers/AccountRootHelpers.h>
11#include <xrpl/ledger/helpers/CredentialHelpers.h>
12#include <xrpl/ledger/helpers/LendingHelpers.h>
13#include <xrpl/ledger/helpers/SponsorHelpers.h>
14#include <xrpl/ledger/helpers/TokenHelpers.h>
15#include <xrpl/ledger/helpers/VaultHelpers.h>
16#include <xrpl/protocol/AccountID.h>
17#include <xrpl/protocol/Asset.h>
18#include <xrpl/protocol/Feature.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/LedgerFormats.h>
21#include <xrpl/protocol/Protocol.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STAmount.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/STNumber.h>
26#include <xrpl/protocol/STObject.h>
27#include <xrpl/protocol/STTakesAsset.h>
28#include <xrpl/protocol/STTx.h>
29#include <xrpl/protocol/SeqProxy.h>
30#include <xrpl/protocol/TER.h>
31#include <xrpl/protocol/TxFlags.h>
32#include <xrpl/protocol/Units.h>
33#include <xrpl/protocol/XRPAmount.h>
34#include <xrpl/tx/Transactor.h>
35
36#include <cstddef>
37#include <cstdint>
38#include <limits>
39#include <memory>
40#include <optional>
41#include <type_traits>
42#include <vector>
43
44namespace xrpl {
45
46// StartDate is strictly after SubscriptionDate. A min-gap vault must still
47// fit a minimum-interval loan plus kLoanRedemptionBuffer. The interval and
48// buffer constants are independent; only their sum (plus the +1 for a
49// strictly-later StartDate) is required to fit in kMinInvestmentPeriod.
51
52bool
57
60{
61 return tfLoanSetMask;
62}
63
66{
67 using namespace lending;
68
69 auto const& tx = ctx.tx;
70
71 if (tx.isFieldPresent(sfSponsorFlags) && isReserveSponsored(tx))
72 {
73 JLOG(ctx.j.debug()) << "LoanSet: reserve sponsorship is not allowed.";
74 return temINVALID_FLAG;
75 }
76
77 // Special case for Batch inner transactions
78 if (tx.isFlag(tfInnerBatchTxn) && ctx.rules.enabled(featureBatchV1_1) &&
79 !tx.isFieldPresent(sfCounterparty))
80 {
81 auto const parentBatchId = ctx.parentBatchId.value_or(UInt256{0});
82 JLOG(ctx.j.debug()) << "BatchTrace[" << parentBatchId << "]: "
83 << "no Counterparty for inner LoanSet transaction.";
84 return temBAD_SIGNER;
85 }
86
87 // These extra hoops are because STObjects cannot be Proxy'd from STObject.
88 auto const counterPartySig = [&tx] -> std::optional<STObject const> {
89 if (tx.isFieldPresent(sfCounterpartySignature))
90 return tx.getFieldObject(sfCounterpartySignature);
91 return std::nullopt;
92 }();
93 // A proposed LoanSet is stored unsigned; its CounterpartySignature is
94 // collected on-ledger afterward, so its absence here is expected, not an
95 // error (On-Chain Cosigner spec ยง5.3.1.2).
96 if (!tx.isFlag(tfInnerBatchTxn) && !counterPartySig && (ctx.flags & TapProposal) == 0)
97 {
98 JLOG(ctx.j.warn()) << "LoanSet transaction must have a CounterpartySignature.";
99 return temBAD_SIGNER;
100 }
101
102 if (counterPartySig)
103 {
104 if (auto const ret = xrpl::detail::preflightCheckSigningKey(*counterPartySig, ctx.j))
105 return ret;
106 }
107
108 if (auto const data = tx[~sfData];
109 data && !data->empty() && !validDataLength(tx[~sfData], kMaxDataPayloadLength))
110 return temINVALID;
111 for (auto const& field : {&sfLoanServiceFee, &sfLatePaymentFee, &sfClosePaymentFee})
112 {
113 if (!validNumericMinimum(tx[~*field]))
114 return temINVALID;
115 }
116 // Principal Requested is required
117 auto const p = tx[sfPrincipalRequested];
118 if (p <= 0)
119 return temINVALID;
120 if (!validNumericRange(tx[~sfLoanOriginationFee], p))
121 return temINVALID;
122 if (!validNumericRange(tx[~sfInterestRate], kMaxInterestRate))
123 return temINVALID;
124 if (!validNumericRange(tx[~sfOverpaymentFee], kMaxOverpaymentFee))
125 return temINVALID;
126 if (!validNumericRange(tx[~sfLateInterestRate], kMaxLateInterestRate))
127 return temINVALID;
128 if (!validNumericRange(tx[~sfCloseInterestRate], kMaxCloseInterestRate))
129 return temINVALID;
130 if (!validNumericRange(tx[~sfOverpaymentInterestRate], kMaxOverpaymentInterestRate))
131 return temINVALID;
132
133 if (auto const paymentTotal = tx[~sfPaymentTotal]; paymentTotal && *paymentTotal <= 0)
134 return temINVALID;
135
136 auto const paymentInterval = tx[~sfPaymentInterval];
138 return temINVALID; // Grace period is between min default value and payment interval
139 if (auto const gracePeriod = tx[~sfGracePeriod]; !validNumericRange(
140 gracePeriod,
141 paymentInterval.value_or(LoanSet::kDefaultPaymentInterval),
143 {
144 return temINVALID;
145 }
146
147 // Copied from preflight2
148 if (counterPartySig)
149 {
150 if (auto const ret =
151 xrpl::detail::preflightCheckSimulateKeys(ctx.flags, *counterPartySig, ctx.j))
152 return *ret;
153 }
154
155 if (auto const brokerID = ctx.tx[~sfLoanBrokerID]; brokerID && *brokerID == beast::kZero)
156 return temINVALID;
157
158 return tesSUCCESS;
159}
160
161NotTEC
163{
164 if (auto ret = Transactor::checkSign(ctx))
165 return ret;
166
167 // Counter signer is optional. If it's not specified, it's assumed to be
168 // `LoanBroker.Owner`. Note that we have not checked whether the
169 // loanbroker exists at this point.
170 auto const counterSigner = [&] -> std::optional<AccountID> {
171 if (auto const c = ctx.tx.at(~sfCounterparty))
172 return c;
173
174 if (auto const broker = ctx.view.read(keylet::loanBroker(ctx.tx[sfLoanBrokerID])))
175 return broker->at(sfOwner);
176 return std::nullopt;
177 }();
178 if (!counterSigner)
179 return temBAD_SIGNER;
180
181 // Counterparty signature is optional. Presence is checked in preflight.
182 if (!ctx.tx.isFieldPresent(sfCounterpartySignature))
183 return tesSUCCESS;
184 auto const counterSig = ctx.tx.getFieldObject(sfCounterpartySignature);
186 ctx.view, ctx.flags, ctx.parentBatchId, *counterSigner, counterSig, ctx.j);
187}
188
191{
192 auto const normalCost = Transactor::calculateBaseFee(view, tx);
193
194 // Compute the additional cost of each signature in the
195 // CounterpartySignature, whether a single signature or a multisignature
196 XRPAmount const baseFee = view.fees().base;
197
198 // Counterparty signature is optional, but getFieldObject will return an
199 // empty object if it's not present.
200 auto const counterSig = tx.getFieldObject(sfCounterpartySignature);
201 // Each signer adds one more baseFee to the minimum required fee
202 // for the transaction. Note that unlike the base class, the single signer
203 // is counted if present. It will only be absent in a batch inner
204 // transaction.
205 std::size_t const signerCount = [&counterSig] -> int {
206 // Compute defensively.
207 // Assure that "tx" cannot be accessed and cause confusion or miscalculations.
208 if (counterSig.isFieldPresent(sfSigners))
209 return counterSig.getFieldArray(sfSigners).size();
210 return counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0;
211 }();
212
213 return normalCost + (signerCount * baseFee);
214}
215
218{
219 static std::vector<OptionaledField<STNumber>> const kValueFields{
220 ~sfPrincipalRequested,
221 ~sfLoanOriginationFee,
222 ~sfLoanServiceFee,
223 ~sfLatePaymentFee,
224 ~sfClosePaymentFee,
225 // Overpayment fee is really a rate. Don't check it here.
226 };
227
228 return kValueFields;
229}
230
231static std::uint32_t
233{
234 return view.header().closeTime.time_since_epoch().count();
235}
236
237TER
239{
240 auto const& tx = ctx.tx;
241 auto const interval = ctx.tx.at(~sfPaymentInterval).value_or(kDefaultPaymentInterval);
242 auto const total = ctx.tx.at(~sfPaymentTotal).value_or(kDefaultPaymentTotal);
243
244 {
245 // Check for numeric overflow of the schedule before we load any
246 // objects. The Grace Period for the last payment ends at:
247 // startDate + (paymentInterval * paymentTotal) + gracePeriod.
248 // If that value is larger than "maxTime", the value
249 // overflows, and we kill the transaction.
250 using TimeType = decltype(sfNextPaymentDueDate)::type::value_type;
252 constexpr TimeType kMaxTime = std::numeric_limits<TimeType>::max();
253 static_assert(kMaxTime == 4'294'967'295);
254
255 auto const timeAvailable = kMaxTime - getStartDate(ctx.view);
256 auto const grace = ctx.tx.at(~sfGracePeriod).value_or(kDefaultGracePeriod);
257
258 // The grace period can't be larger than the interval. Check it first,
259 // mostly so that unit tests can test that specific case.
260 if (grace > timeAvailable)
261 {
262 JLOG(ctx.j.warn()) << "Grace period exceeds protocol time limit.";
263 return tecKILLED;
264 }
265
266 if (interval > timeAvailable)
267 {
268 JLOG(ctx.j.warn()) << "Payment interval exceeds protocol time limit.";
269 return tecKILLED;
270 }
271
272 if (total > timeAvailable)
273 {
274 JLOG(ctx.j.warn()) << "Payment total exceeds protocol time limit.";
275 return tecKILLED;
276 }
277
278 auto const timeLastPayment = timeAvailable - grace;
279
280 if (timeLastPayment / interval < total)
281 {
282 JLOG(ctx.j.warn()) << "Last payment due date, or grace period for "
283 "last payment exceeds protocol time limit.";
284 return tecKILLED;
285 }
286 }
287
288 auto const account = tx[sfAccount];
289 auto const brokerID = tx[sfLoanBrokerID];
290
291 auto const brokerSle = ctx.view.read(keylet::loanBroker(brokerID));
292 if (!brokerSle)
293 {
294 // This can only be hit if there's a counterparty specified, otherwise
295 // it'll fail in the signature check
296 JLOG(ctx.j.warn()) << "LoanBroker does not exist.";
297 return tecNO_ENTRY;
298 }
299 auto const brokerOwner = brokerSle->at(sfOwner);
300 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
301 if (account != brokerOwner && counterparty != brokerOwner)
302 {
303 JLOG(ctx.j.warn()) << "Neither Account nor Counterparty are the owner "
304 "of the LoanBroker.";
305 return tecNO_PERMISSION;
306 }
307 auto const brokerPseudo = brokerSle->at(sfAccount);
308
309 auto const borrower = counterparty == brokerOwner ? account : counterparty;
310 if (auto const borrowerSle = ctx.view.read(keylet::account(borrower)); !borrowerSle)
311 {
312 // It may not be possible to hit this case, because it'll fail the
313 // signature check with terNO_ACCOUNT.
314 JLOG(ctx.j.warn()) << "Borrower does not exist.";
315 return terNO_ACCOUNT;
316 }
317
318 auto const vault = ctx.view.read(keylet::vault(brokerSle->at(sfVaultID)));
319 if (!vault)
320 {
321 // Should be impossible
322 return tefBAD_LEDGER; // LCOV_EXCL_LINE
323 }
324
325 auto const vaultVersion = getVaultVersion(vault);
326
327 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
328 {
329 auto const phase = getVaultPhase(ctx.view, vault);
330 if (phase == VaultPhase::Subscription)
331 {
332 JLOG(ctx.j.warn()) << "Vault is still in the subscription phase.";
333 return tecTOO_SOON;
334 }
335 if (phase == VaultPhase::Redemption)
336 {
337 JLOG(ctx.j.warn()) << "Vault has entered the redemption phase.";
338 return tecEXPIRED;
339 }
340 if (phase == VaultPhase::Investment)
341 {
342 auto const finalPayment =
343 std::uint64_t{getStartDate(ctx.view)} + (std::uint64_t{interval} * total);
344 if (finalPayment + kLoanRedemptionBuffer > vault->at(sfRedemptionDate))
345 {
346 JLOG(ctx.j.warn())
347 << "Final loan payment date is fewer than " << kLoanRedemptionBuffer
348 << " seconds before the vault's redemption date.";
349 return tecNO_PERMISSION;
350 }
351 }
352 }
353
354 // Instant interest recognition credits interestDue into AssetsTotal, so a vault
355 // already at AssetsMaximum cannot take another loan. Cash-basis origination
356 // does not change AssetsTotal (see cash_basis::loanOriginationDeltas), so
357 // this leftover instant-recognition gate must not apply there.
358 if (vaultVersion < VaultVersion::CashBasis && vault->at(sfAssetsMaximum) != 0 &&
359 vault->at(sfAssetsTotal) >= vault->at(sfAssetsMaximum))
360 {
361 JLOG(ctx.j.warn()) << "Vault at maximum assets limit. Can't add another loan.";
362 return tecLIMIT_EXCEEDED;
363 }
364
365 if (vaultVersion == VaultVersion::FixedPrecision)
366 {
367 // Reject origination if the Vault is already coarsened.
368 if (getVaultScale(vault) != getVaultBaseScale(vault))
369 {
370 JLOG(ctx.j.warn()) << "FixedPrecision Vault is already coarsened; no further loans can "
371 "be originated until it returns to its base scale.";
372 return tecLIMIT_EXCEEDED;
373 }
374 }
375
376 Asset const asset = vault->at(sfAsset);
377
378 auto const vaultPseudo = vault->at(sfAccount);
379
380 // Check that relevant values can be represented as the vault asset type.
381 // This check is almost duplicated in doApply, but that check is done after
382 // the overall loan scale is known. This is mostly only relevant for
383 // integral (non-IOU) types. fixCleanup3_5_0 also rejects out-of-range
384 // values, e.g. XRP above STAmount::kMaxNativeN, which would otherwise throw.
385 bool const fix350Enabled = ctx.view.rules().enabled(fixCleanup3_5_0);
386 for (auto const& field : getValueFields())
387 {
388 if (auto const value = tx[field]; value &&
389 ((fix350Enabled && !isRepresentable(asset, *value)) ||
390 STAmount{asset, *value} != *value))
391 {
392 JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value
393 << ") can not be represented as a(n) " << to_string(asset) << ".";
394 return tecPRECISION_LOSS;
395 }
396 }
397
398 // canAddHolding is an issuer-level check (DefaultRipple for IOU,
399 // lsfMPTCanTransfer for MPT); neither overload looks at the
400 // destination, so the holdingExists() clauses only decide whether a
401 // create path is reachable at all. It always runs before
402 // fixCleanup3_4_0: IOU addEmptyHolding checks DefaultRipple ahead of
403 // the existing-line case, so only preclaim can turn an existing line
404 // under a cleared DefaultRipple into terNO_RIPPLE rather than
405 // tecINTERNAL. After the amendment an existing line short-circuits to
406 // tecDUPLICATE, which doApply ignores, so run the check only when the
407 // borrower lacks a holding, or the origination fee is nonzero and the
408 // broker owner lacks one.
409 auto const originationFee = tx[~sfLoanOriginationFee].value_or(0);
410 if (!ctx.view.rules().enabled(fixCleanup3_4_0) || !holdingExists(ctx.view, borrower, asset) ||
411 (originationFee != beast::kZero && !holdingExists(ctx.view, brokerOwner, asset)))
412 {
413 if (auto const ter = canAddHolding(ctx.view, asset))
414 return ter;
415 }
416
417 // vaultPseudo is going to send funds, so it can't be frozen.
418 if (auto const ret = checkFrozen(ctx.view, vaultPseudo, asset))
419 {
420 JLOG(ctx.j.warn()) << "Vault pseudo-account is frozen.";
421 return ret;
422 }
423
424 // brokerPseudo is the fallback account to receive LoanPay fees, even if the
425 // broker owner is unable to accept them. Don't create the loan if it is
426 // deep frozen.
427 if (auto const ret = checkDeepFrozen(ctx.view, brokerPseudo, asset))
428 {
429 JLOG(ctx.j.warn()) << "Broker pseudo-account is frozen.";
430 return ret;
431 }
432
433 // borrower is eventually going to have to pay back the loan, so it can't be
434 // frozen now. It is also going to receive funds, so it can't be deep
435 // frozen, but being frozen is a prerequisite for being deep frozen, so
436 // checking the one is sufficient.
437 if (auto const ret = checkFrozen(ctx.view, borrower, asset))
438 {
439 JLOG(ctx.j.warn()) << "Borrower account is frozen.";
440 return ret;
441 }
442 // brokerOwner is going to receive funds if there's an origination fee, so
443 // it can't be deep frozen
444 if (auto const ret = checkDeepFrozen(ctx.view, brokerOwner, asset))
445 {
446 JLOG(ctx.j.warn()) << "Broker owner account is frozen.";
447 return ret;
448 }
449
450 return tesSUCCESS;
451}
452
453TER
455{
456 auto const& tx = ctx_.tx;
457 auto& view = ctx_.view();
458
459 auto const brokerID = tx[sfLoanBrokerID];
460
461 auto const brokerSle = view.peek(keylet::loanBroker(brokerID));
462 if (!brokerSle)
463 return tefBAD_LEDGER; // LCOV_EXCL_LINE
464 auto const brokerOwner = brokerSle->at(sfOwner);
465 auto const brokerOwnerSle = view.peek(keylet::account(brokerOwner));
466 if (!brokerOwnerSle)
467 return tefBAD_LEDGER; // LCOV_EXCL_LINE
468
469 auto const vaultSle = view.peek(keylet::vault(brokerSle->at(sfVaultID)));
470 if (!vaultSle)
471 return tefBAD_LEDGER; // LCOV_EXCL_LINE
472 auto const vaultPseudo = vaultSle->at(sfAccount);
473 Asset const vaultAsset = vaultSle->at(sfAsset);
474 auto const vaultVersion = getVaultVersion(vaultSle);
475
476 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
477 auto const borrower = counterparty == brokerOwner ? accountID_ : counterparty;
478 auto const borrowerSle = view.peek(keylet::account(borrower));
479 if (!borrowerSle)
480 {
481 return tefBAD_LEDGER; // LCOV_EXCL_LINE
482 }
483
484 auto const brokerPseudo = brokerSle->at(sfAccount);
485 auto const brokerPseudoSle = view.peek(keylet::account(brokerPseudo));
486 if (!brokerPseudoSle)
487 {
488 return tefBAD_LEDGER; // LCOV_EXCL_LINE
489 }
490
491 if (brokerSle->isFlag(lsfLoanBrokerPrivate))
492 {
493 auto const domainID = brokerSle->at(~sfDomainID);
494 if (!domainID)
495 {
496 JLOG(j_.warn()) << "Private LoanBroker must have a DomainID.";
497 return tecNO_AUTH;
498 }
499 if (auto const ter = verifyValidDomain(view, borrower, *domainID, j_); !isTesSuccess(ter))
500 {
501 if (ter == tecNO_PERMISSION)
502 {
503 JLOG(j_.warn()) << "Borrower is not a member of the LoanBroker's domain.";
504 return tecNO_AUTH;
505 }
506 return ter;
507 }
508 }
509
510 auto const principalRequested = tx[sfPrincipalRequested];
511
512 auto vaultAvailableProxy = vaultSle->at(sfAssetsAvailable);
513 auto vaultTotalProxy = vaultSle->at(sfAssetsTotal);
514 // For Legacy/CashBasis, getVaultBaseScale falls through to getVaultScale.
515 auto const vaultScale = getVaultBaseScale(vaultSle);
516 if (vaultAvailableProxy < principalRequested)
517 {
518 JLOG(j_.warn()) << "Insufficient assets available in the Vault to fund the loan.";
520 }
521
522 TenthBips32 const interestRate{tx[~sfInterestRate].value_or(0)};
523
524 auto const paymentInterval = tx[~sfPaymentInterval].value_or(kDefaultPaymentInterval);
525 auto const paymentTotal = tx[~sfPaymentTotal].value_or(kDefaultPaymentTotal);
526
527 auto const properties = computeLoanProperties(
528 view.rules(),
529 vaultAsset,
530 principalRequested,
531 interestRate,
532 paymentInterval,
533 paymentTotal,
534 TenthBips16{brokerSle->at(sfManagementFeeRate)},
535 vaultScale);
536
537 LoanState const state = constructLoanState(
538 properties.loanState.valueOutstanding,
539 principalRequested,
540 properties.loanState.managementFeeDue);
541
542 XRPL_ASSERT_PARTS(
543 *vaultSle->at(sfAssetsMaximum) == 0 || vaultVersion >= VaultVersion::CashBasis ||
544 *vaultSle->at(sfAssetsMaximum) > *vaultTotalProxy,
545 "xrpl::LoanSet::doApply",
546 "instant-recognition vault is below maximum limit");
547
548 if (loanOriginationExceedsVaultMaximum(vaultSle, vaultTotalProxy, state.interestDue))
549 {
550 JLOG(j_.warn()) << "Loan would exceed the maximum assets of the vault";
551 return tecLIMIT_EXCEEDED;
552 }
553 // Check that relevant values won't lose precision. This is mostly only
554 // relevant for IOU assets.
555 for (auto const& field : getValueFields())
556 {
557 if (auto const value = tx[field];
558 value && !isRounded(vaultAsset, *value, properties.loanScale))
559 {
560 JLOG(j_.warn()) << field.f->getName() << " (" << *value
561 << ") has too much precision. Total loan value is "
562 << properties.loanState.valueOutstanding << " with a scale of "
563 << properties.loanScale;
564 return tecPRECISION_LOSS;
565 }
566 }
567
568 if (auto const ret = checkLoanGuards(
569 vaultAsset,
570 principalRequested,
571 interestRate != beast::kZero,
572 paymentTotal,
573 properties,
574 j_))
575 return ret;
576
577 // Check that the other computed values are valid
578 if (properties.loanState.managementFeeDue < 0 || properties.loanState.valueOutstanding <= 0 ||
579 properties.periodicPayment <= 0)
580 {
581 // LCOV_EXCL_START
582 JLOG(j_.warn()) << "Computed loan properties are invalid. Does not compute."
583 << " Management fee: " << properties.loanState.managementFeeDue
584 << ". Total Value: " << properties.loanState.valueOutstanding
585 << ". PeriodicPayment: " << properties.periodicPayment;
586 return tecINTERNAL;
587 // LCOV_EXCL_STOP
588 }
589
590 if (vaultVersion == VaultVersion::FixedPrecision)
591 {
592 // Reject origination if this loan's interest would grow the Vault past its Open-zone
593 // capacity.
594 if (vaultOpenZoneCapacity(vaultSle, state.interestDue) > getVaultOpenLimit(vaultSle))
595 {
596 JLOG(j_.warn()) << "Loan interest would exceed the FixedPrecision Vault's Open zone.";
597 return tecLIMIT_EXCEEDED;
598 }
599 XRPL_ASSERT(
600 properties.loanScale == getVaultBaseScale(vaultSle),
601 "xrpl::LoanSet::doApply : FixedPrecision loan uses Vault base scale");
602 }
603
604 auto const originationFee = tx[~sfLoanOriginationFee].value_or(Number{});
605
606 auto const loanAssetsToBorrower = principalRequested - originationFee;
607
608 auto const [assetsTotalDelta, debtTotalDelta] =
609 loanOriginationDeltas(vaultSle, principalRequested, state.interestDue);
610 auto const newDebtTotal = brokerSle->at(sfDebtTotal) + debtTotalDelta;
611 if (auto const debtMaximum = brokerSle->at(sfDebtMaximum);
612 debtMaximum != 0 && debtMaximum < newDebtTotal)
613 {
614 JLOG(j_.warn()) << "Loan would exceed the maximum debt limit of the LoanBroker.";
615 return tecLIMIT_EXCEEDED;
616 }
617 TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)};
618 {
619 auto const minCover = [&] {
620 if (ctx_.view().rules().enabled(fixCleanup3_2_0))
621 {
622 return minimumBrokerCover(newDebtTotal, coverRateMinimum, vaultSle);
623 }
624
625 // Round the minimum required cover up to be conservative. This ensures
626 // CoverAvailable never drops below the theoretical minimum, protecting
627 // the broker's solvency.
629 return tenthBipsOfValue(newDebtTotal, coverRateMinimum);
630 }();
631 if (brokerSle->at(sfCoverAvailable) < minCover)
632 {
633 JLOG(j_.warn()) << "Insufficient first-loss capital to cover the loan.";
635 }
636 }
637
638 increaseOwnerCount(view, borrowerSle, {}, 1, j_);
639
640 {
641 auto const balance =
642 accountID_ == borrower ? preFeeBalance_ : borrowerSle->at(sfBalance).value().xrp();
643 if (balance < accountReserve(view, borrowerSle, j_))
645 }
646
647 // Account for the origination fee using two payments
648 //
649 // 1. Transfer loanAssetsAvailable (principalRequested - originationFee)
650 // from vault pseudo-account to the borrower.
651 // Create a holding for the borrower if one does not already exist.
652
653 XRPL_ASSERT_PARTS(
654 borrower == accountID_ || borrower == counterparty,
655 "xrpl::LoanSet::doApply",
656 "borrower signed transaction");
657 auto const applyViewContext = ctx_.getApplyViewContext();
658 if (auto const ter = addEmptyHolding(
659 applyViewContext, borrower, borrowerSle->at(sfBalance).value().xrp(), vaultAsset, j_);
660 ter && ter != tecDUPLICATE)
661 {
662 // ignore tecDUPLICATE. That means the holding already exists, and
663 // is fine here
664 return ter;
665 }
666
667 if (auto const ter = requireAuth(view, vaultAsset, borrower, AuthType::StrongAuth))
668 return ter;
669
670 // 2. Transfer originationFee, if any, from vault pseudo-account to
671 // LoanBroker owner.
672 if (originationFee != beast::kZero)
673 {
674 // Create the holding if it doesn't already exist (necessary for MPTs).
675 // The owner may have deleted their MPT / line at some point.
676 XRPL_ASSERT_PARTS(
677 brokerOwner == accountID_ || brokerOwner == counterparty,
678 "xrpl::LoanSet::doApply",
679 "broker owner signed transaction");
680
681 if (auto const ter = addEmptyHolding(
682 applyViewContext,
683 brokerOwner,
684 brokerOwnerSle->at(sfBalance).value().xrp(),
685 vaultAsset,
686 j_);
687 ter && ter != tecDUPLICATE)
688 {
689 // ignore tecDUPLICATE. That means the holding already exists,
690 // and is fine here
691 return ter;
692 }
693 }
694
695 if (auto const ter = requireAuth(view, vaultAsset, brokerOwner, AuthType::StrongAuth))
696 return ter;
697
698 if (auto const ter = accountSendMulti(
699 view,
700 vaultPseudo,
701 vaultAsset,
702 {{borrower, loanAssetsToBorrower}, {brokerOwner, originationFee}},
703 j_,
705 return ter;
706
707 // Get shortcuts to the loan property values
708 auto const startDate = getStartDate(view);
709 auto loanSequenceProxy = brokerSle->at(sfLoanSequence);
710
711 // Create the loan
712 auto loan =
713 std::make_shared<SLE>(keylet::loan(brokerID, SeqProxy::rawSequence(*loanSequenceProxy)));
714
715 // Prevent copy/paste errors
716 auto const setLoanField = [&loan, &tx](auto const& field, std::uint32_t const defValue = 0) {
717 // at() is smart enough to unseat a default field set to the default
718 // value
719 loan->at(field) = tx[field].value_or(defValue);
720 };
721
722 // Set required and fixed tx fields
723 loan->at(sfLoanScale) = properties.loanScale;
724 loan->at(sfStartDate) = startDate;
725 loan->at(sfPaymentInterval) = paymentInterval;
726 loan->at(sfLoanSequence) = *loanSequenceProxy;
727 loan->at(sfLoanBrokerID) = brokerID;
728 loan->at(sfBorrower) = borrower;
729 // Set all other transaction fields directly from the transaction
730 if (tx.isFlag(tfLoanOverpayment))
731 loan->setFlag(lsfLoanOverpayment);
732 setLoanField(~sfLoanOriginationFee);
733 setLoanField(~sfLoanServiceFee);
734 setLoanField(~sfLatePaymentFee);
735 setLoanField(~sfClosePaymentFee);
736 setLoanField(~sfOverpaymentFee);
737 setLoanField(~sfInterestRate);
738 setLoanField(~sfLateInterestRate);
739 setLoanField(~sfCloseInterestRate);
740 setLoanField(~sfOverpaymentInterestRate);
741 setLoanField(~sfGracePeriod, kDefaultGracePeriod);
742 // Set dynamic / computed fields to their initial values
743 loan->at(sfPrincipalOutstanding) = principalRequested;
744 loan->at(sfPeriodicPayment) = properties.periodicPayment;
745 loan->at(sfTotalValueOutstanding) = properties.loanState.valueOutstanding;
746 loan->at(sfManagementFeeOutstanding) = properties.loanState.managementFeeDue;
747 loan->at(sfPreviousPaymentDueDate) = 0;
748 loan->at(sfNextPaymentDueDate) = startDate + paymentInterval;
749 loan->at(sfPaymentRemaining) = paymentTotal;
750 view.insert(loan);
751
752 // Update the balances in the vault
753 if (vaultVersion == VaultVersion::FixedPrecision)
754 {
755 if (auto const ter = adjustVaultBalances(
756 vaultSle,
757 {
758 .cash = -STAmount{vaultAsset, principalRequested},
759 .deployed = debtTotalDelta,
760 .yield = state.interestDue,
761 },
762 j_);
763 !isTesSuccess(ter))
764 return ter; // LCOV_EXCL_LINE
765 }
766 else
767 {
768 vaultAvailableProxy -= principalRequested;
769 vaultTotalProxy += assetsTotalDelta;
770 }
771 XRPL_ASSERT_PARTS(
772 *vaultAvailableProxy <= *vaultTotalProxy,
773 "xrpl::LoanSet::doApply",
774 "assets available must not be greater than assets outstanding");
775 view.update(vaultSle);
776
777 // Update the balances in the loan broker
778 adjustBrokerDebtTotal(brokerSle, vaultSle, debtTotalDelta, vaultScale);
779 adjustLoanBrokerOwnerCount(view, brokerSle, 1, j_);
780 loanSequenceProxy += 1;
781 // The sequence should be extremely unlikely to roll over, but fail if it
782 // does
783 if (loanSequenceProxy == 0)
785 view.update(brokerSle);
786
787 // Put the loan into the pseudo-account's directory
788 if (auto const ter = dirLink(view, brokerPseudo, loan, sfLoanBrokerNode))
789 return ter;
790 // Borrower is the owner of the loan
791 if (auto const ter = dirLink(view, borrower, loan, sfOwnerNode))
792 return ter;
793
794 associateAsset(*vaultSle, vaultAsset);
795 associateAsset(*brokerSle, vaultAsset);
796 associateAsset(*loan, vaultAsset);
797
798 return tesSUCCESS;
799}
800
801void
803{
804 // No transaction-specific invariants yet (future work).
805}
806
807bool
809{
810 // No transaction-specific invariants yet (future work).
811 return true;
812}
813
814//------------------------------------------------------------------------------
815
816} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
Stream warn() const
Definition Journal.h:356
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Definition LoanSet.cpp:802
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
Definition LoanSet.cpp:59
static TER preclaim(PreclaimContext const &ctx)
Definition LoanSet.cpp:238
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Definition LoanSet.cpp:190
static constexpr std::uint32_t kDefaultPaymentTotal
static std::vector< OptionaledField< STNumber > > const & getValueFields()
Definition LoanSet.cpp:217
static NotTEC preflight(PreflightContext const &ctx)
Definition LoanSet.cpp:65
static NotTEC checkSign(PreclaimContext const &ctx)
Definition LoanSet.cpp:162
static constexpr std::uint32_t kDefaultPaymentInterval
static constexpr std::uint32_t kMinPaymentInterval
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 LoanSet.cpp:808
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition LoanSet.cpp:53
TER doApply() override
Definition LoanSet.cpp:454
static constexpr std::uint32_t kDefaultGracePeriod
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
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.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
std::shared_ptr< STLedgerEntry const > const & ConstRef
T::value_type at(TypedField< T > const &f) const
Get the value of a field.
Definition STObject.h:1077
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
STObject getFieldObject(SField const &field) const
Definition STObject.cpp:678
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
static NotTEC checkSign(PreclaimContext const &ctx)
static bool validNumericMinimum(std::optional< T > value, T min=T{})
Minimum will usually be zero.
Definition Transactor.h:712
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
XRPAmount preFeeBalance_
Definition Transactor.h:167
static bool validDataLength(std::optional< Slice > const &slice, std::size_t maxLength)
ApplyContext & ctx_
Definition Transactor.h:162
static bool validNumericRange(std::optional< T > value, T max, T min=T{})
Definition Transactor.h:693
T is_same_v
T make_shared(T... args)
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
std::optional< NotTEC > preflightCheckSimulateKeys(ApplyFlags flags, STObject const &sigObject, beast::Journal j)
Checks the special signing key state needed for simulation.
NotTEC preflightCheckSigningKey(STObject const &sigObject, beast::Journal j)
Checks the validity of the transactor signing key.
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
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)
@ terNO_ACCOUNT
Definition TER.h:219
constexpr FlagValue tfInnerBatchTxn
Definition TxFlags.h:44
Number vaultOpenZoneCapacity(SLE::ConstRef vault, Number const &roundedAmount)
Open-zone capacity after adding roundedAmount: AssetsTotal + YieldUnrealized.
bool loanOriginationExceedsVaultMaximum(SLE::ConstRef vaultSle, Number const &vaultTotal, Number const &interestDue)
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
@ 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.
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
TenthBips< std::uint16_t > TenthBips16
Definition Units.h:453
void increaseOwnerCount(ApplyView &view, SLE::Ref accountSle, SLE::Ref sponsorSle, std::uint32_t count, beast::Journal j)
Increase owner-count fields when the caller supplies the sponsor.
bool isReserveSponsored(STTx const &tx)
Whether the transaction's reserve is sponsored (sfSponsor present + spfSponsorReserve set).
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
constexpr std::size_t kMaxDataPayloadLength
The maximum length of Data payload.
Definition Protocol.h:303
TER checkLoanGuards(Asset const &vaultAsset, Number const &principalRequested, bool expectInterest, std::uint32_t paymentTotal, LoanProperties const &properties, beast::Journal j)
TER adjustVaultBalances(SLE::Ref vault, VaultBalanceChange const &change, beast::Journal j)
Apply a balance change to a FixedPrecision Vault.
BaseUInt< 256 > UInt256
Definition base_uint.h:581
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
TER verifyValidDomain(ApplyView &view, AccountID const &account, UInt256 domainID, beast::Journal j)
void adjustLoanBrokerOwnerCount(ApplyView &view, SLE::Ref brokerSle, std::int32_t delta, beast::Journal j)
Adjust a LoanBroker's owner count.
static std::uint32_t getStartDate(ReadView const &view)
Definition LoanSet.cpp:232
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
int getVaultBaseScale(SLE::ConstRef vault)
Return the Vault's base exponent.
bool isRepresentable(Asset const &asset, Number const &value)
Check whether an arbitrary precision Number can be converted to an STAmount of a given Asset without ...
@ TapProposal
Definition ApplyView.h:53
@ temINVALID
Definition TER.h:98
@ temINVALID_FLAG
Definition TER.h:99
@ temBAD_SIGNER
Definition TER.h:103
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TER dirLink(ApplyView &view, AccountID const &owner, SLE::pointer const &object, SF_UINT64 const &node=sfOwnerNode)
Definition View.cpp:385
Number getVaultOpenLimit(SLE::ConstRef vault)
Open-zone capacity ceiling: 9 * 10^(15 + baseScale).
TERSubset< CanCvtToTER > TER
Definition TER.h:657
XRPAmount accountReserve(ReadView const &view, SLE::ConstRef sle, beast::Journal j, Adjustment adj={})
Returns the account reserve, in drops.
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.
@ tecNO_ENTRY
Definition TER.h:317
@ tecNO_AUTH
Definition TER.h:311
@ tecINTERNAL
Definition TER.h:321
@ tecTOO_SOON
Definition TER.h:329
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecEXPIRED
Definition TER.h:325
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
@ tecKILLED
Definition TER.h:327
@ tecMAX_SEQUENCE_REACHED
Definition TER.h:331
@ 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!...
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)
constexpr std::uint32_t kLoanRedemptionBuffer
Minimum gap between a closed-ended loan's final scheduled payment and the vault's RedemptionDate.
Definition Protocol.h:379
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)
constexpr std::uint32_t kMinInvestmentPeriod
Bounds on the length of a closed-ended vault's Investment phase (RedemptionDate - SubscriptionDate).
Definition Protocol.h:391
@ tesSUCCESS
Definition TER.h:253
bool holdingExists(ReadView const &view, AccountID const &account, Asset const &asset)
True if the account already holds this asset (or is the issuer / XRP).
bool checkLendingProtocolDependencies(Rules const &rules, STTx const &tx)
bool isRounded(Asset const &asset, Number const &value, std::int32_t scale)
NetClock::time_point closeTime
This structure captures the parts of a loan state.
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
std::optional< UInt256 const > const parentBatchId
Definition Transactor.h:99
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
std::optional< UInt256 const > parentBatchId
Definition Transactor.h:45
T time_since_epoch(T... args)