xrpld
Loading...
Searching...
No Matches
LoanDefaultCoverTests.cpp
1#include <xrpl/basics/Number.h>
2#include <xrpl/basics/base_uint.h>
3#include <xrpl/protocol/Asset.h>
4#include <xrpl/protocol/Indexes.h>
5#include <xrpl/protocol/Issue.h>
6#include <xrpl/protocol/MPTIssue.h>
7#include <xrpl/protocol/Protocol.h>
8#include <xrpl/protocol/SField.h>
9#include <xrpl/protocol/STAmount.h>
10#include <xrpl/protocol/STLedgerEntry.h>
11#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
12#include <xrpl/protocol/STTakesAsset.h>
13#include <xrpl/protocol/UintTypes.h>
14#include <xrpl/protocol/Units.h>
15#include <xrpl/tx/transactors/lending/LoanManage.h>
16
17#include <gtest/gtest.h>
18#include <helpers/Account.h>
19#include <protocol/VaultTestHelpers.h>
20
21#include <algorithm>
22#include <cstdint>
23#include <memory>
24#include <random>
25#include <sstream>
26
27namespace xrpl {
28namespace {
29
30// Minimal bare LoanBroker SLE carrying the fields calculateDefaultCover reads:
31// CoverAvailable, DebtTotal, and the two cover rates. Not a valid ledger entry
32// on its own -- just enough for the function's own field reads.
33std::shared_ptr<SLE>
34makeBroker(
35 Asset const& asset,
36 Number const& coverAvailable,
37 Number const& debtTotal,
38 TenthBips32 coverRateMinimum,
39 TenthBips32 coverRateLiquidation)
40{
42 broker->at(sfCoverAvailable) = coverAvailable;
43 broker->at(sfDebtTotal) = debtTotal;
44 broker->at(sfCoverRateMinimum) = coverRateMinimum.value();
45 broker->at(sfCoverRateLiquidation) = coverRateLiquidation.value();
46 associateAsset(*broker, asset);
47 return broker;
48}
49
50// Minimal bare Loan SLE carrying the only field calculateDefaultCover reads:
51// PrincipalOutstanding.
52std::shared_ptr<SLE>
53makeLoan(Asset const& asset, Number const& principalOutstanding)
54{
56 loan->at(sfPrincipalOutstanding) = principalOutstanding;
57 associateAsset(*loan, asset);
58 return loan;
59}
60
61// Replicates calculateDefaultCover's uncapped XLS-66 raw cover computation
62// (same Upward rounding), so tests can independently verify the
63// CoverAvailable/PrincipalOutstanding cap without duplicating
64// calculateDefaultCover itself.
66rawCoverFor(
67 Number const& debtTotal,
68 TenthBips32 coverRateMinimum,
69 TenthBips32 coverRateLiquidation,
70 Number const& principalOutstanding)
71{
73 Number const minimumCover = tenthBipsOfValue(debtTotal, coverRateMinimum);
74 return std::min(tenthBipsOfValue(minimumCover, coverRateLiquidation), principalOutstanding);
75}
76
77struct CoverCase
78{
79 Number assetsAvailable;
80 Number coverAvailable;
81 Number debtTotal;
82 TenthBips32 coverRateMinimum;
83 TenthBips32 coverRateLiquidation;
84 Number principalOutstanding;
85};
86
87// Builds the ledger entries for one case, calls calculateDefaultCover, and
88// checks every invariant defaultLoanFixedPrecision itself asserts right after
89// the call: cover is non-negative, never exceeds the uncapped XLS-66 amount
90// or the broker's CoverAvailable, leaves AssetsAvailable + cover exactly
91// representable (STAmount round-trips to the same Number) whenever the cover
92// can carry AssetsAvailable's digits, and rounds CoverAvailable - cover by at
93// most half an ulp.
94void
95checkCoverCase(Asset const& asset, std::uint8_t scale, CoverCase const& in)
96{
97 auto const vault = makeVault(
98 asset,
99 in.assetsAvailable,
101 scale,
102 Number{0},
103 in.assetsAvailable);
104 auto const broker = makeBroker(
105 asset, in.coverAvailable, in.debtTotal, in.coverRateMinimum, in.coverRateLiquidation);
106 auto const loan = makeLoan(asset, in.principalOutstanding);
107
108 STAmount const cover = LoanManage::calculateDefaultCover(loan, broker, vault);
109
110 Number const rawCover = rawCoverFor(
111 in.debtTotal, in.coverRateMinimum, in.coverRateLiquidation, in.principalOutstanding);
112
113 std::ostringstream context;
114 context << "scale=" << int(scale) << " assetsAvailable=" << in.assetsAvailable
115 << " coverAvailable=" << in.coverAvailable << " debtTotal=" << in.debtTotal
116 << " coverRateMinimum=" << in.coverRateMinimum.value()
117 << " coverRateLiquidation=" << in.coverRateLiquidation.value()
118 << " principalOutstanding=" << in.principalOutstanding << " rawCover=" << rawCover
119 << " cover=" << Number(cover);
120
121 EXPECT_GE(Number(cover), Number{0}) << "cover < 0: " << context.str();
122 EXPECT_LE(Number(cover), rawCover) << "cover exceeds uncapped XLS-66 amount: " << context.str();
123 EXPECT_LE(Number(cover), in.coverAvailable)
124 << "cover exceeds CoverAvailable: " << context.str();
125
126 // AssetsAvailable + cover is exact unless AssetsAvailable has digits finer
127 // than the 16-digit cover can carry; then no cover cancels them, and the
128 // sum rounds by at most half an ulp of its posterior grid.
129 Number const vaultSum = in.assetsAvailable + Number(cover);
130 STAmount const vaultRounded{asset, vaultSum};
131 bool const coverCanCarryAssetsAvailable =
133 asset,
134 in.assetsAvailable,
135 xrpl::scale(Number(cover), asset),
136 Number::RoundingMode::TowardsZero) == in.assetsAvailable;
137 if (coverCanCarryAssetsAvailable)
138 {
139 EXPECT_EQ(Number(vaultRounded), vaultSum)
140 << "AssetsAvailable + cover not exactly 16-digit representable: " << context.str();
141 }
142 else
143 {
144 Number const vaultRoundingError = abs(Number(vaultRounded) - vaultSum);
145 EXPECT_LE(vaultRoundingError, Number(5, xrpl::scale(Number(vaultRounded), asset) - 1))
146 << "AssetsAvailable + cover rounding error exceeds half a posterior ulp: "
147 << context.str();
148 }
149
150 // The LoanBroker absorbs the rounding: CoverAvailable - cover rounds to
151 // nearest, so the error stays within half an ulp of its posterior grid.
152 Number const brokerSum = in.coverAvailable - Number(cover);
153 STAmount const brokerRounded{asset, brokerSum};
154 Number const brokerRoundingError = abs(Number(brokerRounded) - brokerSum);
155 EXPECT_LE(brokerRoundingError, Number(5, xrpl::scale(Number(brokerRounded), asset) - 1))
156 << "CoverAvailable - cover rounding error exceeds half a posterior ulp: " << context.str();
157}
158
159} // namespace
160
161TEST(LoanDefaultCover, hand_picked_cases)
162{
163 test::Account const issuer{"issuer"};
164 Issue const iou{toCurrency("USD"), issuer.id()};
165 std::uint8_t const scale = 6;
166
167 TenthBips32 const halfRate = percentageToTenthBips(50);
168 TenthBips32 const fullRate = lending::kMaxCoverRate;
169
170 // Open zone: AssetsAvailable and CoverAvailable both well under the Open
171 // limit (9 * 10^9 at Scale 6); every grid involved stays at the fine
172 // (scale-6) exponent.
173 checkCoverCase(
174 iou,
175 scale,
176 {
177 .assetsAvailable = Number{1000},
178 .coverAvailable = Number{5000},
179 .debtTotal = Number{10000},
180 .coverRateMinimum = halfRate,
181 .coverRateLiquidation = halfRate,
182 .principalOutstanding = Number{2000},
183 });
184
185 // CoverAvailable coarsened above the Open limit (20,000,000,000.00000,
186 // 16 significant digits); AssetsAvailable stays small and fine.
187 Number const coarseCoverAvailable{2'000'000'000'000'000, -5};
188 checkCoverCase(
189 iou,
190 scale,
191 {
192 .assetsAvailable = Number{100},
193 .coverAvailable = coarseCoverAvailable,
194 .debtTotal = Number{1000},
195 .coverRateMinimum = fullRate,
196 .coverRateLiquidation = fullRate,
197 .principalOutstanding = Number{500},
198 });
199
200 // AssetsAvailable one unit below a power of ten (9,999,999,999.999999,
201 // 16 significant digits already); CoverAvailable stays small and fine.
202 Number const coarseAssetsAvailable{9'999'999'999'999'999, -6};
203 checkCoverCase(
204 iou,
205 scale,
206 {
207 .assetsAvailable = coarseAssetsAvailable,
208 .coverAvailable = Number{50},
209 .debtTotal = Number{1000},
210 .coverRateMinimum = fullRate,
211 .coverRateLiquidation = fullRate,
212 .principalOutstanding = Number{30},
213 });
214
215 // Both AssetsAvailable and CoverAvailable coarsened.
216 checkCoverCase(
217 iou,
218 scale,
219 {
220 .assetsAvailable = coarseAssetsAvailable,
221 .coverAvailable = coarseCoverAvailable,
222 .debtTotal = Number{1000},
223 .coverRateMinimum = fullRate,
224 .coverRateLiquidation = fullRate,
225 .principalOutstanding = Number{900},
226 });
227
228 // Cover capped by CoverAvailable: the uncapped XLS-66 amount vastly
229 // exceeds the broker's available cover.
230 checkCoverCase(
231 iou,
232 scale,
233 {
234 .assetsAvailable = Number{1000},
235 .coverAvailable = Number{1},
236 .debtTotal = Number{1'000'000},
237 .coverRateMinimum = fullRate,
238 .coverRateLiquidation = fullRate,
239 .principalOutstanding = Number{1'000'000},
240 });
241
242 // Cover capped by PrincipalOutstanding: DebtTotal times both rates would
243 // exceed the Loan's own outstanding principal.
244 checkCoverCase(
245 iou,
246 scale,
247 {
248 .assetsAvailable = Number{1000},
249 .coverAvailable = Number{1'000'000},
250 .debtTotal = Number{1'000'000},
251 .coverRateMinimum = fullRate,
252 .coverRateLiquidation = fullRate,
253 .principalOutstanding = Number{5},
254 });
255}
256
257// The raw cover carries more than 16 digits and is large enough that its last
258// 16-digit place is coarser than AssetsAvailable's grid. The sum must be floored
259// from the exact raw cover: truncating the cover to 16 digits first could cost
260// the Vault one posterior unit.
261TEST(LoanDefaultCover, uses_exact_raw_cover)
262{
263 test::Account const issuer{"issuer"};
264 Issue const iou{toCurrency("USD"), issuer.id()};
265 std::uint8_t const scale = 6;
266
267 Number const assetsAvailable{5, -6};
268 Number const coverAvailable{2, 11};
269 Number const debtTotal{1'234'567'890'123'457LL, -4};
270 TenthBips32 const rate = percentageToTenthBips(33);
271 Number const principalOutstanding{2, 11};
272
273 auto const vault = makeVault(
274 iou, assetsAvailable, VaultVersion::FixedPrecision, scale, Number{0}, assetsAvailable);
275 auto const broker = makeBroker(iou, coverAvailable, debtTotal, rate, rate);
276 auto const loan = makeLoan(iou, principalOutstanding);
277
278 Number const rawCover = rawCoverFor(debtTotal, rate, rate, principalOutstanding);
279 // The case only means something if truncating the raw cover to 16 digits
280 // loses digits that its sum with AssetsAvailable would keep.
281 ASSERT_NE(Number(STAmount{iou, rawCover}), rawCover);
282
283 STAmount const cover = LoanManage::calculateDefaultCover(loan, broker, vault);
284
285 // Floor the exact sum, then take the 16-digit credit, also rounded down.
286 STAmount const expected = [&] {
288 Number const sum = assetsAvailable + rawCover;
289 Number const flooredSum =
291 return STAmount{iou, flooredSum - assetsAvailable};
292 }();
293 EXPECT_EQ(cover, expected) << "rawCover=" << rawCover << " cover=" << Number(cover);
294}
295
296TEST(LoanDefaultCover, integral_asset_cases)
297{
298 test::Account const issuer{"issuer"};
299 TenthBips32 const fullRate = lending::kMaxCoverRate;
300
301 for (Asset const asset : {Asset{xrpIssue()}, Asset{MPTIssue{makeMptID(1, issuer.id())}}})
302 {
303 // Integral assets have no fractional grid (Scale is unused), so the
304 // same cover arithmetic must still land exactly for whole-unit
305 // amounts.
306 checkCoverCase(
307 asset,
308 0,
309 {
310 .assetsAvailable = Number{1000},
311 .coverAvailable = Number{200},
312 .debtTotal = Number{900},
313 .coverRateMinimum = fullRate,
314 .coverRateLiquidation = fullRate,
315 .principalOutstanding = Number{150},
316 });
317 }
318}
319
320TEST(LoanDefaultCover, randomized_sweep)
321{
322 test::Account const issuer{"issuer"};
323 Issue const iou{toCurrency("USD"), issuer.id()};
324
325 // NOLINTNEXTLINE(bugprone-random-generator-seed): fixed seed for reproducible test
326 std::mt19937 rng{20261002u};
327 constexpr int kIterations = 5000;
328
329 auto const pickScale = [&rng] -> std::uint8_t {
331 return static_cast<std::uint8_t>(dist(rng));
332 };
333 auto const pickRate = [&rng] -> TenthBips32 {
335 return TenthBips32{dist(rng)};
336 };
337 // Mantissa with 1 to 16 digits, biased toward landing exactly on a power
338 // of ten or one unit below it (all nines) -- the cusps where coarsening
339 // and carries are most likely to surface a bug. Always positive, since
340 // these stand in for ledger balances.
341 auto const pickMantissa = [&rng] -> std::int64_t {
342 std::uniform_int_distribution<int> digitsDist(1, 16);
343 int const digits = digitsDist(rng);
344 std::int64_t powerOfTen = 1;
345 for (int i = 0; i < digits - 1; ++i)
346 powerOfTen *= 10;
347
349 int const shape = shapeDist(rng);
350 if (shape == 0)
351 return powerOfTen; // bare power of ten
352 if (shape == 1)
353 return (powerOfTen * 10) - 1; // all nines, one digit up
354
355 std::uniform_int_distribution<std::int64_t> mantissaDist(powerOfTen, (powerOfTen * 10) - 1);
356 return mantissaDist(rng);
357 };
358 // A FixedPrecision Vault never holds a balance finer than its own Scale
359 // (exponent must be >= -scale); minExponent enforces that so every
360 // generated case is a state the real system could actually reach.
361 auto const pickExponent = [&rng](int minExponent) -> int {
362 std::uniform_int_distribution<int> dist(minExponent, minExponent + 25);
363 return dist(rng);
364 };
365 auto const pickNumber = [&](int minExponent) -> Number {
366 return Number{pickMantissa(), pickExponent(minExponent)};
367 };
368
369 for (int i = 0; i < kIterations; ++i)
370 {
371 std::uint8_t const scale = pickScale();
372 int const minExponent = -static_cast<int>(scale);
373 CoverCase const in{
374 .assetsAvailable = pickNumber(minExponent),
375 .coverAvailable = pickNumber(minExponent),
376 .debtTotal = pickNumber(minExponent),
377 .coverRateMinimum = pickRate(),
378 .coverRateLiquidation = pickRate(),
379 .principalOutstanding = pickNumber(minExponent),
380 };
381
382 checkCoverCase(iou, scale, in);
383 }
384}
385
386} // namespace xrpl
A currency issued by an account.
Definition Issue.h:18
static STAmount calculateDefaultCover(SLE::Ref loanSle, SLE::Ref brokerSle, SLE::Ref vaultSle)
Compute the First-Loss Capital cover amount for a defaulted Loan on a FixedPrecision Vault,...
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
T make_shared(T... args)
T min(T... args)
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 loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
constexpr TenthBips32 kMaxCoverRate
The maximum coverage rate required of a loan broker in 1/10 bips.
Definition Protocol.h:159
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
static auto sum(TCollection const &col)
TEST(FileUtilitiesTest, get_file_contents)
constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage)
Definition Protocol.h:127
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
std::shared_ptr< SLE > makeVault(Asset const &asset, Number const &assetsTotal, std::optional< VaultVersion > version, std::uint8_t scaleValue=kVaultDefaultIouScale, Number const &assetsDeployed=Number{0}, std::optional< Number > assetsAvailable=std::nullopt)
bool toCurrency(Currency &, std::string const &)
Tries to convert a string to a Currency, returns true on success.
Definition UintTypes.cpp:65
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
constexpr std::uint8_t kFixedPrecisionVaultMaximumIouScale
Maximum Scale for a Vault created under featureLendingProtocolV1_2.
Definition Protocol.h:325
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
constexpr Number abs(Number x) noexcept
Definition Number.h:880
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:745
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
UInt256 uint256
Definition base_uint.h:587
T str(T... args)