1#include <xrpl/ledger/helpers/VaultHelpers.h>
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>
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>
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/protocol/TER.h>
39 XRPL_ASSERT(vault &&
vault->getType() == ltVAULT,
"xrpl::fixedBaseScale : valid Vault sle");
72[[nodiscard]] std::expected<STAmount, TER>
76 delta.asset() ==
vault->at(sfAsset),
77 "xrpl::clampToAvailableScale : delta and vault asset match");
80 "xrpl::clampToAvailableScale : FixedPrecision Vault");
81 XRPL_ASSERT(delta.negative(),
"xrpl::clampToAvailableScale : outflow delta is negative");
90 posteriorScale(vault,
vault->at(sfAssetsAvailable), delta),
95 abs(actualDelta) <=
abs(delta),
96 "xrpl::clampToAvailableScale : actual delta smaller or equal to calculated delta");
107decodeVaultKind(std::optional<std::uint8_t> vaultKind)
124 XRPL_ASSERT(vault &&
vault->getType() == ltVAULT,
"xrpl::syncAssetsTotal : valid Vault sle");
133 "xrpl::syncAssetsTotal : AssetsAvailable is a 16-digit STAmount value");
146 ?
vault->at(sfAssetsAvailable)
148 auto const asset =
vault->at(sfAsset);
178 Number const posterior = reference + delta;
184 return scale(posterior, asset);
186 return liveScale(posterior, asset, baseScale);
189 UNREACHABLE(
"xrpl::detail::posteriorAssetScale : valid VaultVersion");
219 STAmount const credit{asset, flooredSum - reference};
223 "xrpl::detail::creditToPosteriorScale",
224 "credit is between zero and raw");
232 vault && vault->getType() == ltVAULT,
233 "xrpl::detail::getPosteriorVaultScale : valid Vault sle");
235 delta.
asset() == vault->at(sfAsset),
236 "xrpl::detail::getPosteriorVaultScale : delta and Vault asset match");
245 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getAssetsTotal : valid Vault sle");
248 return vault->at(sfAssetsTotal);
254 return vault->at(sfAssetsAvailable) + vault->at(sfAssetsDeployed);
261 vault && vault->getType() == ltVAULT,
"xrpl::adjustVaultBalances : valid Vault sle");
264 "xrpl::adjustVaultBalances : FixedPrecision Vault");
265 Asset const asset = vault->at(sfAsset);
267 XRPL_ASSERT(cash.asset() == asset,
"xrpl::adjustVaultBalances : cash and Vault asset match");
273 "xrpl::adjustVaultBalances : ambient rounding mode is ToNearest");
285 Number const lossUnrealizedAfter =
Number(vault->at(sfLossUnrealized)) + change.
loss;
290 Number const yieldUnrealizedAfter =
Number(vault->at(sfYieldUnrealized)) + change.
yield;
296 JLOG(j.
fatal()) <<
"adjustVaultBalances: a balance would become negative."
297 <<
" AssetsAvailable: " <<
Number(availableAfter)
298 <<
", AssetsDeployed: " << assetsDeployedAfter
299 <<
", LossUnrealized: " << lossUnrealizedAfter
300 <<
", YieldUnrealized: " << yieldUnrealizedAfter;
307 if (lossUnrealizedAfter > assetsDeployedAfter)
313 (
STAmount{asset, assetsDeployedAfter} == assetsDeployedAfter),
314 "xrpl::adjustVaultBalances : AssetsDeployed is a 16-digit STAmount value");
316 (
STAmount{asset, lossUnrealizedAfter} == lossUnrealizedAfter),
317 "xrpl::adjustVaultBalances : LossUnrealized is a 16-digit STAmount value");
319 (
STAmount{asset, yieldUnrealizedAfter} == yieldUnrealizedAfter),
320 "xrpl::adjustVaultBalances : YieldUnrealized is a 16-digit STAmount value");
322 vault->at(sfAssetsAvailable) = availableAfter;
323 vault->at(sfAssetsDeployed) = assetsDeployedAfter;
324 vault->at(sfLossUnrealized) = lossUnrealizedAfter;
325 vault->at(sfYieldUnrealized) = yieldUnrealizedAfter;
326 syncAssetsTotal(vault);
337 vault->at(sfAssetsTotal) += delta;
338 vault->at(sfAssetsAvailable) += delta;
345 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultScale : valid Vault sle");
352 return scale(assetsTotal, vault->at(sfAsset));
354 return detail::liveScale(assetsTotal, vault->at(sfAsset), fixedBaseScale(vault));
357 UNREACHABLE(
"xrpl::getVaultScale : valid VaultVersion");
365 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultBaseScale : valid Vault sle");
373 return fixedBaseScale(vault);
376 UNREACHABLE(
"xrpl::getVaultBaseScale : valid VaultVersion");
381[[nodiscard]] STAmount
388 vault && vault->getType() == ltVAULT,
"xrpl::roundToPosteriorVaultScale : valid Vault sle");
390 amount.
asset() == vault->at(sfAsset),
391 "xrpl::roundToPosteriorVaultScale : amount and Vault asset match");
397[[nodiscard]] STAmount
404 vault && vault->getType() == ltVAULT,
405 "xrpl::creditToPosteriorAvailableScale : valid Vault sle");
406 Asset const asset = vault->at(sfAsset);
413 Number const reference = vault->at(sfAssetsAvailable);
415 asset, reference, fixedBaseScale(vault), raw, roundingMode);
421 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultOpenLimit : valid Vault sle");
424 "xrpl::getVaultOpenLimit : FixedPrecision Vault");
432 vault && vault->getType() == ltVAULT,
"xrpl::checkOptionalVaultInflow : valid Vault sle");
434 amount.
asset() == vault->at(sfAsset),
435 "xrpl::checkOptionalVaultInflow : amount and Vault asset match");
436 XRPL_ASSERT(!amount.
negative(),
"xrpl::checkOptionalVaultInflow : non-negative amount");
460 vault && vault->getType() == ltVAULT,
"xrpl::vaultOpenZoneCapacity : valid Vault sle");
463 "xrpl::vaultOpenZoneCapacity : FixedPrecision Vault");
465 return getAssetsTotal(vault) + vault->at(sfYieldUnrealized) + roundedAmount;
477 if (debitIsNonZeroDust(vault, amount))
479 JLOG(j.
debug()) << name <<
": amount too small to change stored vault balance";
489 << name <<
": overflow error with"
490 <<
" scale=" << (int)vault->at(sfScale)
491 <<
", assetsTotal=" << vault->at(sfAssetsTotal) <<
", amount=" << amount;
501 XRPL_ASSERT(!assets.
negative(),
"xrpl::assetsToSharesDeposit : non-negative assets");
503 assets.
asset() == vault->at(sfAsset),
504 "xrpl::assetsToSharesDeposit : assets and vault match");
505 if (assets.
negative() || assets.
asset() != vault->at(sfAsset))
509 STAmount shares{vault->at(sfShareMPTID)};
517 Number const shareTotal = issuance->at(sfOutstandingAmount);
518 shares = ((shareTotal * assets) / assetTotal).truncate();
525 XRPL_ASSERT(!shares.
negative(),
"xrpl::sharesToAssetsDeposit : non-negative shares");
527 shares.
asset() == vault->at(sfShareMPTID),
528 "xrpl::sharesToAssetsDeposit : shares and vault match");
529 if (shares.
negative() || shares.
asset() != vault->at(sfShareMPTID))
533 STAmount assets{vault->at(sfAsset)};
540 Number const shareTotal = issuance->at(sfOutstandingAmount);
541 assets = (assetTotal * shares) / shareTotal;
545[[nodiscard]] std::expected<STAmount, TER>
549 delta.
asset() == vault->at(sfAsset),
550 "xrpl::clampToAssetsTotalScale : delta and vault asset match");
552 Asset const asset = vault->at(sfAsset);
567 !delta.
negative(),
"xrpl::clampToAssetsTotalScale : FixedPrecision credit only");
570 actualDelta = rounded.
negative() ? -rounded : rounded;
578 int const postScale = [&] {
580 return scale(assetsTotal + delta, asset);
596 Number const posterior = [&] {
598 return assetsTotal + magnitude;
601 Number const roundedPosterior =
603 actualDelta =
STAmount{asset, roundedPosterior - assetsTotal};
608 abs(actualDelta) <=
abs(delta),
609 "xrpl::clampToAssetsTotalScale : actual delta smaller or equal to calculated delta");
619[[nodiscard]] std::expected<STAmount, TER>
622 XRPL_ASSERT(delta.
negative(),
"xrpl::clampVaultOutflow : outflow delta is negative");
624 ? clampToAvailableScale(vault, delta)
633 return -
static_cast<int>(
scale);
658 assetTotal -= vault->at(sfLossUnrealized);
670 XRPL_ASSERT(!assets.
negative(),
"xrpl::assetsToSharesWithdraw : non-negative assets");
672 assets.
asset() == vault->at(sfAsset),
673 "xrpl::assetsToSharesWithdraw : assets and vault match");
674 if (assets.
negative() || assets.
asset() != vault->at(sfAsset))
678 STAmount shares{vault->at(sfShareMPTID)};
681 Number const shareTotal = issuance->at(sfOutstandingAmount);
682 Number result = (shareTotal * assets) / assetTotal;
696 XRPL_ASSERT(!shares.
negative(),
"xrpl::sharesToAssetsWithdraw : non-negative shares");
698 shares.
asset() == vault->at(sfShareMPTID),
699 "xrpl::sharesToAssetsWithdraw : shares and vault match");
700 if (shares.
negative() || shares.
asset() != vault->at(sfShareMPTID))
704 STAmount assets{vault->at(sfAsset)};
707 Number const shareTotal = issuance->at(sfOutstandingAmount);
708 assets = (assetTotal * shares) / shareTotal;
716 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
717 "xrpl::isSoleShareholder : valid issuance SLE");
719 std::uint64_t const outstanding = issuance->at(sfOutstandingAmount);
720 if (outstanding == 0)
723 auto const shareMPTID =
724 makeMptID(issuance->getFieldU32(sfSequence), issuance->getAccountID(sfIssuer));
729 return sleToken->getFieldU64(sfMPTAmount) == outstanding;
740 UNREACHABLE(
"xrpl::decodeVaultVersion : invalid vault version");
750 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultVersion : valid Vault sle");
760 if (rules.
enabled(featureLendingProtocolV1_1) && rules.
enabled(featureLendingProtocolV1_2) &&
761 rules.
enabled(fixCleanup3_4_0))
763 if (rules.
enabled(featureLendingProtocolV1_1))
771 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultKind : valid Vault sle");
772 return decodeVaultKind(vault->at(~sfVaultKind));
778 return decodeVaultKind(tx[~sfVaultKind]);
784 auto const kindField = tx[~sfVaultKind];
802 XRPL_ASSERT(vault && vault->getType() == ltVAULT,
"xrpl::getVaultPhase : valid Vault sle");
804 view, (*vault)[~sfVaultKind], (*vault)[~sfSubscriptionDate], (*vault)[~sfRedemptionDate]);
834 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
835 "xrpl::checkVaultDomain : valid issuance SLE");
837 auto const maybeDomainID = issuance->at(~sfDomainID);
A generic endpoint for log messages.
Number is a floating point type that can represent a wide range of values.
Number truncate() const noexcept
static constexpr int kMinExponent
static RoundingMode getround()
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
Rules controlling protocol behavior.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
std::uint64_t mantissa() const noexcept
bool negative() const noexcept
bool integral() const noexcept
Asset const & asset() const
int exponent() const noexcept
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
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
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
VaultPhase
Lifecycle phase of a vault.
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.
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.
Number assetsTotalForWithdrawal(SLE::ConstRef vault, WaiveUnrealizedLoss waive)
Returns the assets backing outstanding shares for a withdrawal: sfAssetsTotal minus sfLossUnrealized,...
constexpr std::uint32_t kMaxInvestmentPeriod
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,...
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.
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)
constexpr Number abs(Number x) noexcept
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.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Number getVaultOpenLimit(SLE::ConstRef vault)
Open-zone capacity ceiling: 9 * 10^(15 + baseScale).
TERSubset< CanCvtToTER > TER
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...
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).
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.
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.