1#include <xrpl/tx/transactors/vault/VaultWithdraw.h>
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.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/AccountRootHelpers.h>
11#include <xrpl/ledger/helpers/CredentialHelpers.h>
12#include <xrpl/ledger/helpers/TokenHelpers.h>
13#include <xrpl/ledger/helpers/VaultHelpers.h>
14#include <xrpl/protocol/AccountID.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/Indexes.h>
17#include <xrpl/protocol/LedgerFormats.h>
18#include <xrpl/protocol/MPTIssue.h>
19#include <xrpl/protocol/Protocol.h>
20#include <xrpl/protocol/SField.h>
21#include <xrpl/protocol/STLedgerEntry.h>
22#include <xrpl/protocol/STNumber.h>
23#include <xrpl/protocol/STTakesAsset.h>
24#include <xrpl/protocol/STTx.h>
25#include <xrpl/protocol/TER.h>
26#include <xrpl/protocol/XRPAmount.h>
27#include <xrpl/tx/Transactor.h>
44 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
45 "xrpl::shouldWaiveWithdrawal : valid issuance sle");
57 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: zero/empty vault ID.";
64 if (
auto const destination = ctx.
tx[~sfDestination])
95 <<
"VaultWithdraw: vault withdrawal is not allowed in the investment phase.";
100 auto const amount = ctx.
tx[sfAmount];
101 auto const vaultAsset = vault->at(sfAsset);
102 auto const vaultShare = vault->at(sfShareMPTID);
103 if (amount.asset() != vaultAsset && amount.asset() != vaultShare)
106 auto const& vaultAccount = vault->at(sfAccount);
107 auto const& account = ctx.
tx[sfAccount];
108 auto const& dstAcct = ctx.
tx[~sfDestination].value_or(account);
114 if (
auto ter =
canTransfer(ctx.
view, vaultAsset, vaultAccount, dstAcct, waive);
117 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: vault assets are non-transferable.";
125 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: invalid withdrawal policy.";
143 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: cannot withdraw into a pseudo-account.";
147 if (fix313Enabled && amount.asset() == vaultShare)
157 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: missing issuance of vault shares.";
168 auto const maybeAssets =
179 ctx.
tx[~sfCredentialIDs]))
187 <<
"VaultWithdraw: overflow error with"
188 <<
" scale=" << (int)vault->at(sfScale)
189 <<
", assetsTotal=" << vault->at(sfAssetsTotal)
190 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
191 <<
", amount=" << amount.value();
211 if (fix340Enabled && account == dstAcct && !
holdingExists(ctx.
view, dstAcct, vaultAsset))
227 if (fix340Enabled && vault->isFlag(lsfVaultPrivate) && dstAcct != account &&
228 dstAcct != vaultAsset.getIssuer())
234 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: missing issuance of vault shares.";
282 auto applyViewContext =
ctx_.getApplyViewContext();
286 auto const mptIssuanceID = *((*vault)[sfShareMPTID]);
291 JLOG(
j_.error()) <<
"VaultWithdraw: missing issuance of vault shares.";
303 auto const amount =
ctx_.tx[sfAmount];
304 Asset const vaultAsset = vault->at(sfAsset);
306 MPTIssue const share{mptIssuanceID};
317 if (amount.asset() == vaultAsset)
329 auto const truncate =
333 vault, sleIssuance, amount, truncate, waiveUnrealizedLoss);
336 sharesRedeemed = *maybeShares;
345 auto const maybeAssets =
349 assetsWithdrawn = *maybeAssets;
351 else if (amount.asset() == share)
355 sharesRedeemed = amount;
356 auto const maybeAssets =
360 assetsWithdrawn = *maybeAssets;
372 <<
"VaultWithdraw: overflow error with"
373 <<
" scale=" << (int)vault->at(sfScale).value()
374 <<
", assetsTotal=" << vault->at(sfAssetsTotal).value()
375 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
376 <<
", amount=" << amount.value();
384 bool const isFinalWithdrawal =
385 sharesRedeemed ==
STAmount{share, sleIssuance->at(sfOutstandingAmount)};
387 auto assetsAvailable = vault->at(sfAssetsAvailable);
388 auto assetsTotal = vault->at(sfAssetsTotal);
389 auto const lossUnrealized = vault->at(sfLossUnrealized);
391 if (fix340Enabled && !isFinalWithdrawal)
396 if (amount.asset() == share && assetsWithdrawn ==
beast::kZero &&
399 JLOG(
j_.debug()) <<
"VaultWithdraw: fixed-share withdrawal rounds to zero assets";
410 JLOG(
j_.debug()) <<
"VaultWithdraw: withdrawal amount too small to change stored"
421 <<
"VaultWithdraw: overflow error with"
422 <<
" scale=" << (int)vault->at(sfScale).value()
423 <<
", assetsTotal=" << vault->at(sfAssetsTotal).value()
424 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
425 <<
", amount=" << amount.value();
443 JLOG(
j_.debug()) <<
"VaultWithdraw: account doesn't hold enough shares";
453 if (fix340Enabled && !isFinalWithdrawal && assetsWithdrawn >
beast::kZero)
460 if (*assetsAvailable < assetsWithdrawn)
462 JLOG(
j_.debug()) <<
"VaultWithdraw: vault doesn't hold enough assets";
474 return maybeClamped.error();
475 assetsWithdrawn = *maybeClamped;
483 <<
"VaultWithdraw: overflow error with"
484 <<
" scale=" << (int)vault->at(sfScale).value()
485 <<
", assetsTotal=" << vault->at(sfAssetsTotal).value()
486 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
487 <<
", amount=" << amount.value();
496 if (*assetsAvailable < assetsWithdrawn)
498 JLOG(
j_.debug()) <<
"VaultWithdraw: vault doesn't hold enough assets";
508 if (
view().rules().enabled(fixCleanup3_2_0) && isFinalWithdrawal)
517 "xrpl::VaultWithdraw::doApply : final withdrawal with non-zero unrealized loss");
520 "Cannot burn all outstanding shares while unrealized loss is non-zero";
525 STAmount const allAvailable{vaultAsset, *assetsAvailable};
526 if (assetsWithdrawn != allAvailable)
529 <<
"VaultWithdraw: final withdrawal share-value mismatch;"
530 <<
" computed=" << assetsWithdrawn.
getText()
531 <<
" assetsAvailable=" << allAvailable.
getText();
533 assetsWithdrawn = allAvailable;
543 assetsTotal -= assetsWithdrawn;
544 assetsAvailable -= assetsWithdrawn;
548 auto const& vaultAccount = vault->at(sfAccount);
566 <<
"VaultWithdraw: removed empty MPToken for vault shares"
574 <<
"VaultWithdraw: failed to remove MPToken for vault shares"
586 auto const dstAcct =
ctx_.tx[~sfDestination].value_or(
accountID_);
A generic endpoint for log messages.
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
std::string getText() const override
Asset const & asset() const
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFieldPresent(SField const &field) const
AccountID const accountID_
static bool checkExtraFeatures(PreflightContext const &ctx)
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
static TER preclaim(PreclaimContext const &ctx)
static NotTEC preflight(PreflightContext const &ctx)
NotTEC checkFields(STTx const &tx, Rules const &rules, beast::Journal j)
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
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.
bool debitIsNonZeroDust(Asset const &asset, Number const &total, Number const &amount)
Returns true if debiting amount from total (the current value of a vault's sfAssetsTotal or sfAssetsA...
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...
TER removeEmptyHolding(ApplyViewContext ctx, AccountID const &accountID, MPTIssue const &mptIssue, beast::Journal journal)
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
Number assetsTotalForWithdrawal(SLE::ConstRef vault, WaiveUnrealizedLoss waive)
Returns the assets backing outstanding shares for a withdrawal: sfAssetsTotal minus sfLossUnrealized,...
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
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 canTransfer(ReadView const &view, MPTIssue const &mptIssue, AccountID const &from, AccountID const &to, WaiveMPTCanTransfer waive=WaiveMPTCanTransfer::No, std::uint8_t depth=0)
Check whether to may receive the given MPT from from.
std::string transToken(TER code)
std::string to_string(BaseUInt< Bits, Tag > const &a)
TER doWithdraw(ApplyViewContext ctx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &amount, beast::Journal j)
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, SLE::Ref sponsorSle={}, WaiveTransferFee waiveFee=WaiveTransferFee::No, AllowMPTOverflow allowOverflow=AllowMPTOverflow::No)
Calls static accountSendIOU if saAmount represents Issue.
TER canWithdraw(ReadView const &view, AccountID const &from, AccountID const &to, SLE::ConstRef toSle, STAmount const &amount, bool hasDestinationTag, std::optional< std::vector< UInt256 > > const &credentialIDs=std::nullopt)
Checks that can withdraw funds from an object to itself or a destination.
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
static WaiveUnrealizedLoss shouldWaiveWithdrawal(ReadView const &view, AccountID const &account, SLE::ConstRef issuance)
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
bool isTesSuccess(TER x) noexcept
constexpr std::uint8_t kVaultStrategyFirstComeFirstServe
Vault withdrawal policies.
TERSubset< CanCvtToTER > TER
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
TER checkWithdrawFreeze(ReadView const &view, AccountID const &pseudoAcct, AccountID const &submitterAcct, AccountID const &dstAcct, Asset const &asset)
Checks freeze compliance for withdrawing an asset from a pseudo-account (e.g.
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
bool holdingExists(ReadView const &view, AccountID const &account, Asset const &asset)
True if the account already holds this asset (or is the issuer / XRP).
WaiveUnrealizedLoss
Controls whether the withdraw conversion helpers (assetsToSharesWithdraw and sharesToAssetsWithdraw) ...
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.