xrpld
Loading...
Searching...
No Matches
LoanManage.cpp
1#include <xrpl/tx/transactors/lending/LoanManage.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/core/ServiceRegistry.h>
7#include <xrpl/ledger/ApplyView.h>
8#include <xrpl/ledger/View.h>
9#include <xrpl/ledger/helpers/LendingHelpers.h>
10#include <xrpl/ledger/helpers/TokenHelpers.h>
11#include <xrpl/protocol/Asset.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/LedgerFormats.h>
15#include <xrpl/protocol/Protocol.h>
16#include <xrpl/protocol/SField.h>
17#include <xrpl/protocol/STAmount.h>
18#include <xrpl/protocol/STLedgerEntry.h>
19#include <xrpl/protocol/STTakesAsset.h>
20#include <xrpl/protocol/STTx.h>
21#include <xrpl/protocol/TER.h>
22#include <xrpl/protocol/TxFlags.h>
23#include <xrpl/protocol/Units.h>
24#include <xrpl/protocol/XRPAmount.h>
25#include <xrpl/tx/Transactor.h>
26
27#include <algorithm>
28#include <cstdint>
29namespace xrpl {
30
31bool
36
39{
40 return tfLoanManageMask;
41}
42
45{
46 if (ctx.tx[sfLoanID] == beast::kZero)
47 return temINVALID;
48
49 // Flags are mutually exclusive
50 if (auto const flagField = ctx.tx[~sfFlags]; flagField && (*flagField != 0u))
51 {
52 auto const flags = *flagField & tfUniversalMask;
53 if ((flags & (flags - 1)) != 0)
54 {
55 JLOG(ctx.j.warn()) << "LoanManage: Only one of tfLoanDefault, tfLoanImpair, or "
56 "tfLoanUnimpair can be set.";
57 return temINVALID_FLAG;
58 }
59 }
60
61 return tesSUCCESS;
62}
63
64TER
66{
67 auto const& tx = ctx.tx;
68
69 auto const account = tx[sfAccount];
70 auto const loanID = tx[sfLoanID];
71
72 auto const loanSle = ctx.view.read(keylet::loan(loanID));
73 if (!loanSle)
74 {
75 JLOG(ctx.j.warn()) << "Loan does not exist.";
76 return tecNO_ENTRY;
77 }
78 // Impairment only allows certain transitions.
79 // 1. Once it's in default, it can't be changed.
80 // 2. It can get worse: unimpaired -> impaired -> default
81 // or unimpaired -> default
82 // 3. It can get better: impaired -> unimpaired
83 // 4. If it's in a state, it can't be put in that state again.
84 if (loanSle->isFlag(lsfLoanDefault))
85 {
86 JLOG(ctx.j.warn()) << "Loan is in default. A defaulted loan can not be modified.";
87 return tecNO_PERMISSION;
88 }
89 if (loanSle->isFlag(lsfLoanImpaired) && tx.isFlag(tfLoanImpair))
90 {
91 JLOG(ctx.j.warn()) << "Loan is impaired. A loan can not be impaired twice.";
92 return tecNO_PERMISSION;
93 }
94 if (!(loanSle->isFlag(lsfLoanImpaired) || loanSle->isFlag(lsfLoanDefault)) &&
95 (tx.isFlag(tfLoanUnimpair)))
96 {
97 JLOG(ctx.j.warn()) << "Loan is unimpaired. Can not be unimpaired again.";
98 return tecNO_PERMISSION;
99 }
100 if (loanSle->at(sfPaymentRemaining) == 0)
101 {
102 JLOG(ctx.j.warn()) << "Loan is fully paid. A loan can not be modified "
103 "after it is fully paid.";
104 return tecNO_PERMISSION;
105 }
106 if (tx.isFlag(tfLoanDefault) &&
107 !hasExpired(ctx.view, loanSle->at(sfNextPaymentDueDate) + loanSle->at(sfGracePeriod)))
108 {
109 JLOG(ctx.j.warn()) << "A loan can not be defaulted before the next payment due date.";
110 return tecTOO_SOON;
111 }
112
113 auto const loanBrokerID = loanSle->at(sfLoanBrokerID);
114 auto const loanBrokerSle = ctx.view.read(keylet::loanBroker(loanBrokerID));
115 if (!loanBrokerSle)
116 {
117 // should be impossible
118 return tecINTERNAL; // LCOV_EXCL_LINE
119 }
120 if (loanBrokerSle->at(sfOwner) != account)
121 {
122 JLOG(ctx.j.warn()) << "LoanBroker for Loan does not belong to the account. LoanManage "
123 "can only be submitted by the Loan Broker.";
124 return tecNO_PERMISSION;
125 }
126
127 return tesSUCCESS;
128}
129
130TER
133 SLE::ref loanSle,
134 SLE::ref brokerSle,
135 SLE::ref vaultSle,
136 Asset const& vaultAsset,
138{
139 // Calculate the amount of the Default that First-Loss Capital covers:
140
141 std::int32_t const loanScale = loanSle->at(sfLoanScale);
142 auto brokerDebtTotalProxy = brokerSle->at(sfDebtTotal);
143
144 Number const totalDefaultAmount = loanVaultExposure(vaultSle, loanSle);
145
146 // Apply the First-Loss Capital to the Default Amount
147 TenthBips32 const coverRateMinimum{brokerSle->at(sfCoverRateMinimum)};
148 TenthBips32 const coverRateLiquidation{brokerSle->at(sfCoverRateLiquidation)};
149 auto const defaultCovered = [&]() {
150 // Always round the minimum required up.
152 auto const minimumCover = tenthBipsOfValue(brokerDebtTotalProxy.value(), coverRateMinimum);
153 // Round the liquidation amount up, too
154 auto const covered = roundToAsset(
155 vaultAsset,
156 /*
157 * This formula is from the XLS-66 spec, section 3.2.3.2 (State
158 * Changes), specifically "if the `tfLoanDefault` flag is set" /
159 * "Apply the First-Loss Capital to the Default Amount"
160 */
161 std::min(tenthBipsOfValue(minimumCover, coverRateLiquidation), totalDefaultAmount),
162 loanScale);
163 auto const coverAvailable = *brokerSle->at(sfCoverAvailable);
164
165 return std::min(covered, coverAvailable);
166 }();
167
168 auto const vaultDefaultAmount = totalDefaultAmount - defaultCovered;
169
170 // Update the Vault object:
171
172 // The vault may be at a different scale than the loan. Reduce rounding
173 // errors during the accounting by rounding some of the values to that
174 // scale.
175 auto const vaultScale = getAssetsTotalScale(vaultSle);
176
177 {
178 // Decrease the Total Value of the Vault:
179 auto vaultTotalProxy = vaultSle->at(sfAssetsTotal);
180 auto vaultAvailableProxy = vaultSle->at(sfAssetsAvailable);
181
182 if (vaultTotalProxy < vaultDefaultAmount)
183 {
184 // LCOV_EXCL_START
185 JLOG(j.warn()) << "Vault total assets is less than the vault default amount";
186 return tefBAD_LEDGER;
187 // LCOV_EXCL_STOP
188 }
189
190 auto const vaultDefaultRounded = roundToAsset(
191 vaultAsset, vaultDefaultAmount, vaultScale, Number::RoundingMode::Downward);
192 vaultTotalProxy -= vaultDefaultRounded;
193 // Increase the Asset Available of the Vault by liquidated First-Loss
194 // Capital and any unclaimed funds amount:
195 vaultAvailableProxy += defaultCovered;
196 if (*vaultAvailableProxy > *vaultTotalProxy && !vaultAsset.integral())
197 {
198 auto const difference = vaultAvailableProxy - vaultTotalProxy;
199 JLOG(j.debug()) << "Vault assets available: " << *vaultAvailableProxy << "("
200 << vaultAvailableProxy.value().exponent()
201 << "), Total: " << *vaultTotalProxy << "("
202 << vaultTotalProxy.value().exponent() << "), Difference: " << difference
203 << "(" << difference.exponent() << ")";
204 if (vaultAvailableProxy.value().exponent() - difference.exponent() > 13)
205 {
206 // If the difference is dust, bring the total up to match
207 // the available
208 JLOG(j.debug()) << "Difference between vault assets available and total is "
209 "dust. Set both to the larger value.";
210 vaultTotalProxy = vaultAvailableProxy;
211 }
212 }
213 if (*vaultAvailableProxy > *vaultTotalProxy)
214 {
215 // LCOV_EXCL_START
216 JLOG(j.fatal()) << "Vault assets available must not be greater "
217 "than assets outstanding. Available: "
218 << *vaultAvailableProxy << ", Total: " << *vaultTotalProxy;
219 return tecINTERNAL;
220 // LCOV_EXCL_STOP
221 }
222
223 // The loss has been realized
224 if (loanSle->isFlag(lsfLoanImpaired))
225 {
226 auto vaultLossUnrealizedProxy = vaultSle->at(sfLossUnrealized);
227 if (vaultLossUnrealizedProxy < totalDefaultAmount)
228 {
229 // LCOV_EXCL_START
230 JLOG(j.warn()) << "Vault unrealized loss is less than the default amount";
231 return tefBAD_LEDGER;
232 // LCOV_EXCL_STOP
233 }
235 vaultLossUnrealizedProxy, -totalDefaultAmount, vaultAsset, vaultScale);
236 }
237 view.update(vaultSle);
238 }
239
240 // Update the LoanBroker object:
241
242 {
243 // Decrease the Debt of the LoanBroker:
244 adjustImpreciseNumber(brokerDebtTotalProxy, -totalDefaultAmount, vaultAsset, vaultScale);
245 // Decrease the First-Loss Capital Cover Available:
246 auto coverAvailableProxy = brokerSle->at(sfCoverAvailable);
247 if (coverAvailableProxy < defaultCovered)
248 {
249 // LCOV_EXCL_START
250 JLOG(j.warn()) << "LoanBroker cover available is less than amount covered";
251 return tefBAD_LEDGER;
252 // LCOV_EXCL_STOP
253 }
254 coverAvailableProxy -= defaultCovered;
255 view.update(brokerSle);
256 }
257
258 // Update the Loan object:
259 loanSle->setFlag(lsfLoanDefault);
260
261 loanSle->at(sfTotalValueOutstanding) = 0;
262 loanSle->at(sfPaymentRemaining) = 0;
263 loanSle->at(sfPrincipalOutstanding) = 0;
264 loanSle->at(sfManagementFeeOutstanding) = 0;
265 // Zero out the next due date. Since it's default, it'll be removed from
266 // the object.
267 loanSle->at(sfNextPaymentDueDate) = 0;
268 view.update(loanSle);
269
270 // Return funds from the LoanBroker pseudo-account to the
271 // Vault pseudo-account:
272 return accountSend(
273 view,
274 brokerSle->at(sfAccount),
275 vaultSle->at(sfAccount),
276 STAmount{vaultAsset, defaultCovered},
277 j,
278 {},
280}
281
282TER
285 SLE::ref loanSle,
286 SLE::ref vaultSle,
287 Asset const& vaultAsset,
289{
290 Number const lossUnrealized = loanVaultExposure(vaultSle, loanSle);
291
292 // The vault may be at a different scale than the loan. Reduce rounding
293 // errors during the accounting by rounding some of the values to that
294 // scale.
295 auto const vaultScale = getAssetsTotalScale(vaultSle);
296
297 // Update the Vault object(set "paper loss")
298 auto vaultLossUnrealizedProxy = vaultSle->at(sfLossUnrealized);
299 adjustImpreciseNumber(vaultLossUnrealizedProxy, lossUnrealized, vaultAsset, vaultScale);
300 if (vaultLossUnrealizedProxy > vaultSle->at(sfAssetsTotal) - vaultSle->at(sfAssetsAvailable))
301 {
302 // Having a loss greater than the vault's unavailable assets
303 // will leave the vault in an invalid / inconsistent state.
304 JLOG(j.warn()) << "Vault unrealized loss is too large, and will "
305 "corrupt the vault.";
306 return tecLIMIT_EXCEEDED;
307 }
308 view.update(vaultSle);
309
310 // Update the Loan object
311 loanSle->setFlag(lsfLoanImpaired);
312 auto loanNextDueProxy = loanSle->at(sfNextPaymentDueDate);
313 if (!hasExpired(view, loanNextDueProxy))
314 {
315 // loan payment is not yet late -
316 // move the next payment due date to now
317 loanNextDueProxy = view.parentCloseTime().time_since_epoch().count();
318 }
319 view.update(loanSle);
320
321 return tesSUCCESS;
322}
323
324[[nodiscard]] TER
327 SLE::ref loanSle,
328 SLE::ref vaultSle,
329 Asset const& vaultAsset,
331{
332 // The vault may be at a different scale than the loan. Reduce rounding
333 // errors during the accounting by rounding some of the values to that
334 // scale.
335 auto const vaultScale = getAssetsTotalScale(vaultSle);
336
337 // Update the Vault object(clear "paper loss")
338 auto vaultLossUnrealizedProxy = vaultSle->at(sfLossUnrealized);
339 Number const lossReversed = loanVaultExposure(vaultSle, loanSle);
340 if (vaultLossUnrealizedProxy < lossReversed)
341 {
342 // LCOV_EXCL_START
343 JLOG(j.warn()) << "Vault unrealized loss is less than the amount to be cleared";
344 return tefBAD_LEDGER;
345 // LCOV_EXCL_STOP
346 }
347 // Reverse the "paper loss"
348 adjustImpreciseNumber(vaultLossUnrealizedProxy, -lossReversed, vaultAsset, vaultScale);
349
350 view.update(vaultSle);
351
352 // Update the Loan object
353 loanSle->clearFlag(lsfLoanImpaired);
354 auto const paymentInterval = loanSle->at(sfPaymentInterval);
355 auto const normalPaymentDueDate =
356 std::max(loanSle->at(sfPreviousPaymentDueDate), loanSle->at(sfStartDate)) + paymentInterval;
357 if (!hasExpired(view, normalPaymentDueDate))
358 {
359 // loan was unimpaired within the payment interval
360 loanSle->at(sfNextPaymentDueDate) = normalPaymentDueDate;
361 }
362 else
363 {
364 // loan was unimpaired after the original payment due date
365 loanSle->at(sfNextPaymentDueDate) =
366 view.parentCloseTime().time_since_epoch().count() + paymentInterval;
367 }
368 view.update(loanSle);
369
370 return tesSUCCESS;
371}
372
373TER
375{
376 auto const& tx = ctx_.tx;
377 auto& view = ctx_.view();
378
379 auto const loanID = tx[sfLoanID];
380 auto const loanSle = view.peek(keylet::loan(loanID));
381 if (!loanSle)
382 return tefBAD_LEDGER; // LCOV_EXCL_LINE
383
384 auto const brokerID = loanSle->at(sfLoanBrokerID);
385 auto const brokerSle = view.peek(keylet::loanBroker(brokerID));
386 if (!brokerSle)
387 return tefBAD_LEDGER; // LCOV_EXCL_LINE
388
389 auto const vaultSle = view.peek(keylet::vault(brokerSle->at(sfVaultID)));
390 if (!vaultSle)
391 return tefBAD_LEDGER; // LCOV_EXCL_LINE
392 auto const vaultAsset = vaultSle->at(sfAsset);
393
394 auto const result = [&]() -> TER {
395 // Valid flag combinations are checked in preflight. No flags is valid -
396 // just a noop.
397 if (tx.isFlag(tfLoanDefault))
398 return defaultLoan(view, loanSle, brokerSle, vaultSle, vaultAsset, j_);
399 if (tx.isFlag(tfLoanImpair))
400 return impairLoan(view, loanSle, vaultSle, vaultAsset, j_);
401 if (tx.isFlag(tfLoanUnimpair))
402 return unimpairLoan(view, loanSle, vaultSle, vaultAsset, j_);
403 // NoOp, as described above.
404 return tesSUCCESS;
405 }();
406
407 // Pre-amendment, associateAsset was only called on the noop (no flags)
408 // path. Post-amendment, we call associateAsset on all successful paths.
409 if (view.rules().enabled(fixCleanup3_1_3) && isTesSuccess(result))
410 {
411 associateAsset(*loanSle, vaultAsset);
412 associateAsset(*brokerSle, vaultAsset);
413 associateAsset(*vaultSle, vaultAsset);
414 }
415
416 return result;
417}
418
419void
421{
422 // No transaction-specific invariants yet (future work).
423}
424
425bool
427{
428 // No transaction-specific invariants yet (future work).
429 return true;
430}
431
432//------------------------------------------------------------------------------
433
434} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream debug() const
Definition Journal.h:344
Stream warn() const
Definition Journal.h:356
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:134
bool integral() const
Definition Asset.h:133
void visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override
Inspect a single ledger entry modified by this transaction.
static TER defaultLoan(ApplyView &view, SLE::ref loanSle, SLE::ref brokerSle, SLE::ref vaultSle, Asset const &vaultAsset, beast::Journal j)
Helper function that might be needed by other transactors.
static TER preclaim(PreclaimContext const &ctx)
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.
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
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.
static TER impairLoan(ApplyView &view, SLE::ref loanSle, SLE::ref vaultSle, Asset const &vaultAsset, beast::Journal j)
Helper function that might be needed by other transactors.
TER doApply() override
static NotTEC preflight(PreflightContext const &ctx)
static bool checkExtraFeatures(PreflightContext const &ctx)
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 SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
std::shared_ptr< STLedgerEntry > const & ref
std::shared_ptr< STLedgerEntry const > const & const_ref
beast::Journal const j_
Definition Transactor.h:155
ApplyView & view()
Definition Transactor.h:175
ApplyContext & ctx_
Definition Transactor.h:153
T max(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet loan(uint256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:573
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:561
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:567
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp, ExpiryComparison comparison=ExpiryComparison::Inclusive)
Determines whether the given expiration time has passed.
Definition View.cpp:48
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, SLE::ref sponsorSle={}, WaiveTransferFee waiveFee=WaiveTransferFee::No, AllowMPTOverflow allowOverflow=AllowMPTOverflow::No)
Calls static accountSendIOU if saAmount represents Issue.
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:138
int getAssetsTotalScale(SLE::const_ref vaultSle)
void adjustImpreciseNumber(NumberProxy value, Number const &adjustment, Asset const &asset, int vaultScale)
@ tefBAD_LEDGER
Definition TER.h:162
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:607
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:735
@ temINVALID
Definition TER.h:98
@ temINVALID_FLAG
Definition TER.h:99
bool isTesSuccess(TER x) noexcept
Definition TER.h:676
TERSubset< CanCvtToTER > TER
Definition TER.h:647
Number loanVaultExposure(SLE::const_ref vaultSle, SLE::const_ref loanSle)
@ tecNO_ENTRY
Definition TER.h:309
@ tecINTERNAL
Definition TER.h:313
@ tecTOO_SOON
Definition TER.h:321
@ tecLIMIT_EXCEEDED
Definition TER.h:364
@ tecNO_PERMISSION
Definition TER.h:308
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
constexpr FlagValue tfUniversalMask
Definition TxFlags.h:46
@ tesSUCCESS
Definition TER.h:245
bool checkLendingProtocolDependencies(Rules const &rules, STTx const &tx)
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:83
ReadView const & view
Definition Transactor.h:86
beast::Journal const j
Definition Transactor.h:91
State information when preflighting a tx.
Definition Transactor.h:38
beast::Journal const j
Definition Transactor.h:45