xrpld
Loading...
Searching...
No Matches
VaultHelpers.cpp
1#include <xrpl/ledger/helpers/VaultHelpers.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/View.h>
10#include <xrpl/ledger/helpers/CredentialHelpers.h>
11#include <xrpl/protocol/AccountID.h>
12#include <xrpl/protocol/Asset.h>
13#include <xrpl/protocol/Feature.h>
14#include <xrpl/protocol/Indexes.h>
15#include <xrpl/protocol/LedgerFormats.h> // IWYU pragma: keep
16#include <xrpl/protocol/Protocol.h>
17#include <xrpl/protocol/SField.h>
18#include <xrpl/protocol/STAmount.h>
19#include <xrpl/protocol/STLedgerEntry.h>
20#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/protocol/TER.h>
23
24#include <algorithm>
25#include <cstdint>
26#include <expected>
27#include <optional>
28#include <stdexcept>
29#include <string_view>
30#include <utility>
31
32namespace xrpl {
33
34namespace {
35
36[[nodiscard]] int
37fixedBaseScale(SLE::ConstRef vault)
38{
39 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::fixedBaseScale : valid Vault sle");
40 Asset const asset = vault->at(sfAsset);
41 // sfScale is never written for an integral asset (VaultCreate only sets
42 // it when scale != 0, and integral assets always get scale 0), so it
43 // must not be read here; vaultBaseScale ignores the scale argument for
44 // an integral asset anyway.
45 if (asset.integral())
46 return 0;
47 return vaultBaseScale(asset, vault->at(sfScale));
48}
49
50// Thin, vault-specific wrapper over posteriorAssetScale: used by
51// getPosteriorVaultScale and the cash outflow rounding below.
52[[nodiscard]] int
53posteriorScale(SLE::ConstRef vault, Number const& reference, Number const& delta)
54{
56 getVaultVersion(vault), vault->at(sfAsset), fixedBaseScale(vault), reference, delta);
57}
58
59// FixedPrecision-only counterpart to clampToAssetsTotalScale, for cash
60// outflows (VaultWithdraw, VaultClawback): rounds the magnitude of delta
61// toward zero at AssetsAvailable's own posterior scale, the balance the cash
62// actually leaves, instead of the derived AssetsTotal cache. Same
63// tecPRECISION_LOSS and integral-asset and magnitude-never-exceeds-delta
64// rules as clampToAssetsTotalScale. Not part of the public interface; reached
65// only through clampVaultOutflow.
66//
67// For an outflow it is safe to round the delta directly, unlike the credit
68// case: amount on the posterior grid of AssetsAvailable always leaves
69// AssetsAvailable minus amount representable, since the posterior grid is
70// exactly the grid AssetsAvailable itself will canonicalize to after the
71// subtraction.
72[[nodiscard]] std::expected<STAmount, TER>
73clampToAvailableScale(SLE::ConstRef vault, STAmount const& delta)
74{
75 XRPL_ASSERT(
76 delta.asset() == vault->at(sfAsset),
77 "xrpl::clampToAvailableScale : delta and vault asset match");
78 XRPL_ASSERT(
80 "xrpl::clampToAvailableScale : FixedPrecision Vault");
81 XRPL_ASSERT(delta.negative(), "xrpl::clampToAvailableScale : outflow delta is negative");
82
83 Asset const asset = vault->at(sfAsset);
84 STAmount magnitude = delta.negative() ? -delta : delta;
85 if (asset.integral())
86 return magnitude;
87
88 STAmount const rounded = roundToScale(
89 delta,
90 posteriorScale(vault, vault->at(sfAssetsAvailable), delta),
92 STAmount actualDelta = rounded.negative() ? -rounded : rounded;
93
94 XRPL_ASSERT(
95 abs(actualDelta) <= abs(delta),
96 "xrpl::clampToAvailableScale : actual delta smaller or equal to calculated delta");
97
98 // Reject changes below scale precision (1 ULP) to prevent share balance changes
99 // without corresponding asset movements.
100 if (actualDelta <= beast::kZero)
102
103 return actualDelta;
104}
105
106[[nodiscard]] VaultKind
107decodeVaultKind(std::optional<std::uint8_t> vaultKind)
108{
109 if (vaultKind && *vaultKind == std::to_underlying(VaultKind::ClosedEnded))
112}
113
114// Write cached AssetsTotal from getAssetsTotal, as the exact total rounded
115// Downward to the Vault asset's 16-digit STAmount representation. Below
116// coarsening this equals the exact total; above it, the cache is a
117// deliberate floor of the exact value. Internal to adjustVaultBalances,
118// the only writer of AssetsAvailable, AssetsDeployed, AssetsTotal,
119// YieldUnrealized and LossUnrealized on a FixedPrecision Vault after
120// creation; not part of the public interface.
121void
122syncAssetsTotal(SLE::Ref vault)
123{
124 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::syncAssetsTotal : valid Vault sle");
125 Asset const asset = vault->at(sfAsset);
126
127 // adjustVaultBalances writes AssetsAvailable as an already-canonical
128 // STAmount before calling this, so the associateAsset pass a transactor
129 // runs afterwards is always a no-op. If this fires, AssetsAvailable was
130 // written some other way.
131 XRPL_ASSERT(
132 (STAmount{asset, vault->at(sfAssetsAvailable)} == vault->at(sfAssetsAvailable)),
133 "xrpl::syncAssetsTotal : AssetsAvailable is a 16-digit STAmount value");
134
136 vault->at(sfAssetsTotal) = STAmount{asset, getAssetsTotal(vault)};
137}
138
139[[nodiscard]] bool
140debitIsNonZeroDust(SLE::ConstRef vault, Number const& amount)
141{
142 if (amount == 0)
143 return false;
144
145 auto const total = getVaultVersion(vault) == VaultVersion::FixedPrecision
146 ? vault->at(sfAssetsAvailable)
147 : getAssetsTotal(vault);
148 auto const asset = vault->at(sfAsset);
149 return STAmount{asset, total - amount} == STAmount{asset, total};
150}
151} // namespace
152
153namespace detail {
154
155[[nodiscard]] int
156liveScale(Number const& reference, Asset const& asset, int baseScale)
157{
158 if (reference == beast::kZero)
159 return baseScale;
160 // Round Downward, not the ambient mode: the live exponent must match the
161 // exponent syncAssetsTotal actually stores (also Downward), regardless of
162 // what rounding mode the caller's own arithmetic is using.
164 return std::max(baseScale, scale(reference, asset));
165}
166
167[[nodiscard]] int
169 VaultVersion version,
170 Asset const& asset,
171 int baseScale,
172 Number const& reference,
173 Number const& delta)
174{
175 // ToNearest for the sum and for scale()'s canonicalization of it, as the
176 // Legacy/CashBasis clamp always did; liveScale sets its own mode.
178 Number const posterior = reference + delta;
179
180 switch (version)
181 {
184 return scale(posterior, asset);
186 return liveScale(posterior, asset, baseScale);
187 }
188 // LCOV_EXCL_START
189 UNREACHABLE("xrpl::detail::posteriorAssetScale : valid VaultVersion");
190 return Number::kMinExponent - 1;
191 // LCOV_EXCL_STOP
192}
193
194[[nodiscard]] STAmount
196 Asset const& asset,
197 Number const& reference,
198 int baseScale,
199 Number const& raw,
200 Number::RoundingMode roundingMode)
201{
202 // Floor the SUM (reference + raw), not just raw. See
203 // creditToPosteriorAvailableScale's doc: a delta floored on its own grid
204 // can still leave a 17-digit sum once the reference has crossed a power
205 // of ten.
206 //
207 // Both reference + raw and flooredSum - reference can carry more digits
208 // than Number holds (the sum is on the posterior grid, the reference on
209 // the finer one). Compute both under roundingMode, not the caller's
210 // ambient mode, so the credit this returns never exceeds raw.
211 //
212 // Take the grid from this same sum. A sum just under a power of ten that
213 // rounds up to it in another mode would pick the coarser grid, and
214 // flooring the unrounded sum on it would land below reference.
215 NumberRoundModeGuard const rg(roundingMode);
216 Number const sum = reference + raw;
217 int const atScale = liveScale(sum, asset, baseScale);
218 Number const flooredSum = roundToAsset(asset, sum, atScale, roundingMode);
219 STAmount const credit{asset, flooredSum - reference};
220 XRPL_ASSERT_PARTS(
221 roundingMode != Number::RoundingMode::Downward ||
222 (credit >= beast::kZero && Number(credit) <= raw),
223 "xrpl::detail::creditToPosteriorScale",
224 "credit is between zero and raw");
225 return credit;
226}
227
228[[nodiscard]] int
230{
231 XRPL_ASSERT(
232 vault && vault->getType() == ltVAULT,
233 "xrpl::detail::getPosteriorVaultScale : valid Vault sle");
234 XRPL_ASSERT(
235 delta.asset() == vault->at(sfAsset),
236 "xrpl::detail::getPosteriorVaultScale : delta and Vault asset match");
237 return posteriorScale(vault, getAssetsTotal(vault), delta);
238}
239
240} // namespace detail
241
242[[nodiscard]] Number
244{
245 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getAssetsTotal : valid Vault sle");
246
248 return vault->at(sfAssetsTotal);
249
250 // AssetsAvailable is at -Scale (or coarser) and AssetsDeployed is always at
251 // -Scale, so the sum is exact while it fits 19 digits. Fix the mode so a
252 // sum that does not fit rounds the same way for every caller.
254 return vault->at(sfAssetsAvailable) + vault->at(sfAssetsDeployed);
255}
256
257[[nodiscard]] TER
259{
260 XRPL_ASSERT(
261 vault && vault->getType() == ltVAULT, "xrpl::adjustVaultBalances : valid Vault sle");
262 XRPL_ASSERT(
264 "xrpl::adjustVaultBalances : FixedPrecision Vault");
265 Asset const asset = vault->at(sfAsset);
266 STAmount const cash = change.cash.value_or(STAmount{asset, 0});
267 XRPL_ASSERT(cash.asset() == asset, "xrpl::adjustVaultBalances : cash and Vault asset match");
268 // This is the mode the ledger's own transfers (trust line / MPT balance
269 // updates) normalize in; computing AA' with any other ambient mode would
270 // not reproduce what the real transfer just did to the backing balance.
271 XRPL_ASSERT(
273 "xrpl::adjustVaultBalances : ambient rounding mode is ToNearest");
274
275 // AA' is the exact trust-line/MPT arithmetic the ledger uses for the
276 // transfer itself: a Number sum re-canonicalized to the asset's 16-digit
277 // STAmount precision. MPT and XRP sums are already integral, so this is
278 // a no-op rounding for them.
279 //
280 // AssetsDeployed, LossUnrealized and YieldUnrealized move no cash, so they stay
281 // exact Number sums; the asserts below check each fits 16 digits, rather
282 // than letting an STAmount conversion round it silently.
283 STAmount const availableAfter{asset, Number(vault->at(sfAssetsAvailable)) + Number(cash)};
284 Number const assetsDeployedAfter = Number(vault->at(sfAssetsDeployed)) + change.deployed;
285 Number const lossUnrealizedAfter = Number(vault->at(sfLossUnrealized)) + change.loss;
286 // LoanSet, LoanPay and default each move YieldUnrealized by the change in
287 // the Loan's own TotalValueOutstanding - PrincipalOutstanding -
288 // ManagementFeeOutstanding, so it always equals that sum over the
289 // Vault's Loans and cannot go negative.
290 Number const yieldUnrealizedAfter = Number(vault->at(sfYieldUnrealized)) + change.yield;
291
292 if (availableAfter < beast::kZero || assetsDeployedAfter < beast::kZero ||
293 lossUnrealizedAfter < beast::kZero || yieldUnrealizedAfter < beast::kZero)
294 {
295 // LCOV_EXCL_START
296 JLOG(j.fatal()) << "adjustVaultBalances: a balance would become negative."
297 << " AssetsAvailable: " << Number(availableAfter)
298 << ", AssetsDeployed: " << assetsDeployedAfter
299 << ", LossUnrealized: " << lossUnrealizedAfter
300 << ", YieldUnrealized: " << yieldUnrealizedAfter;
301 return tefBAD_LEDGER;
302 // LCOV_EXCL_STOP
303 }
304
305 // The impairment rule: a Loan can only be impaired for as much as it
306 // still owes. Reachable only through LoanManage's impair.
307 if (lossUnrealizedAfter > assetsDeployedAfter)
308 return tecLIMIT_EXCEEDED;
309
310 // Every caller derives principal from a Loan's own PrincipalOutstanding so the new total must
311 // stay representable at the asset's own 16-digit precision too.
312 XRPL_ASSERT(
313 (STAmount{asset, assetsDeployedAfter} == assetsDeployedAfter),
314 "xrpl::adjustVaultBalances : AssetsDeployed is a 16-digit STAmount value");
315 XRPL_ASSERT(
316 (STAmount{asset, lossUnrealizedAfter} == lossUnrealizedAfter),
317 "xrpl::adjustVaultBalances : LossUnrealized is a 16-digit STAmount value");
318 XRPL_ASSERT(
319 (STAmount{asset, yieldUnrealizedAfter} == yieldUnrealizedAfter),
320 "xrpl::adjustVaultBalances : YieldUnrealized is a 16-digit STAmount value");
321
322 vault->at(sfAssetsAvailable) = availableAfter;
323 vault->at(sfAssetsDeployed) = assetsDeployedAfter;
324 vault->at(sfLossUnrealized) = lossUnrealizedAfter;
325 vault->at(sfYieldUnrealized) = yieldUnrealizedAfter;
326 syncAssetsTotal(vault);
327
328 return tesSUCCESS;
329}
330
331[[nodiscard]] TER
333{
335 return adjustVaultBalances(vault, {.cash = delta}, j);
336
337 vault->at(sfAssetsTotal) += delta;
338 vault->at(sfAssetsAvailable) += delta;
339 return tesSUCCESS;
340}
341
342[[nodiscard]] int
344{
345 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultScale : valid Vault sle");
346
347 Number const assetsTotal = getAssetsTotal(vault);
348 switch (getVaultVersion(vault))
349 {
352 return scale(assetsTotal, vault->at(sfAsset));
354 return detail::liveScale(assetsTotal, vault->at(sfAsset), fixedBaseScale(vault));
355 }
356 // LCOV_EXCL_START
357 UNREACHABLE("xrpl::getVaultScale : valid VaultVersion");
358 return Number::kMinExponent - 1;
359 // LCOV_EXCL_STOP
360}
361
362[[nodiscard]] int
364{
365 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultBaseScale : valid Vault sle");
366
367 switch (getVaultVersion(vault))
368 {
371 return getVaultScale(vault);
373 return fixedBaseScale(vault);
374 }
375 // LCOV_EXCL_START
376 UNREACHABLE("xrpl::getVaultBaseScale : valid VaultVersion");
377 return Number::kMinExponent - 1;
378 // LCOV_EXCL_STOP
379}
380
381[[nodiscard]] STAmount
383 SLE::ConstRef vault,
384 STAmount const& amount,
385 Number::RoundingMode roundingMode)
386{
387 XRPL_ASSERT(
388 vault && vault->getType() == ltVAULT, "xrpl::roundToPosteriorVaultScale : valid Vault sle");
389 XRPL_ASSERT(
390 amount.asset() == vault->at(sfAsset),
391 "xrpl::roundToPosteriorVaultScale : amount and Vault asset match");
392 if (amount.integral())
393 return amount;
394 return roundToScale(amount, detail::getPosteriorVaultScale(vault, amount), roundingMode);
395}
396
397[[nodiscard]] STAmount
399 SLE::ConstRef vault,
400 Number const& raw,
401 Number::RoundingMode roundingMode)
402{
403 XRPL_ASSERT(
404 vault && vault->getType() == ltVAULT,
405 "xrpl::creditToPosteriorAvailableScale : valid Vault sle");
406 Asset const asset = vault->at(sfAsset);
407 if (asset.integral())
408 {
409 NumberRoundModeGuard const rg(roundingMode);
410 return STAmount{asset, raw};
411 }
412
413 Number const reference = vault->at(sfAssetsAvailable);
415 asset, reference, fixedBaseScale(vault), raw, roundingMode);
416}
417
418[[nodiscard]] Number
420{
421 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultOpenLimit : valid Vault sle");
422 XRPL_ASSERT(
424 "xrpl::getVaultOpenLimit : FixedPrecision Vault");
425 return Number{9, 15 + getVaultBaseScale(vault)};
426}
427
428[[nodiscard]] TER
430{
431 XRPL_ASSERT(
432 vault && vault->getType() == ltVAULT, "xrpl::checkOptionalVaultInflow : valid Vault sle");
433 XRPL_ASSERT(
434 amount.asset() == vault->at(sfAsset),
435 "xrpl::checkOptionalVaultInflow : amount and Vault asset match");
436 XRPL_ASSERT(!amount.negative(), "xrpl::checkOptionalVaultInflow : non-negative amount");
437 if (amount.negative())
438 return tefINTERNAL; // LCOV_EXCL_LINE
440 return tesSUCCESS;
441
442 STAmount const rounded =
444 int const baseScale = getVaultBaseScale(vault);
445 // Keep this explicit even though a non-negative YieldUnrealized makes the
446 // Open-zone capacity ceiling reject every coarsening transition too. The
447 // protocol defines both conditions independently.
448 if (detail::getPosteriorVaultScale(vault, rounded) != baseScale)
449 return tecLIMIT_EXCEEDED;
450
451 if (vaultOpenZoneCapacity(vault, rounded) > getVaultOpenLimit(vault))
452 return tecLIMIT_EXCEEDED;
453 return tesSUCCESS;
454}
455
456[[nodiscard]] Number
457vaultOpenZoneCapacity(SLE::ConstRef vault, Number const& roundedAmount)
458{
459 XRPL_ASSERT(
460 vault && vault->getType() == ltVAULT, "xrpl::vaultOpenZoneCapacity : valid Vault sle");
461 XRPL_ASSERT(
463 "xrpl::vaultOpenZoneCapacity : FixedPrecision Vault");
465 return getAssetsTotal(vault) + vault->at(sfYieldUnrealized) + roundedAmount;
466}
467
468[[nodiscard]] TER
470 SLE::ConstRef vault,
471 Number const& amount,
473 std::string_view name)
474{
475 try
476 {
477 if (debitIsNonZeroDust(vault, amount))
478 {
479 JLOG(j.debug()) << name << ": amount too small to change stored vault balance";
480 return tecPRECISION_LOSS;
481 }
482 }
483 // LCOV_EXCL_START
484 catch (std::overflow_error const&)
485 {
486 // It's easy to hit this exception from Number with large enough Scale
487 // so we avoid spamming the log and only use debug here.
488 JLOG(j.debug()) //
489 << name << ": overflow error with"
490 << " scale=" << (int)vault->at(sfScale) //
491 << ", assetsTotal=" << vault->at(sfAssetsTotal) << ", amount=" << amount;
492 return tecPATH_DRY;
493 }
494 // LCOV_EXCL_STOP
495 return tesSUCCESS;
496}
497
498[[nodiscard]] std::optional<STAmount>
500{
501 XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets");
502 XRPL_ASSERT(
503 assets.asset() == vault->at(sfAsset),
504 "xrpl::assetsToSharesDeposit : assets and vault match");
505 if (assets.negative() || assets.asset() != vault->at(sfAsset))
506 return std::nullopt; // LCOV_EXCL_LINE
507
508 Number const assetTotal = getAssetsTotal(vault);
509 STAmount shares{vault->at(sfShareMPTID)};
510 if (assetTotal == 0)
511 {
512 return STAmount{
513 shares.asset(),
514 Number(assets.mantissa(), assets.exponent() + vault->at(sfScale)).truncate()};
515 }
516
517 Number const shareTotal = issuance->at(sfOutstandingAmount);
518 shares = ((shareTotal * assets) / assetTotal).truncate();
519 return shares;
520}
521
522[[nodiscard]] std::optional<STAmount>
524{
525 XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares");
526 XRPL_ASSERT(
527 shares.asset() == vault->at(sfShareMPTID),
528 "xrpl::sharesToAssetsDeposit : shares and vault match");
529 if (shares.negative() || shares.asset() != vault->at(sfShareMPTID))
530 return std::nullopt; // LCOV_EXCL_LINE
531
532 Number const assetTotal = getAssetsTotal(vault);
533 STAmount assets{vault->at(sfAsset)};
534 if (assetTotal == 0)
535 {
536 return STAmount{
537 assets.asset(), shares.mantissa(), shares.exponent() - vault->at(sfScale), false};
538 }
539
540 Number const shareTotal = issuance->at(sfOutstandingAmount);
541 assets = (assetTotal * shares) / shareTotal;
542 return assets;
543}
544
545[[nodiscard]] std::expected<STAmount, TER>
547{
548 XRPL_ASSERT(
549 delta.asset() == vault->at(sfAsset),
550 "xrpl::clampToAssetsTotalScale : delta and vault asset match");
551
552 Asset const asset = vault->at(sfAsset);
553
554 STAmount magnitude = delta.negative() ? -delta : delta;
555 if (asset.integral())
556 {
557 return magnitude;
558 }
559
560 STAmount actualDelta;
562 {
563 // FixedPrecision only reaches this branch for credits (VaultDeposit);
564 // outflows go through clampVaultOutflow -> clampToAvailableScale,
565 // which rounds at AssetsAvailable's own posterior scale instead.
566 XRPL_ASSERT(
567 !delta.negative(), "xrpl::clampToAssetsTotalScale : FixedPrecision credit only");
568 STAmount const rounded =
570 actualDelta = rounded.negative() ? -rounded : rounded;
571 }
572 else
573 {
574 Number const assetsTotal = getAssetsTotal(vault);
575
576 // Calculate the scale after applying the delta using ToNearest rounding.
577 // This aligns the delta with scale checks used by vault invariants.
578 int const postScale = [&] {
580 return scale(assetsTotal + delta, asset);
581 }();
582
583 if (delta.negative())
584 {
585 // For withdrawals (debits), floor the magnitude to the target scale
586 // to ensure exact grid alignment without paying out extra assets.
587 actualDelta = roundToScale(magnitude, postScale, Number::RoundingMode::Downward);
588 }
589 else
590 {
591 // For deposits (credits), derive actualDelta from the floored posterior total.
592 // This prevents grid alignment issues from crediting the vault more than deposited.
593 //
594 // Sum using Downward rounding so intermediate precision doesn't round up
595 // and exceed the original requested amount.
596 Number const posterior = [&] {
598 return assetsTotal + magnitude;
599 }();
600
601 Number const roundedPosterior =
602 roundToAsset(asset, posterior, postScale, Number::RoundingMode::Downward);
603 actualDelta = STAmount{asset, roundedPosterior - assetsTotal};
604 }
605 }
606
607 XRPL_ASSERT(
608 abs(actualDelta) <= abs(delta),
609 "xrpl::clampToAssetsTotalScale : actual delta smaller or equal to calculated delta");
610
611 // Reject changes below scale precision (1 ULP) to prevent share balance changes
612 // without corresponding asset movements.
613 if (actualDelta <= beast::kZero)
615
616 return actualDelta;
617}
618
619[[nodiscard]] std::expected<STAmount, TER>
621{
622 XRPL_ASSERT(delta.negative(), "xrpl::clampVaultOutflow : outflow delta is negative");
624 ? clampToAvailableScale(vault, delta)
625 : clampToAssetsTotalScale(vault, delta);
626}
627
628[[nodiscard]] int
630{
631 if (asset.integral())
632 return 0;
633 return -static_cast<int>(scale);
634}
635
636[[nodiscard]] bool
637isOnVaultBaseGrid(Asset const& asset, Number const& value, int baseScale)
638{
639 // isRepresentable first: building an STAmount from an out-of-range value
640 // throws, and this checks user-supplied values in preclaim.
641 return isRepresentable(asset, value) && STAmount{asset, value} == value &&
642 roundToAsset(asset, value, baseScale, Number::RoundingMode::TowardsZero) == value;
643}
644
645[[nodiscard]] TER
647{
648 return isOnVaultBaseGrid(vault->at(sfAsset), amount, getVaultBaseScale(vault))
649 ? TER{tesSUCCESS}
651}
652
653[[nodiscard]] Number
655{
656 Number assetTotal = getAssetsTotal(vault);
657 if (waive == WaiveUnrealizedLoss::No)
658 assetTotal -= vault->at(sfLossUnrealized);
659 return assetTotal;
660}
661
662[[nodiscard]] std::optional<STAmount>
664 SLE::ConstRef vault,
665 SLE::ConstRef issuance,
666 STAmount const& assets,
667 TruncateShares truncate,
669{
670 XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesWithdraw : non-negative assets");
671 XRPL_ASSERT(
672 assets.asset() == vault->at(sfAsset),
673 "xrpl::assetsToSharesWithdraw : assets and vault match");
674 if (assets.negative() || assets.asset() != vault->at(sfAsset))
675 return std::nullopt; // LCOV_EXCL_LINE
676
677 Number const assetTotal = assetsTotalForWithdrawal(vault, waive);
678 STAmount shares{vault->at(sfShareMPTID)};
679 if (assetTotal == 0)
680 return shares;
681 Number const shareTotal = issuance->at(sfOutstandingAmount);
682 Number result = (shareTotal * assets) / assetTotal;
683 if (truncate == TruncateShares::Yes)
684 result = result.truncate();
685 shares = result;
686 return shares;
687}
688
689[[nodiscard]] std::optional<STAmount>
691 SLE::ConstRef vault,
692 SLE::ConstRef issuance,
693 STAmount const& shares,
695{
696 XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsWithdraw : non-negative shares");
697 XRPL_ASSERT(
698 shares.asset() == vault->at(sfShareMPTID),
699 "xrpl::sharesToAssetsWithdraw : shares and vault match");
700 if (shares.negative() || shares.asset() != vault->at(sfShareMPTID))
701 return std::nullopt; // LCOV_EXCL_LINE
702
703 Number const assetTotal = assetsTotalForWithdrawal(vault, waive);
704 STAmount assets{vault->at(sfAsset)};
705 if (assetTotal == 0)
706 return assets;
707 Number const shareTotal = issuance->at(sfOutstandingAmount);
708 assets = (assetTotal * shares) / shareTotal;
709 return assets;
710}
711
712[[nodiscard]] bool
713isSoleShareholder(ReadView const& view, AccountID const& account, SLE::ConstRef issuance)
714{
715 XRPL_ASSERT(
716 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
717 "xrpl::isSoleShareholder : valid issuance SLE");
718
719 std::uint64_t const outstanding = issuance->at(sfOutstandingAmount);
720 if (outstanding == 0)
721 return false;
722
723 auto const shareMPTID =
724 makeMptID(issuance->getFieldU32(sfSequence), issuance->getAccountID(sfIssuer));
725 auto const sleToken = view.read(keylet::mptoken(shareMPTID, account));
726 if (!sleToken)
727 return false; // LCOV_EXCL_LINE
728
729 return sleToken->getFieldU64(sfMPTAmount) == outstanding;
730}
731
732[[nodiscard]] VaultVersion
734{
735 if (!leVersion)
737 if (*leVersion > std::to_underlying(VaultVersion::FixedPrecision))
738 {
739 // LCOV_EXCL_START
740 UNREACHABLE("xrpl::decodeVaultVersion : invalid vault version");
742 // LCOV_EXCL_STOP
743 }
744 return static_cast<VaultVersion>(*leVersion);
745}
746
747[[nodiscard]] VaultVersion
749{
750 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultVersion : valid Vault sle");
751 return decodeVaultVersion(vault->at(~sfLEVersion));
752}
753
754[[nodiscard]] VaultVersion
756{
757 // FixedPrecision requires featureLendingProtocolV1_1 (closed-ended Vaults and
758 // cash-basis accounting) and fixCleanup3_4_0, so a FixedPrecision Vault always
759 // sees both enabled. fixCleanup3_2_0 is already enabled on the network.
760 if (rules.enabled(featureLendingProtocolV1_1) && rules.enabled(featureLendingProtocolV1_2) &&
761 rules.enabled(fixCleanup3_4_0))
763 if (rules.enabled(featureLendingProtocolV1_1))
766}
767
768[[nodiscard]] VaultKind
770{
771 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultKind : valid Vault sle");
772 return decodeVaultKind(vault->at(~sfVaultKind));
773}
774
775[[nodiscard]] VaultKind
777{
778 return decodeVaultKind(tx[~sfVaultKind]);
779}
780
781[[nodiscard]] bool
783{
784 auto const kindField = tx[~sfVaultKind];
785 if (!kindField)
786 return true;
787 return *kindField == std::to_underlying(VaultKind::OpenEnded) ||
788 *kindField == std::to_underlying(VaultKind::ClosedEnded);
789}
790
791[[nodiscard]] bool
793{
794 auto const s = static_cast<std::int64_t>(sub);
795 auto const r = static_cast<std::int64_t>(red);
796 return r >= s + kMinInvestmentPeriod && r < s + kMaxInvestmentPeriod;
797}
798
799[[nodiscard]] VaultPhase
801{
802 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::getVaultPhase : valid Vault sle");
803 return getVaultPhase(
804 view, (*vault)[~sfVaultKind], (*vault)[~sfSubscriptionDate], (*vault)[~sfRedemptionDate]);
805}
806
807[[nodiscard]] VaultPhase
809 ReadView const& view,
811 std::optional<std::uint32_t> subscriptionDate,
812 std::optional<std::uint32_t> redemptionDate)
813{
814 if (!vaultKind || *vaultKind != std::to_underlying(VaultKind::ClosedEnded))
815 return VaultPhase::NoPhase;
816
817 // Subscription includes now == SubscriptionDate; Investment starts
818 // strictly after SubscriptionDate.
819 if (!hasExpired(view, subscriptionDate, ExpiryComparison::Exclusive))
821 if (!hasExpired(view, redemptionDate))
824}
825
826[[nodiscard]] TER
828 ReadView const& view,
829 SLE::ConstRef issuance,
830 AccountID const& subject,
831 SuppressExpired suppressExpired)
832{
833 XRPL_ASSERT(
834 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
835 "xrpl::checkVaultDomain : valid issuance SLE");
836
837 auto const maybeDomainID = issuance->at(~sfDomainID);
838 if (!maybeDomainID)
839 return tecNO_AUTH;
840
841 auto const err = credentials::validDomain(view, *maybeDomainID, subject);
842 if (err == tecEXPIRED && suppressExpired == SuppressExpired::Yes)
843 return tesSUCCESS;
844
845 return err;
846}
847
848} // 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
bool integral() const
Definition Asset.h:133
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
Number truncate() const noexcept
static constexpr int kMinExponent
Definition Number.h:361
static RoundingMode getround()
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.
Rules controlling protocol behavior.
Definition Rules.h:40
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
std::uint64_t mantissa() const noexcept
Definition STAmount.h:490
bool negative() const noexcept
Definition STAmount.h:484
bool integral() const noexcept
Definition STAmount.h:465
Asset const & asset() const
Definition STAmount.h:496
int exponent() const noexcept
Definition STAmount.h:459
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
TER validDomain(ReadView const &view, UInt256 domainID, AccountID const &subject)
int posteriorAssetScale(VaultVersion version, Asset const &asset, int baseScale, Number const &reference, Number const &delta)
Shared core of getPosteriorVaultScale and getPosteriorBrokerCoverScale: the exponent reference + delt...
int liveScale(Number const &reference, Asset const &asset, int baseScale)
Shared grid-floor core of getVaultScale / getPosteriorVaultScale / getPosteriorBrokerCoverScale: base...
STAmount creditToPosteriorScale(Asset const &asset, Number const &reference, int baseScale, Number const &raw, Number::RoundingMode roundingMode)
Shared core of creditToPosteriorAvailableScale and creditToPosteriorBrokerCoverScale: floors referenc...
int getPosteriorVaultScale(SLE::ConstRef vault, STAmount const &delta)
Return the Vault's posterior live exponent after applying an unrounded delta.
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:565
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
VaultPhase
Lifecycle phase of a vault.
Definition Protocol.h:367
std::optional< STAmount > sharesToAssetsWithdraw(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &shares, WaiveUnrealizedLoss waive=WaiveUnrealizedLoss::No)
From the perspective of a vault, return the number of assets to give the depositor when they redeem a...
bool isSoleShareholder(ReadView const &view, AccountID const &account, SLE::ConstRef issuance)
Returns true iff account holds all of the vault's outstanding shares, i.e.
Number vaultOpenZoneCapacity(SLE::ConstRef vault, Number const &roundedAmount)
Open-zone capacity after adding roundedAmount: AssetsTotal + YieldUnrealized.
std::expected< STAmount, TER > clampVaultOutflow(SLE::ConstRef vault, STAmount const &delta)
Outflow clamp dispatcher for VaultWithdraw and VaultClawback: rounds a negative delta to the scale ap...
static auto sum(TCollection const &col)
bool isOnVaultBaseGrid(Asset const &asset, Number const &value, int baseScale)
Returns true iff value is exactly representable both as an STAmount of asset and on the base grid at ...
TER checkVaultDomain(ReadView const &view, SLE::ConstRef issuance, AccountID const &subject, SuppressExpired suppressExpired)
Checks that subject belongs to the permissioned domain governing a vault's shares.
std::optional< STAmount > assetsToSharesWithdraw(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &assets, TruncateShares truncate=TruncateShares::No, WaiveUnrealizedLoss waive=WaiveUnrealizedLoss::No)
From the perspective of a vault, return the number of shares to demand from the depositor when they a...
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:52
bool isValidClosedEndedGap(std::uint32_t sub, std::uint32_t red)
Returns true iff the (SubscriptionDate, RedemptionDate) gap of a closed-ended vault satisfies kMinInv...
std::optional< STAmount > sharesToAssetsDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &shares)
From the perspective of a vault, return the number of assets to take from depositor when they receive...
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
@ tefBAD_LEDGER
Definition TER.h:164
@ tefINTERNAL
Definition TER.h:167
Number assetsTotalForWithdrawal(SLE::ConstRef vault, WaiveUnrealizedLoss waive)
Returns the assets backing outstanding shares for a withdrawal: sfAssetsTotal minus sfLossUnrealized,...
constexpr std::uint32_t kMaxInvestmentPeriod
Definition Protocol.h:393
int getVaultScale(SLE::ConstRef vault)
Return the Vault's current live exponent.
std::expected< STAmount, TER > clampToAssetsTotalScale(SLE::ConstRef vault, STAmount const &delta)
Adjusts a requested asset change (delta) to match the decimal scale of the updated total vault assets...
TER checkAssetsMaximum(SLE::ConstRef vault, Number const &amount)
Checks that a requested AssetsMaximum is exactly representable on the Vault's base grid,...
VaultKind
Vault kind.
Definition Protocol.h:358
TER adjustVaultCash(SLE::Ref vault, STAmount const &delta, beast::Journal j)
Apply a signed cash movement to a Vault of any version.
VaultVersion getVaultDefaultVersion(Rules const &rules)
Resolves which LEVersion a newly-created Vault should get under the currently active amendments.
TruncateShares
Controls whether to truncate shares instead of rounding.
STAmount roundToScale(STAmount const &value, std::int32_t scale, Number::RoundingMode rounding=Number::getround())
Round an arbitrary precision Amount to the precision of an STAmount that has a given exponent.
TER adjustVaultBalances(SLE::Ref vault, VaultBalanceChange const &change, beast::Journal j)
Apply a balance change to a FixedPrecision Vault.
VaultVersion
Vault ledger-entry schema versions, persisted as sfLEVersion.
Definition Protocol.h:342
TER checkDebitNotDust(SLE::ConstRef vault, Number const &amount, beast::Journal j, std::string_view name)
Reject a cash outflow that is dust (see debitIsNonZeroDust) or whose check overflows Number,...
std::optional< STAmount > assetsToSharesDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &assets)
From the perspective of a vault, return the number of shares to give depositor when they offer a fixe...
STAmount roundToPosteriorVaultScale(SLE::ConstRef vault, STAmount const &amount, Number::RoundingMode roundingMode)
Round an amount at the Vault's posterior live exponent.
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
int getVaultBaseScale(SLE::ConstRef vault)
Return the Vault's base exponent.
TER checkOptionalVaultInflow(SLE::ConstRef vault, STAmount const &amount)
Check whether amount is an admissible optional inflow.
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
constexpr Number abs(Number x) noexcept
Definition Number.h:880
VaultKind getVaultKind(SLE::ConstRef vault)
Resolves the VaultKind of a vault SLE.
bool isRepresentable(Asset const &asset, Number const &value)
Check whether an arbitrary precision Number can be converted to an STAmount of a given Asset without ...
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
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
Number getVaultOpenLimit(SLE::ConstRef vault)
Open-zone capacity ceiling: 9 * 10^(15 + baseScale).
TERSubset< CanCvtToTER > TER
Definition TER.h:657
int vaultBaseScale(Asset const &asset, std::uint8_t scale)
Returns the Vault's base exponent for asset at scale, before a Vault object exists to read it from: 0...
@ tecPATH_DRY
Definition TER.h:305
@ tecNO_AUTH
Definition TER.h:311
@ tecEXPIRED
Definition TER.h:325
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecLIMIT_EXCEEDED
Definition TER.h:372
Number getAssetsTotal(SLE::ConstRef vault)
Return the Vault's current assets total.
SuppressExpired
Controls whether checkVaultDomain reports an expired credential as an error.
bool isValidVaultKind(STTx const &tx)
Returns true iff sfVaultKind is either absent from tx or is present and equal to a recognised VaultKi...
VaultVersion getVaultVersion(SLE::ConstRef vault)
Resolves a Vault's LEVersion.
constexpr std::uint32_t kMinInvestmentPeriod
Bounds on the length of a closed-ended vault's Investment phase (RedemptionDate - SubscriptionDate).
Definition Protocol.h:391
STAmount creditToPosteriorAvailableScale(SLE::ConstRef vault, Number const &raw, Number::RoundingMode roundingMode)
Round a FixedPrecision cash inflow (LoanPay's credit, LoanManage's default cover credit) into AssetsA...
VaultVersion decodeVaultVersion(std::optional< std::uint8_t > leVersion)
Decodes an already-extracted sfLEVersion value with the same range check as getVaultVersion.
@ tesSUCCESS
Definition TER.h:253
WaiveUnrealizedLoss
Controls whether the withdraw conversion helpers (assetsToSharesWithdraw and sharesToAssetsWithdraw) ...
A change to a FixedPrecision Vault's balances.
Number loss
Signed change to impaired principal (LossUnrealized), exact.
std::optional< STAmount > cash
Signed change to AssetsAvailable.
Number yield
Signed change to scheduled, unpaid interest (YieldUnrealized), exact.
Number deployed
Signed change to AssetsDeployed: open Loan principal, exact.
T unexpected(T... args)