Skip to content
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 54 additions & 4 deletions include/xrpl/ledger/helpers/VaultHelpers.h
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,29 @@ checkOptionalVaultInflow(SLE::ConstRef vault, STAmount const& amount);
[[nodiscard]] Number
vaultOpenZoneCapacity(SLE::ConstRef vault, Number const& roundedAmount);

/**
* How the share<->asset conversions below round their result.
*
* Legacy: compute the exchange in Number arithmetic and quantize the result
* to nearest (share counts are then truncated where documented). This is the
* pre-fixCleanup3_6_0 behavior.
*
* FavorVault: for vaults holding an integral asset (XRP or MPT), compute
* a * b / c exactly in 128-bit integer arithmetic and round the quotient in
* the vault's favor, so no single depositor or withdrawer can dilute the other
* shareholders:
* - share counts (minted on deposit, burned on withdraw) round down;
* - the assets charged for minted shares round up;
* - the assets paid for burned shares round down.
* Number keeps only 19 significant digits, so rounding each Number step in a
* fixed direction can move an otherwise exact result by a whole unit once the
* totals are large; the integer path avoids that. IOU conversions are left on
* the Legacy arithmetic: an IOU result cannot be represented exactly anyway,
* and the callers' scale clamps (clampToAssetsTotalScale, clampVaultOutflow)
* already round the IOU amount in the vault's favor.
*/
enum class VaultRounding : bool { Legacy = false, FavorVault = true };

/**
* From the perspective of a vault, return the number of shares to give
* depositor when they offer a fixed amount of assets. Note, since shares are
Expand All @@ -255,25 +278,41 @@ vaultOpenZoneCapacity(SLE::ConstRef vault, Number const& roundedAmount);
* @param vault The vault SLE.
* @param issuance The MPTokenIssuance SLE for the vault's shares.
* @param assets The amount of assets to convert.
* @param rounding FavorVault computes the truncated share count exactly for
* integral assets; see VaultRounding.
*
* @return The number of shares, or nullopt on error.
*/
[[nodiscard]] std::optional<STAmount>
assetsToSharesDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const& assets);
assetsToSharesDeposit(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& assets,
VaultRounding rounding = VaultRounding::Legacy);

/**
* From the perspective of a vault, return the number of assets to take from
* depositor when they receive a fixed amount of shares. Note, since shares are
* MPT, they are always an integral number.
*
* With FavorVault and an integral asset the charge is the exact fair value of
* the shares rounded up, so the depositor pays at least what the shares are
* worth and existing shareholders cannot be diluted. Legacy rounds to nearest,
* which can undercharge by up to half a unit.
*
* @param vault The vault SLE.
* @param issuance The MPTokenIssuance SLE for the vault's shares.
* @param shares The amount of shares to convert.
* @param rounding How to round the resulting assets; see VaultRounding.
*
* @return The number of assets, or nullopt on error.
*/
[[nodiscard]] std::optional<STAmount>
sharesToAssetsDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const& shares);
sharesToAssetsDeposit(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& shares,
VaultRounding rounding = VaultRounding::Legacy);

/**
* Adjusts a requested asset change (delta) to match the decimal scale of the
Expand Down Expand Up @@ -421,6 +460,9 @@ checkDebitNotDust(
* @param truncate Whether to truncate instead of rounding.
* @param waive Whether to waive the unrealized-loss discount when computing
* the exchange rate.
* @param rounding FavorVault computes a truncated share count exactly for
* integral assets; see VaultRounding. It has no effect unless
* truncate is Yes.
*
* @return The number of shares, or nullopt on error.
*/
Expand All @@ -430,18 +472,25 @@ assetsToSharesWithdraw(
SLE::ConstRef issuance,
STAmount const& assets,
TruncateShares truncate = TruncateShares::No,
WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No);
WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No,
VaultRounding rounding = VaultRounding::Legacy);

/**
* From the perspective of a vault, return the number of assets to give the
* depositor when they redeem a fixed amount of shares. Note, since shares are
* MPT, they are always an integral number.
*
* With FavorVault and an integral asset the payout is the exact fair value of
* the shares rounded down, so the shareholder receives at most what the shares
* are worth and the remaining shareholders cannot be diluted. Legacy rounds to
* nearest, which can overpay by up to half a unit.
*
* @param vault The vault SLE.
* @param issuance The MPTokenIssuance SLE for the vault's shares.
* @param shares The amount of shares to convert.
* @param waive Whether to waive (i.e. not subtract) the vault's unrealized
* loss when computing the exchange rate.
* @param rounding How to round the resulting assets; see VaultRounding.
*
* @return The number of assets, or nullopt on error.
*/
Expand All @@ -450,7 +499,8 @@ sharesToAssetsWithdraw(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& shares,
WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No);
WaiveUnrealizedLoss waive = WaiveUnrealizedLoss::No,
VaultRounding rounding = VaultRounding::Legacy);

/**
* Returns true iff account holds all of the vault's outstanding shares,
Expand Down
89 changes: 85 additions & 4 deletions src/libxrpl/ledger/helpers/VaultHelpers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,12 @@
#include <xrpl/protocol/STTx.h>
#include <xrpl/protocol/TER.h>

#include <boost/multiprecision/cpp_int.hpp>

#include <algorithm>
#include <cstdint>
#include <expected>
#include <limits>
#include <optional>
#include <stdexcept>
#include <string_view>
Expand Down Expand Up @@ -148,6 +151,60 @@ debitIsNonZeroDust(SLE::ConstRef vault, Number const& amount)
auto const asset = vault->at(sfAsset);
return STAmount{asset, total - amount} == STAmount{asset, total};
}

enum class RoundUp : bool { No = false, Yes = true };

// Returns n as an exact non-negative integer, or nullopt if n is negative or
// has a fractional part.
std::optional<std::uint64_t>
toExactUInt(Number const& n)
{
if (n.signum() < 0 || n.truncate() != n)
return std::nullopt;
return static_cast<std::uint64_t>(static_cast<std::int64_t>(n));
}

// Converts with VaultRounding::FavorVault for a vault holding an integral
// asset: returns a * b / c in units of `to`, rounded up or down.
//
// Every total and amount of an integral asset is an integer, so the quotient
// is computed exactly in 128 bits and rounded once. Number keeps only 19
// digits, and a directed rounding mode applies to every Number step, so with
// large totals the Number path can land a whole unit away from the exact
// result: 1'000'000'000'000'007 * 123'456'789 / 1'000'000'000'000'007 is
// exactly 123'456'789, but rounding every Number step up gives 123'456'790.
//
// Throws std::overflow_error if c is zero or the quotient does not fit in an
// int64, as the Number path does; callers already handle that.
STAmount
favorVaultMulDiv(Asset const& to, Number const& a, Number const& b, Number const& c, RoundUp up)
Comment thread
muhammadsalah marked this conversation as resolved.
Resolved
{
auto const ua = toExactUInt(a);
auto const ub = toExactUInt(b);
auto const uc = toExactUInt(c);
if (!ua || !ub || !uc)
{
// LCOV_EXCL_START
UNREACHABLE("xrpl::favorVaultMulDiv : integral operands");
// Still round in the vault's favor; the result is quantized to `to`
// while the guard is active.
NumberRoundModeGuard const rg(
up == RoundUp::Yes ? Number::RoundingMode::Upward : Number::RoundingMode::Downward);
return STAmount{to, (a * b) / c};
// LCOV_EXCL_STOP
}

using boost::multiprecision::uint128_t;
if (*uc == 0)
throw std::overflow_error("xrpl::favorVaultMulDiv : divide by zero");
uint128_t const num = uint128_t{*ua} * *ub;
uint128_t quotient = num / *uc;
if (up == RoundUp::Yes && quotient * *uc != num)
++quotient;
if (quotient > std::numeric_limits<std::int64_t>::max())
throw std::overflow_error("xrpl::favorVaultMulDiv : overflow");
return STAmount{to, Number{static_cast<std::int64_t>(quotient)}};
}
} // namespace

namespace detail {
Expand Down Expand Up @@ -496,7 +553,11 @@ checkDebitNotDust(
}

[[nodiscard]] std::optional<STAmount>
assetsToSharesDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const& assets)
assetsToSharesDeposit(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& assets,
VaultRounding const rounding)
{
Comment thread
muhammadsalah marked this conversation as resolved.
Resolved
XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesDeposit : non-negative assets");
XRPL_ASSERT(
Expand All @@ -515,12 +576,18 @@ assetsToSharesDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount cons
}

Number const shareTotal = issuance->at(sfOutstandingAmount);
if (rounding == VaultRounding::FavorVault && assets.integral())
return favorVaultMulDiv(shares.asset(), shareTotal, assets, assetTotal, RoundUp::No);
shares = ((shareTotal * assets) / assetTotal).truncate();
return shares;
}

[[nodiscard]] std::optional<STAmount>
sharesToAssetsDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const& shares)
sharesToAssetsDeposit(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& shares,
VaultRounding const rounding)
{
XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsDeposit : non-negative shares");
XRPL_ASSERT(
Expand All @@ -538,6 +605,10 @@ sharesToAssetsDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount cons
}

Number const shareTotal = issuance->at(sfOutstandingAmount);
// Charging a depositor rounds up so they pay at least the fair value of
// the minted shares.
if (rounding == VaultRounding::FavorVault && assets.integral())
return favorVaultMulDiv(assets.asset(), assetTotal, shares, shareTotal, RoundUp::Yes);
assets = (assetTotal * shares) / shareTotal;
return assets;
}
Expand Down Expand Up @@ -665,7 +736,8 @@ assetsToSharesWithdraw(
SLE::ConstRef issuance,
STAmount const& assets,
TruncateShares truncate,
WaiveUnrealizedLoss waive)
WaiveUnrealizedLoss waive,
VaultRounding const rounding)
{
XRPL_ASSERT(!assets.negative(), "xrpl::assetsToSharesWithdraw : non-negative assets");
XRPL_ASSERT(
Expand All @@ -679,6 +751,9 @@ assetsToSharesWithdraw(
if (assetTotal == 0)
return shares;
Number const shareTotal = issuance->at(sfOutstandingAmount);
if (truncate == TruncateShares::Yes && rounding == VaultRounding::FavorVault &&
assets.integral())
return favorVaultMulDiv(shares.asset(), shareTotal, assets, assetTotal, RoundUp::No);
Number result = (shareTotal * assets) / assetTotal;
if (truncate == TruncateShares::Yes)
result = result.truncate();
Expand All @@ -691,7 +766,8 @@ sharesToAssetsWithdraw(
SLE::ConstRef vault,
SLE::ConstRef issuance,
STAmount const& shares,
WaiveUnrealizedLoss waive)
WaiveUnrealizedLoss waive,
VaultRounding const rounding)
{
XRPL_ASSERT(!shares.negative(), "xrpl::sharesToAssetsWithdraw : non-negative shares");
XRPL_ASSERT(
Expand All @@ -705,6 +781,11 @@ sharesToAssetsWithdraw(
if (assetTotal == 0)
return assets;
Number const shareTotal = issuance->at(sfOutstandingAmount);
// Paying a withdrawing shareholder rounds down so they receive at most the
// fair value of the shares they burn; otherwise the assets-per-share price
// would drop and dilute the remaining shareholders.
if (rounding == VaultRounding::FavorVault && assets.integral())
return favorVaultMulDiv(assets.asset(), assetTotal, shares, shareTotal, RoundUp::No);
assets = (assetTotal * shares) / shareTotal;
return assets;
}
Expand Down
33 changes: 26 additions & 7 deletions src/libxrpl/tx/transactors/vault/VaultClawback.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,11 @@ VaultClawback::assetsToClawback(
STAmount const& clawbackAmount)
{
bool const fix340Enabled = ctx_.view().rules().enabled(fixCleanup3_4_0);
bool const fix360Enabled = ctx_.view().rules().enabled(fixCleanup3_6_0);
// Post-fixCleanup3_6_0: the holder losing shares receives nothing, but the recovery must still
// not exceed the fair value of the shares burned, or the remaining shareholders cover the
// difference. Round the same way as VaultWithdraw.
auto const rounding = fix360Enabled ? VaultRounding::FavorVault : VaultRounding::Legacy;
Comment thread
muhammadsalah marked this conversation as resolved.
Resolved
if (clawbackAmount.asset() != vault->at(sfAsset))
{
// preclaim should have blocked this , now it's an internal error
Expand Down Expand Up @@ -305,7 +310,7 @@ VaultClawback::assetsToClawback(
AuthHandling::IgnoreAuth,
j_);
auto const maybeAssets = sharesToAssetsWithdraw(
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss);
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss, rounding);
if (!maybeAssets)
return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE

Expand All @@ -316,16 +321,17 @@ VaultClawback::assetsToClawback(
// Pre-fixCleanup3_4_0: shares were rounded to nearest, so the round-trip back to assets
// could exceed clawbackAmount.
// Post-fixCleanup3_4_0: truncate shares so assetsRecovered <= clawbackAmount by
// construction.
auto const truncate = fix340Enabled ? TruncateShares::Yes : TruncateShares::No;
// construction. Post-fixCleanup3_6_0 does too, independently of fixCleanup3_4_0.
auto const truncate =
fix340Enabled || fix360Enabled ? TruncateShares::Yes : TruncateShares::No;
auto const maybeShares = assetsToSharesWithdraw(
vault, sleShareIssuance, clawbackAmount, truncate, waiveUnrealizedLoss);
vault, sleShareIssuance, clawbackAmount, truncate, waiveUnrealizedLoss, rounding);
if (!maybeShares)
return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;

auto const maybeAssets = sharesToAssetsWithdraw(
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss);
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss, rounding);
if (!maybeAssets)
return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
Expand All @@ -340,14 +346,15 @@ VaultClawback::assetsToClawback(
sleShareIssuance,
assetsRecovered,
TruncateShares::Yes,
waiveUnrealizedLoss);
waiveUnrealizedLoss,
rounding);
if (!maybeShares)
return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE
sharesDestroyed = *maybeShares;
}

auto const maybeAssets = sharesToAssetsWithdraw(
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss);
vault, sleShareIssuance, sharesDestroyed, waiveUnrealizedLoss, rounding);
if (!maybeAssets)
return std::unexpected(tecINTERNAL); // LCOV_EXCL_LINE
assetsRecovered = *maybeAssets;
Expand Down Expand Up @@ -456,6 +463,18 @@ VaultClawback::doApply()
if (sharesDestroyed == beast::kZero)
return tecPRECISION_LOSS;

// Post-fixCleanup3_6_0: when a share is worth less than one unit of an integral asset, the
// rounded-down recovery can be zero. Burning shares without debiting a non-empty vault would
// fail the clawback invariant, so refuse instead, as VaultWithdraw does.
if (view().rules().enabled(fixCleanup3_6_0) && amount.asset() == vaultAsset &&
assetsRecovered == beast::kZero &&
(getAssetsTotal(vault) != beast::kZero ||
Number(vault->at(sfAssetsAvailable)) != beast::kZero))
{
JLOG(j_.debug()) << "VaultClawback: clawback rounds to zero assets";
return tecPRECISION_LOSS;
}

// Number arithmetic can throw overflow_error when Scale and totals are large.
if (view().rules().enabled(fixCleanup3_4_0))
{
Expand Down
15 changes: 13 additions & 2 deletions src/libxrpl/tx/transactors/vault/VaultDeposit.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,10 @@ VaultDeposit::doApply()
{
bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0);
bool const fix340Enabled = view().rules().enabled(fixCleanup3_4_0);
// Post-fixCleanup3_6_0: convert in the vault's favor so the depositor can never be charged
// less than the fair value of the shares they receive; see VaultRounding.
auto const rounding =
view().rules().enabled(fixCleanup3_6_0) ? VaultRounding::FavorVault : VaultRounding::Legacy;
auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
auto const applyViewContext = ctx_.getApplyViewContext();
if (!vault)
Expand Down Expand Up @@ -298,7 +302,7 @@ VaultDeposit::doApply()
{
// Compute exchange before transferring any amounts.
{
auto const maybeShares = assetsToSharesDeposit(vault, sleIssuance, amount);
auto const maybeShares = assetsToSharesDeposit(vault, sleIssuance, amount, rounding);
if (!maybeShares)
return tecINTERNAL; // LCOV_EXCL_LINE
sharesCreated = *maybeShares;
Expand All @@ -310,7 +314,14 @@ VaultDeposit::doApply()
// Convert shares back to assets so the depositor is debited for the amount actually minted.
// The truncated share count is worth <= amount; without this the difference would be
// credited to the vault for free.
auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated);
//
// Post-fixCleanup3_6_0, for XRP and MPT: the charge is the exact fair value of the minted
// shares, rounded up. Round-to-nearest could round it below that value, handing the
// depositor shares worth more than they paid and diluting the existing shareholders.
// Since the share count was floored from `amount` exactly, the ceiling never exceeds
// `amount`. IOU charges are unchanged; the fixCleanup3_4_0 clamp below handles them
// (clampToAssetsTotalScale returns integral amounts unchanged).
auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated, rounding);
if (!maybeAssets)
{
return tecINTERNAL; // LCOV_EXCL_LINE
Expand Down
Loading
Loading