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];
101 ctx.
flags, *counterPartySig, ctx.
j))
105 if (
auto const brokerID = ctx.
tx[~sfLoanBrokerID];
106 brokerID && *brokerID == beast::zero)
122 if (
auto const c = ctx.
tx.
at(~sfCounterparty))
125 if (
auto const broker =
127 return broker->at(sfOwner);
157 auto const counterSig = tx.
getFieldObject(sfCounterpartySignature);
165 return counterSig.isFieldPresent(sfSigners)
166 ? counterSig.getFieldArray(sfSigners).size()
167 : (counterSig.isFieldPresent(sfTxnSignature) ? 1 : 0);
170 return normalCost + (signerCount * baseFee);
177 ~sfPrincipalRequested,
178 ~sfLoanOriginationFee,
197 auto const& tx = ctx.
tx;
205 using timeType =
decltype(sfNextPaymentDueDate)::type::value_type;
208 static_assert(maxTime == 4'294'967'295);
212 auto const interval =
221 if (grace > timeAvailable)
223 JLOG(ctx.
j.
warn()) <<
"Grace period exceeds protocol time limit.";
227 if (interval > timeAvailable)
230 <<
"Payment interval exceeds protocol time limit.";
234 if (total > timeAvailable)
236 JLOG(ctx.
j.
warn()) <<
"Payment total exceeds protocol time limit.";
240 auto const timeLastPayment = timeAvailable - grace;
242 if (timeLastPayment / interval < total)
244 JLOG(ctx.
j.
warn()) <<
"Last payment due date, or grace period for "
245 "last payment exceeds protocol time limit.";
250 auto const account = tx[sfAccount];
251 auto const brokerID = tx[sfLoanBrokerID];
258 JLOG(ctx.
j.
warn()) <<
"LoanBroker does not exist.";
261 auto const brokerOwner = brokerSle->at(sfOwner);
262 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
263 if (account != brokerOwner && counterparty != brokerOwner)
265 JLOG(ctx.
j.
warn()) <<
"Neither Account nor Counterparty are the owner "
266 "of the LoanBroker.";
269 auto const brokerPseudo = brokerSle->at(sfAccount);
271 auto const borrower = counterparty == brokerOwner ? account : counterparty;
277 JLOG(ctx.
j.
warn()) <<
"Borrower does not exist.";
285 Asset const asset = vault->at(sfAsset);
287 auto const vaultPseudo = vault->at(sfAccount);
296 if (
auto const value = tx[field];
297 value &&
STAmount{asset, *value} != *value)
299 JLOG(ctx.
j.
warn()) << field.f->getName() <<
" (" << *value
300 <<
") can not be represented as a(n) "
313 JLOG(ctx.
j.
warn()) <<
"Vault pseudo-account is frozen.";
322 JLOG(ctx.
j.
warn()) <<
"Broker pseudo-account is frozen.";
332 JLOG(ctx.
j.
warn()) <<
"Borrower account is frozen.";
339 JLOG(ctx.
j.
warn()) <<
"Broker owner account is frozen.";
352 auto const brokerID = tx[sfLoanBrokerID];
357 auto const brokerOwner = brokerSle->at(sfOwner);
362 auto const vaultSle =
view.
peek(keylet ::vault(brokerSle->at(sfVaultID)));
365 auto const vaultPseudo = vaultSle->at(sfAccount);
366 Asset const vaultAsset = vaultSle->at(sfAsset);
368 auto const counterparty = tx[~sfCounterparty].value_or(brokerOwner);
369 auto const borrower = counterparty == brokerOwner ?
account_ : counterparty;
376 auto const brokerPseudo = brokerSle->at(sfAccount);
378 if (!brokerPseudoSle)
382 auto const principalRequested = tx[sfPrincipalRequested];
384 auto vaultAvailableProxy = vaultSle->at(sfAssetsAvailable);
385 auto vaultTotalProxy = vaultSle->at(sfAssetsTotal);
387 if (vaultAvailableProxy < principalRequested)
390 <<
"Insufficient assets available in the Vault to fund the loan.";
394 TenthBips32 const interestRate{tx[~sfInterestRate].value_or(0)};
396 auto const paymentInterval =
414 if (
auto const value = tx[field];
415 value && !
isRounded(vaultAsset, *value, properties.loanScale))
418 << field.f->getName() <<
" (" << *value
419 <<
") has too much precision. Total loan value is "
420 << properties.totalValueOutstanding <<
" with a scale of "
421 << properties.loanScale;
430 interestRate != beast::zero,
437 if (properties.managementFeeOwedToBroker < 0 ||
438 properties.totalValueOutstanding <= 0 ||
439 properties.periodicPayment <= 0)
443 <<
"Computed loan properties are invalid. Does not compute.";
449 properties.totalValueOutstanding,
451 properties.managementFeeOwedToBroker);
453 auto const originationFee = tx[~sfLoanOriginationFee].value_or(
Number{});
455 auto const loanAssetsToBorrower = principalRequested - originationFee;
457 auto const newDebtDelta = principalRequested + state.
interestDue;
458 auto const newDebtTotal = brokerSle->at(sfDebtTotal) + newDebtDelta;
459 if (
auto const debtMaximum = brokerSle->at(sfDebtMaximum);
460 debtMaximum != 0 && debtMaximum < newDebtTotal)
463 <<
"Loan would exceed the maximum debt limit of the LoanBroker.";
466 TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)};
472 if (brokerSle->at(sfCoverAvailable) <
476 <<
"Insufficient first-loss capital to cover the loan.";
483 auto const ownerCount = borrowerSle->at(sfOwnerCount);
484 auto const balance =
account_ == borrower
486 : borrowerSle->at(sfBalance).
value().xrp();
498 borrower ==
account_ || borrower == counterparty,
499 "xrpl::LoanSet::doApply",
500 "borrower signed transaction");
504 borrowerSle->at(sfBalance).value().xrp(),
518 if (originationFee != beast::zero)
523 brokerOwner ==
account_ || brokerOwner == counterparty,
524 "xrpl::LoanSet::doApply",
525 "broker owner signed transaction");
530 brokerOwnerSle->at(sfBalance).value().xrp(),
547 {{borrower, loanAssetsToBorrower}, {brokerOwner, originationFee}},
554 auto loanSequenceProxy = brokerSle->at(sfLoanSequence);
562 [&loan, &tx](
auto const& field,
std::uint32_t const defValue = 0) {
565 loan->at(field) = tx[field].value_or(defValue);
569 loan->at(sfLoanScale) = properties.loanScale;
570 loan->at(sfStartDate) = startDate;
571 loan->at(sfPaymentInterval) = paymentInterval;
572 loan->at(sfLoanSequence) = *loanSequenceProxy;
573 loan->at(sfLoanBrokerID) = brokerID;
574 loan->at(sfBorrower) = borrower;
578 setLoanField(~sfLoanOriginationFee);
579 setLoanField(~sfLoanServiceFee);
580 setLoanField(~sfLatePaymentFee);
581 setLoanField(~sfClosePaymentFee);
582 setLoanField(~sfOverpaymentFee);
583 setLoanField(~sfInterestRate);
584 setLoanField(~sfLateInterestRate);
585 setLoanField(~sfCloseInterestRate);
586 setLoanField(~sfOverpaymentInterestRate);
589 loan->at(sfPrincipalOutstanding) = principalRequested;
590 loan->at(sfPeriodicPayment) = properties.periodicPayment;
591 loan->at(sfTotalValueOutstanding) = properties.totalValueOutstanding;
592 loan->at(sfManagementFeeOutstanding) = properties.managementFeeOwedToBroker;
593 loan->at(sfPreviousPaymentDate) = 0;
594 loan->at(sfNextPaymentDueDate) = startDate + paymentInterval;
595 loan->at(sfPaymentRemaining) = paymentTotal;
599 vaultAvailableProxy -= principalRequested;
602 *vaultAvailableProxy <= *vaultTotalProxy,
603 "xrpl::LoanSet::doApply",
604 "assets available must not be greater than assets outstanding");
609 brokerSle->at(sfDebtTotal), newDebtDelta, vaultAsset, vaultScale);
613 loanSequenceProxy += 1;
616 if (loanSequenceProxy == 0)
621 if (
auto const ter =
dirLink(
view, brokerPseudo, loan, sfLoanBrokerNode))
624 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)
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)
int getVaultScale(SLE::const_ref vaultSle)
@ 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 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)