xrpld
Loading...
Searching...
No Matches
LoanPayFixedPrecisionBase.h
1#pragma once
2
3#include <test/app/lending/LoanFixedPrecisionBase.h>
4#include <test/app/vault/VaultFixedPrecisionBase.h>
5#include <test/jtx/Account.h>
6#include <test/jtx/Env.h>
7#include <test/jtx/TestHelpers.h>
8#include <test/jtx/amount.h>
9#include <test/jtx/fee.h>
10#include <test/jtx/sig.h>
11#include <test/jtx/vault.h>
12
13#include <xrpl/basics/Number.h>
14#include <xrpl/basics/chrono.h>
15#include <xrpl/beast/unit_test/suite.h>
16#include <xrpl/beast/utility/Zero.h>
17#include <xrpl/ledger/helpers/LendingHelpers.h>
18#include <xrpl/protocol/Asset.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/Keylet.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/SeqProxy.h>
26#include <xrpl/protocol/TxFlags.h>
27#include <xrpl/protocol/Units.h>
28
29#include <cassert>
30#include <chrono>
31#include <cstddef>
32#include <cstdint>
33#include <optional>
34#include <string>
35#include <vector>
36
37namespace xrpl {
38
39// LoanPay-tier scaffolding on top of LoanFixedPrecisionBase: the
40// coarsened-vault fixture (repeated late interest pushes a FixedPrecision
41// vault's live Scale past its base grid) and the helpers built on it. Shared
42// by LoanPayFixedPrecision and, via LoanManageFixedPrecisionBase, by
43// LoanManageFixedPrecision.
45{
46protected:
47 // Brings the Keylet overload into scope alongside the CoarsenedVault
48 // overload added below; otherwise the derived overload would hide it.
51
52 // Coarsens a FixedPrecision vault through paid late interest, which the
53 // LoanSet Open-zone guard does not bound. Deposits near the Open-zone ceiling,
54 // originates a zero-interest loan for most of it, lets the first payment go
55 // very late at the maximum LateInterestRate, and pays it late.
56 //
57 // extraLoans are originated before the coarsening loan goes late, because a
58 // coarsened vault refuses further LoanSet. loanKeylets[0] is the coarsening
59 // loan; loanKeylets[1..] are the extras in order.
65
66 // An extra loan originated before the vault coarsens, on top of the shared
67 // zero-interest / 1-day-interval / 60s-grace defaults.
68 struct ExtraLoan
69 {
73 // Override with a long interval to keep the first payment from being overdue
74 // once the clock advances to coarsen the vault.
76 // Defaults to the shared depositor. A dust-sized loan needs its own borrower
77 // with a small balance: a sub-1e-9 debit from a multi-million balance does
78 // not fit STAmount's 16 digits and rounds away.
80 // A flat per-payment service fee to the broker owner, giving a terminal
81 // payment a zero vault-credit leg but a non-zero fee leg.
83 };
84
85 void
87 test::jtx::Env& env,
88 CoarsenedVault const& coarsened,
89 std::string const& label = {})
90 {
91 checkVaultLoanSums(env, coarsened.fixture, coarsened.loanKeylets, label);
92 }
93
95 {
99 // The explicit initializer avoids the missing-field-initializers warning when a
100 // designated initializer omits it.
101 std::vector<ExtraLoan> extraLoans = // NOLINT(readability-redundant-member-init)
102 {};
106 // 800 days pushes AssetsAvailable itself past its 16-digit budget, so cash
107 // flows floor at a coarser grid. 200 days coarsens only getVaultScale()
108 // (AA + AssetsDeployed), leaving AA's own grid at the base grid.
109 int overdueDays = 800;
110 };
111
112 void
113 expectCoarsened(test::jtx::Env const& env, CoarsenedVault const& coarsened)
114 {
115 expectCoarsened(env, coarsened.fixture.vaultKeylet);
116 }
117
118 // IOU setup for the coarsened-vault scenarios: the depositor holds 10M USD.
119 static AssetAccounts
120 setupCoarsenIou(test::jtx::Env& env, bool clawback = false)
121 {
122 return setupIou(
123 env,
124 {.clawback = clawback, .depositorTrust = 30'000'000, .depositorFunds = 10'000'000});
125 }
126
127 enum class Debit { Withdraw, Clawback };
128
129 // Submits a VaultWithdraw (depositor) or VaultClawback (issuer) of amount and
130 // returns how much AssetsAvailable dropped.
131 Number
133 test::jtx::Env& env,
134 CoarsenedVault const& coarsened,
135 Debit kind,
136 test::jtx::Account const& issuer,
137 test::jtx::Account const& depositor,
138 PrettyAsset const& asset,
139 Number const& amount)
140 {
141 auto const& vault = coarsened.fixture.vault;
142 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
143 auto const before = snapshotVault(env, vaultKeylet, asset);
144 if (kind == Debit::Withdraw)
145 {
146 env(vault.withdraw(
147 {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(amount)}));
148 }
149 else
150 {
151 env(vault.clawback({
152 .issuer = issuer,
153 .id = vaultKeylet.key,
154 .holder = depositor,
155 .amount = asset(amount).value(),
156 }));
157 }
158 env.close();
159 return before.available - snapshotVault(env, vaultKeylet, asset).available;
160 }
161
162 CoarsenedVault
164 test::jtx::Env& env,
165 test::jtx::Account const& owner,
166 test::jtx::Account const& depositor,
167 PrettyAsset const& asset)
168 {
169 return coarsenVault(env, owner, depositor, asset, CoarsenParams{});
170 }
171
172 CoarsenedVault
174 test::jtx::Env& env,
175 test::jtx::Account const& owner,
176 test::jtx::Account const& depositor,
177 PrettyAsset const& asset,
178 CoarsenParams const& params)
179 {
180 using namespace test::jtx;
181 using namespace loan;
182 using namespace loan_broker;
183 using namespace lending;
184
185 // A 15-year investment window, so extra loans with long payment intervals
186 // still fit before RedemptionDate.
187 std::chrono::seconds const investmentWindow{15 * 365 * 24 * 60 * 60};
188 auto fixture = setupLendingVault(
189 env,
190 owner,
191 depositor,
192 asset,
193 params.depositAmount,
194 investmentWindow,
195 params.scale,
196 params.coverRateMinimum,
197 params.coverRateLiquidation);
198
199 if (params.coverDeposit != beast::kZero)
200 {
201 env(coverDeposit(owner, fixture.brokerKeylet.key, asset(params.coverDeposit).value()));
202 env.close();
203 }
204
205 std::uint32_t const gracePeriod = 60;
206
207 std::vector<Keylet> loanKeylets;
208 std::vector<ExtraLoan> allLoans{ExtraLoan{.principal = params.loanPrincipal}};
209 allLoans.insert(allLoans.end(), params.extraLoans.begin(), params.extraLoans.end());
210 for (std::size_t i = 0; i < allLoans.size(); ++i)
211 {
212 auto const loanKeylet =
213 keylet::loan(fixture.brokerKeylet.key, SeqProxy::rawSequence(i + 1));
214 auto const& loan = allLoans[i];
215 auto const submit = [&](auto&&... extra) {
216 env(set(loan.borrower.value_or(depositor),
217 fixture.brokerKeylet.key,
218 loan.principal,
219 loan.flags),
220 kInterestRate(TenthBips32(0)),
221 kLoanServiceFee(loan.serviceFee),
222 kGracePeriod(gracePeriod),
223 kPaymentInterval(loan.paymentInterval),
224 kPaymentTotal(loan.paymentTotal),
225 Sig(sfCounterpartySignature, owner),
226 Fee(env.current()->fees().base * 2),
227 extra...);
228 };
229 if (i == 0)
230 {
231 // Only the coarsening loan needs a non-zero LateInterestRate.
232 submit(kLateInterestRate(kMaxLateInterestRate));
233 }
234 else
235 {
236 submit();
237 }
238 env.close();
239 loanKeylets.push_back(loanKeylet);
240 }
241
242 auto const loanSle = env.le(loanKeylets[0]);
243 BEAST_EXPECT(loanSle);
244 std::uint32_t const dueDate = loanSle ? loanSle->at(sfNextPaymentDueDate) : 0;
245
246 // Leave the first payment overdue long enough that penalty interest pushes
247 // AssetsAvailable itself, not just AA + AssetsDeployed, past its 16-digit budget at
248 // the base scale; only then do cash credits floor.
249 env.close(
250 NetClock::time_point{NetClock::duration{dueDate + gracePeriod}} +
251 std::chrono::seconds{params.overdueDays * 24 * 60 * 60});
252
253 // Generously covers the coarsening loan's principal plus accrued late
254 // interest.
255 Number const latePaymentAmount = params.loanPrincipal * 10;
256 env(pay(
257 depositor, loanKeylets[0].key, asset(latePaymentAmount).value(), tfLoanLatePayment));
258 env.close();
259
260 return {.fixture = fixture, .loanKeylets = loanKeylets};
261 }
262
263 // Reads an integral-asset vault Number field (AssetsAvailable, AssetsDeployed,
264 // LossUnrealized, ... are STNumber fields, not plain UInt64 SFields) as a
265 // std::uint64_t for plain integer arithmetic and search loops. Number
266 // itself does not normalize to the asset's own zero exponent, so the value
267 // is round-tripped through an STAmount of the vault's (integral) asset
268 // first, matching how STAmount::mpt()/xrp() extract an exact int64.
269 template <class T>
270 static std::uint64_t
271 toU64(SLE::ConstRef vault, TypedField<T> const& field)
272 {
273 Asset const asset = vault->at(sfAsset);
274 STAmount const amount{asset, Number(vault->at(field))};
275 assert(amount.exponent() == 0);
276 return static_cast<std::uint64_t>(amount.mantissa());
277 }
278
279 // Doubles AssetsAvailable roughly cycles times via an origination/
280 // repayment loop: originate a single-payment, kMaxInterestRate (100%),
281 // one-year loan for the vault's entire current AssetsAvailable, then pay
282 // it off in full at the due date. AssetsDeployed returns to zero after every
283 // cycle, and the depositor's share count is never touched, so this grows
284 // the per-share NAV purely through externally-funded interest -- the
285 // "originate, repay, and delete...loans that grow the vault" step shared
286 // by the sole-holder clawback and final-withdrawal scenarios below. The
287 // depositor needs enough of their own funds to cover the interest leg of
288 // every cycle (the principal itself round-trips: it is lent back out,
289 // then repaid).
290 void
292 test::jtx::Env& env,
293 LendingFixture const& fixture,
294 test::jtx::Account const& depositor,
295 PrettyAsset const& asset,
296 int cycles)
297 {
298 using namespace test::jtx;
299 using namespace loan;
300
301 for (int i = 0; i < cycles; ++i)
302 {
303 auto const vaultSle = env.le(fixture.vaultKeylet);
304 if (!BEAST_EXPECT(vaultSle))
305 return;
306 Number const principal = vaultSle->at(sfAssetsAvailable);
307 if (!BEAST_EXPECT(principal > beast::kZero))
308 return;
309
310 std::uint32_t const oneYearInterval = 365 * 24 * 60 * 60;
311 auto const loanKeylet = openLoan(
312 env,
313 fixture,
314 principal,
315 /* paymentTotal */ 1,
317 /* flags */ 0,
318 oneYearInterval);
319
320 auto const loanSle = env.le(loanKeylet);
321 if (!BEAST_EXPECT(loanSle))
322 return;
323 std::uint32_t const dueDate = loanSle->at(sfNextPaymentDueDate);
325
326 Number const periodicPayment = loanSle->at(sfPeriodicPayment);
327 std::int32_t const loanScale = loanSle->at(sfLoanScale);
328 Number const paymentDue = roundPeriodicPayment(asset, periodicPayment, loanScale);
329
330 // The clock is advanced to just past the due date, so the payment
331 // must be flagged late (LateInterestRate is 0 by default, so this
332 // adds no penalty -- it only satisfies the overdue check in
333 // LendingHelpers' loanMakePayment).
334 env(pay(depositor, loanKeylet.key, asset(paymentDue).value(), tfLoanLatePayment));
335 env.close();
336 }
337 }
338};
339
340} // namespace xrpl
static LendingFixture setupLendingVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset, Number const &depositAmount, std::chrono::seconds investmentWindow=std::chrono::seconds{1 '000 '000}, std::optional< std::uint8_t > scale=std::nullopt, TenthBips32 coverRateMinimum=TenthBips32(0), TenthBips32 coverRateLiquidation=TenthBips32(0), TenthBips16 managementFeeRate=TenthBips16(0))
void checkVaultLoanSums(test::jtx::Env &env, LendingFixture const &fixture, std::vector< Keylet > const &loanKeylets, std::string const &label={})
static Keylet openLoan(test::jtx::Env &env, LendingFixture const &fixture, Number const &principal, std::uint32_t paymentTotal, TenthBips32 interestRate=TenthBips32(0), std::uint32_t flags=0, std::uint32_t paymentInterval=120, std::uint32_t gracePeriod=60)
CoarsenedVault coarsenVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset)
static AssetAccounts setupCoarsenIou(test::jtx::Env &env, bool clawback=false)
void expectCoarsened(test::jtx::Env const &env, CoarsenedVault const &coarsened)
Number debitAvailable(test::jtx::Env &env, CoarsenedVault const &coarsened, Debit kind, test::jtx::Account const &issuer, test::jtx::Account const &depositor, PrettyAsset const &asset, Number const &amount)
static std::uint64_t toU64(SLE::ConstRef vault, TypedField< T > const &field)
CoarsenedVault coarsenVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset, CoarsenParams const &params)
void compoundVaultBySoleHolderLoanCycles(test::jtx::Env &env, LendingFixture const &fixture, test::jtx::Account const &depositor, PrettyAsset const &asset, int cycles)
void checkVaultLoanSums(test::jtx::Env &env, CoarsenedVault const &coarsened, std::string const &label={})
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
std::uint64_t mantissa() const noexcept
Definition STAmount.h:490
int exponent() const noexcept
Definition STAmount.h:459
std::shared_ptr< STLedgerEntry const > const & ConstRef
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
static AssetAccounts setupIou(test::jtx::Env &env, IouParams const &params)
VaultSnapshot snapshotVault(test::jtx::Env &env, Keylet const &vaultKeylet, PrettyAsset const &asset)
void expectCoarsened(test::jtx::Env const &env, Keylet const &vaultKeylet)
test::jtx::PrettyAsset PrettyAsset
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
T end(T... args)
T insert(T... args)
constexpr Zero kZero
Definition Zero.h:30
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
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage)
Definition Protocol.h:127
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
Number roundPeriodicPayment(Asset const &asset, Number const &periodicPayment, std::int32_t scale)
Ensure the periodic payment is always rounded consistently.
T push_back(T... args)
T size(T... args)
UInt256 key
Definition Keylet.h:21
std::optional< test::jtx::Account > borrower
A field with a type known at compile time.
Definition SField.h:307