1#include <xrpld/app/tx/detail/LoanSet.h>
3#include <xrpld/app/misc/LendingHelpers.h>
5#include <xrpl/protocol/TxFlags.h>
24 using namespace Lending;
26 auto const& tx = ctx.
tx;
30 !tx.isFieldPresent(sfCounterparty))
33 JLOG(ctx.
j.
debug()) <<
"BatchTrace[" << parentBatchId <<
"]: "
34 <<
"no Counterparty for inner LoanSet transaction.";
40 if (tx.isFieldPresent(sfCounterpartySignature))
41 return tx.getFieldObject(sfCounterpartySignature);
47 <<
"LoanSet transaction must have a CounterpartySignature.";
58 if (
auto const data = tx[~sfData]; data && !data->empty() &&
61 for (
auto const& field :
62 {&sfLoanServiceFee, &sfLatePaymentFee, &sfClosePaymentFee})
68 if (
auto const p = tx[sfPrincipalRequested]; p <= 0)
81 tx[~sfOverpaymentInterestRate], maxOverpaymentInterestRate))
84 if (
auto const paymentTotal = tx[~sfPaymentTotal];
85 paymentTotal && *paymentTotal <= 0)
88 if (
auto const paymentInterval = tx[~sfPaymentInterval];
92 else if (
auto const gracePeriod = tx[~sfGracePeriod];
103 ctx.
flags, *counterPartySig, ctx.
j))
107 if (
auto const brokerID = ctx.
tx[~sfLoanBrokerID];
108 brokerID && *brokerID == beast::zero)
124 if (
auto const c = ctx.
tx.
at(~sfCounterparty))
127 if (
auto const broker =
129 return broker->at(sfOwner);
159 auto const counterSig = tx.
getFieldObject(sfCounterpartySignature);
167 return counterSig.isFieldPresent(sfSigners)
168 ? counterSig.getFieldArray(sfSigners).size()
169 : (counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0);
172 return normalCost + (signerCount * baseFee);
179 ~sfPrincipalRequested,
180 ~sfLoanOriginationFee,
199 auto const& tx = ctx.
tx;
207 using timeType =
decltype(sfNextPaymentDueDate)::type::value_type;
210 static_assert(maxTime == 4'294'967'295);
214 auto const interval =
223 if (grace > timeAvailable)
225 JLOG(ctx.
j.
warn()) <<
"Grace period exceeds protocol time limit.";
229 if (interval > timeAvailable)
232 <<
"Payment interval exceeds protocol time limit.";
236 if (total > timeAvailable)
238 JLOG(ctx.
j.
warn()) <<
"Payment total exceeds protocol time limit.";
242 auto const timeLastPayment = timeAvailable - grace;
244 if (timeLastPayment / interval < total)
246 JLOG(ctx.
j.
warn()) <<
"Last payment due date, or grace period for "
247 "last payment exceeds protocol time limit.";
252 auto const account = tx[sfAccount];
253 auto const brokerID = tx[sfLoanBrokerID];
260 JLOG(ctx.
j.
warn()) <<
"LoanBroker does not exist.";
263 auto const brokerOwner = brokerSle->at(sfOwner);
264 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
265 if (account != brokerOwner && counterparty != brokerOwner)
267 JLOG(ctx.
j.
warn()) <<
"Neither Account nor Counterparty are the owner "
268 "of the LoanBroker.";
271 auto const brokerPseudo = brokerSle->at(sfAccount);
273 auto const borrower = counterparty == brokerOwner ? account : counterparty;
279 JLOG(ctx.
j.
warn()) <<
"Borrower does not exist.";
288 if (vault->at(sfAssetsMaximum) != 0 &&
289 vault->at(sfAssetsTotal) >= vault->at(sfAssetsMaximum))
292 <<
"Vault at maximum assets limit. Can't add another loan.";
296 Asset const asset = vault->at(sfAsset);
298 auto const vaultPseudo = vault->at(sfAccount);
307 if (
auto const value = tx[field];
308 value &&
STAmount{asset, *value} != *value)
310 JLOG(ctx.
j.
warn()) << field.f->getName() <<
" (" << *value
311 <<
") can not be represented as a(n) "
324 JLOG(ctx.
j.
warn()) <<
"Vault pseudo-account is frozen.";
333 JLOG(ctx.
j.
warn()) <<
"Broker pseudo-account is frozen.";
343 JLOG(ctx.
j.
warn()) <<
"Borrower account is frozen.";
350 JLOG(ctx.
j.
warn()) <<
"Broker owner account is frozen.";
363 auto const brokerID = tx[sfLoanBrokerID];
368 auto const brokerOwner = brokerSle->at(sfOwner);
373 auto const vaultSle =
view.
peek(keylet ::vault(brokerSle->at(sfVaultID)));
376 auto const vaultPseudo = vaultSle->at(sfAccount);
377 Asset const vaultAsset = vaultSle->at(sfAsset);
379 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
380 auto const borrower = counterparty == brokerOwner ?
account_ : counterparty;
387 auto const brokerPseudo = brokerSle->at(sfAccount);
389 if (!brokerPseudoSle)
393 auto const principalRequested = tx[sfPrincipalRequested];
395 auto vaultAvailableProxy = vaultSle->at(sfAssetsAvailable);
396 auto vaultTotalProxy = vaultSle->at(sfAssetsTotal);
398 if (vaultAvailableProxy < principalRequested)
401 <<
"Insufficient assets available in the Vault to fund the loan.";
405 TenthBips32 const interestRate{tx[~sfInterestRate].value_or(0)};
407 auto const paymentInterval =
421 properties.loanState.valueOutstanding,
423 properties.loanState.managementFeeDue);
425 auto const vaultMaximum = *vaultSle->at(sfAssetsMaximum);
427 vaultMaximum == 0 || vaultMaximum > *vaultTotalProxy,
428 "xrpl::LoanSet::doApply",
429 "Vault is below maximum limit");
430 if (vaultMaximum != 0 && state.interestDue > vaultMaximum - vaultTotalProxy)
432 JLOG(
j_.
warn()) <<
"Loan would exceed the maximum assets of the vault";
440 if (
auto const value = tx[field];
441 value && !
isRounded(vaultAsset, *value, properties.loanScale))
444 << field.f->getName() <<
" (" << *value
445 <<
") has too much precision. Total loan value is "
446 << properties.loanState.valueOutstanding
447 <<
" with a scale of " << properties.loanScale;
456 interestRate != beast::zero,
463 if (properties.loanState.managementFeeDue < 0 ||
464 properties.loanState.valueOutstanding <= 0 ||
465 properties.periodicPayment <= 0)
469 <<
"Computed loan properties are invalid. Does not compute."
470 <<
" Management fee: " << properties.loanState.managementFeeDue
471 <<
". Total Value: " << properties.loanState.valueOutstanding
472 <<
". PeriodicPayment: " << properties.periodicPayment;
477 auto const originationFee = tx[~sfLoanOriginationFee].value_or(
Number{});
479 auto const loanAssetsToBorrower = principalRequested - originationFee;
481 auto const newDebtDelta = principalRequested + state.interestDue;
482 auto const newDebtTotal = brokerSle->at(sfDebtTotal) + newDebtDelta;
483 if (
auto const debtMaximum = brokerSle->at(sfDebtMaximum);
484 debtMaximum != 0 && debtMaximum < newDebtTotal)
487 <<
"Loan would exceed the maximum debt limit of the LoanBroker.";
490 TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)};
496 if (brokerSle->at(sfCoverAvailable) <
500 <<
"Insufficient first-loss capital to cover the loan.";
507 auto const ownerCount = borrowerSle->at(sfOwnerCount);
508 auto const balance =
account_ == borrower
510 : borrowerSle->at(sfBalance).
value().xrp();
522 borrower ==
account_ || borrower == counterparty,
523 "xrpl::LoanSet::doApply",
524 "borrower signed transaction");
528 borrowerSle->at(sfBalance).value().xrp(),
542 if (originationFee != beast::zero)
547 brokerOwner ==
account_ || brokerOwner == counterparty,
548 "xrpl::LoanSet::doApply",
549 "broker owner signed transaction");
554 brokerOwnerSle->at(sfBalance).value().xrp(),
571 {{borrower, loanAssetsToBorrower}, {brokerOwner, originationFee}},
578 auto loanSequenceProxy = brokerSle->at(sfLoanSequence);
586 [&loan, &tx](
auto const& field,
std::uint32_t const defValue = 0) {
589 loan->at(field) = tx[field].value_or(defValue);
593 loan->at(sfLoanScale) = properties.loanScale;
594 loan->at(sfStartDate) = startDate;
595 loan->at(sfPaymentInterval) = paymentInterval;
596 loan->at(sfLoanSequence) = *loanSequenceProxy;
597 loan->at(sfLoanBrokerID) = brokerID;
598 loan->at(sfBorrower) = borrower;
602 setLoanField(~sfLoanOriginationFee);
603 setLoanField(~sfLoanServiceFee);
604 setLoanField(~sfLatePaymentFee);
605 setLoanField(~sfClosePaymentFee);
606 setLoanField(~sfOverpaymentFee);
607 setLoanField(~sfInterestRate);
608 setLoanField(~sfLateInterestRate);
609 setLoanField(~sfCloseInterestRate);
610 setLoanField(~sfOverpaymentInterestRate);
613 loan->at(sfPrincipalOutstanding) = principalRequested;
614 loan->at(sfPeriodicPayment) = properties.periodicPayment;
615 loan->at(sfTotalValueOutstanding) = properties.loanState.valueOutstanding;
616 loan->at(sfManagementFeeOutstanding) =
617 properties.loanState.managementFeeDue;
618 loan->at(sfPreviousPaymentDueDate) = 0;
619 loan->at(sfNextPaymentDueDate) = startDate + paymentInterval;
620 loan->at(sfPaymentRemaining) = paymentTotal;
624 vaultAvailableProxy -= principalRequested;
625 vaultTotalProxy += state.interestDue;
627 *vaultAvailableProxy <= *vaultTotalProxy,
628 "xrpl::LoanSet::doApply",
629 "assets available must not be greater than assets outstanding");
634 brokerSle->at(sfDebtTotal), newDebtDelta, vaultAsset, vaultScale);
638 loanSequenceProxy += 1;
641 if (loanSequenceProxy == 0)
646 if (
auto const ter =
dirLink(
view, brokerPseudo, loan, sfLoanBrokerNode))
649 if (
auto const ter =
dirLink(
view, borrower, loan, sfOwnerNode))
virtual void update(std::shared_ptr< SLE > const &sle)=0
Indicate changes to a peeked SLE.
virtual void insert(std::shared_ptr< SLE > const &sle)=0
Insert a new state SLE.
virtual std::shared_ptr< SLE > peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
static TER preclaim(PreclaimContext const &ctx)
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
static std::uint32_t constexpr minPaymentInterval
static std::vector< OptionaledField< STNumber > > const & getValueFields()
static NotTEC preflight(PreflightContext const &ctx)
static std::uint32_t constexpr defaultPaymentInterval
static NotTEC checkSign(PreclaimContext const &ctx)
static std::uint32_t constexpr defaultPaymentTotal
static bool checkExtraFeatures(PreflightContext const &ctx)
static std::uint32_t constexpr defaultGracePeriod
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
virtual std::shared_ptr< SLE const > 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.
T::value_type at(TypedField< T > const &f) const
Get the value of a field.
bool isFieldPresent(SField const &field) const
STObject getFieldObject(SField const &field) const
static NotTEC checkSign(PreclaimContext const &ctx)
static bool validNumericMinimum(std::optional< T > value, T min=T{})
Minimum will usually be zero.
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
static bool validDataLength(std::optional< Slice > const &slice, std::size_t maxLength)
static bool validNumericRange(std::optional< T > value, T max, T min=T{})
constexpr value_type value() const
Returns the underlying value.
NotTEC preflightCheckSigningKey(STObject const &sigObject, beast::Journal j)
Checks the validity of the transactor signing key.
std::optional< NotTEC > preflightCheckSimulateKeys(ApplyFlags flags, STObject const &sigObject, beast::Journal j)
Checks the special signing key state needed for simulation.
Keylet loanbroker(AccountID const &owner, std::uint32_t seq) noexcept
Keylet loan(uint256 const &loanBrokerID, std::uint32_t loanSeq) noexcept
Keylet vault(AccountID const &owner, std::uint32_t seq) noexcept
Keylet account(AccountID const &id) noexcept
AccountID root.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
TER checkDeepFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
TER addEmptyHolding(ApplyView &view, AccountID const &accountID, XRPAmount priorBalance, Issue const &issue, beast::Journal journal)
Any transactors that call addEmptyHolding() in doApply must call canAddHolding() in preflight with th...
TER canAddHolding(ReadView const &view, Asset const &asset)
constexpr std::uint32_t tfInnerBatchTxn
std::string to_string(base_uint< Bits, Tag > const &a)
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
int getAssetsTotalScale(SLE::const_ref vaultSle)
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
void adjustImpreciseNumber(NumberProxy value, Number const &adjustment, Asset const &asset, int vaultScale)
bool checkLendingProtocolDependencies(PreflightContext const &ctx)
constexpr std::uint32_t const tfLoanOverpayment
std::size_t constexpr maxDataPayloadLength
The maximum length of Data payload.
TER checkLoanGuards(Asset const &vaultAsset, Number const &principalRequested, bool expectInterest, std::uint32_t paymentTotal, LoanProperties const &properties, beast::Journal j)
TERSubset< CanCvtToTER > TER
void adjustOwnerCount(ApplyView &view, std::shared_ptr< SLE > const &sle, std::int32_t amount, beast::Journal j)
Adjust the owner count up or down.
TER requireAuth(ReadView const &view, Issue const &issue, AccountID const &account, AuthType authType=AuthType::Legacy)
Check if the account lacks required authorization.
constexpr std::uint32_t const tfLoanSetMask
static std::uint32_t getStartDate(ReadView const &view)
TER dirLink(ApplyView &view, AccountID const &owner, std::shared_ptr< SLE > &object, SF_UINT64 const &node=sfOwnerNode)
@ tecINSUFFICIENT_RESERVE
@ tecMAX_SEQUENCE_REACHED
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(Asset const &asset, Number const &principalOutstanding, TenthBips32 interestRate, std::uint32_t paymentInterval, std::uint32_t paymentsRemaining, TenthBips32 managementFeeRate, std::int32_t minimumScale)
LoanState constructLoanState(Number const &totalValueOutstanding, Number const &principalOutstanding, Number const &managementFeeOutstanding)
bool isRounded(Asset const &asset, Number const &value, std::int32_t scale)
XRPAmount accountReserve(std::size_t ownerCount) const
Returns the account reserve given the owner count, in drops.
This structure captures the parts of a loan state.
State information when determining if a tx is likely to claim a fee.
std::optional< uint256 const > const parentBatchId
State information when preflighting a tx.
std::optional< uint256 const > parentBatchId
T time_since_epoch(T... args)