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/Asset.h>
16#include <xrpl/protocol/Feature.h>
17#include <xrpl/protocol/Indexes.h>
18#include <xrpl/protocol/LedgerFormats.h>
19#include <xrpl/protocol/MPTIssue.h>
20#include <xrpl/protocol/Protocol.h>
21#include <xrpl/protocol/Rate.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STAmount.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/STNumber.h>
26#include <xrpl/protocol/STTakesAsset.h>
27#include <xrpl/protocol/STTx.h>
28#include <xrpl/protocol/TER.h>
29#include <xrpl/protocol/XRPAmount.h>
30#include <xrpl/tx/Transactor.h>
47 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
48 "xrpl::shouldWaiveWithdrawal : valid issuance sle");
68 if (asset.
native() || destination == account || account == asset.
getIssuer() ||
80 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: zero/empty vault ID.";
87 if (
auto const destination = ctx.
tx[~sfDestination])
118 <<
"VaultWithdraw: vault withdrawal is not allowed in the investment phase.";
123 auto const amount = ctx.
tx[sfAmount];
124 auto const vaultAsset = vault->at(sfAsset);
125 auto const vaultShare = vault->at(sfShareMPTID);
126 if (amount.asset() != vaultAsset && amount.asset() != vaultShare)
129 auto const& vaultAccount = vault->at(sfAccount);
130 auto const& account = ctx.
tx[sfAccount];
131 auto const& dstAcct = ctx.
tx[~sfDestination].value_or(account);
137 if (
auto ter =
canTransfer(ctx.
view, vaultAsset, vaultAccount, dstAcct, waive);
140 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: vault assets are non-transferable.";
148 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: invalid withdrawal policy.";
166 JLOG(ctx.
j.
debug()) <<
"VaultWithdraw: cannot withdraw into a pseudo-account.";
170 if (fix313Enabled && amount.asset() == vaultShare)
180 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: missing issuance of vault shares.";
191 auto const maybeAssets =
204 ctx.
tx[~sfCredentialIDs]))
212 <<
"VaultWithdraw: overflow error with"
213 <<
" scale=" << (int)vault->at(sfScale)
214 <<
", assetsTotal=" << vault->at(sfAssetsTotal)
215 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
216 <<
", amount=" << amount.value();
236 if (fix340Enabled && account == dstAcct && !
holdingExists(ctx.
view, dstAcct, vaultAsset))
252 if (fix340Enabled && vault->isFlag(lsfVaultPrivate) && dstAcct != account &&
253 dstAcct != vaultAsset.getIssuer())
259 JLOG(ctx.
j.
error()) <<
"VaultWithdraw: missing issuance of vault shares.";
307 auto const applyViewContext =
ctx_.getApplyViewContext();
311 auto const mptIssuanceID = *(*vault)[sfShareMPTID];
316 JLOG(
j_.error()) <<
"VaultWithdraw: missing issuance of vault shares.";
328 auto const amount =
ctx_.tx[sfAmount];
329 Asset const vaultAsset = vault->at(sfAsset);
330 auto const dstAcct =
ctx_.tx[~sfDestination].value_or(
accountID_);
333 MPTIssue const share{mptIssuanceID};
344 if (amount.asset() == vaultAsset)
356 auto const truncate =
364 waiveUnrealizedLoss);
367 sharesRedeemed = *maybeShares;
376 auto const maybeAssets =
380 assetsWithdrawn = *maybeAssets;
382 else if (amount.asset() == share)
386 sharesRedeemed = amount;
387 auto const maybeAssets =
391 assetsWithdrawn = *maybeAssets;
403 <<
"VaultWithdraw: overflow error with"
404 <<
" scale=" << (int)vault->at(sfScale).value()
405 <<
", assetsTotal=" << vault->at(sfAssetsTotal).value()
406 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
407 <<
", amount=" << amount.value();
415 bool const isFinalWithdrawal =
416 sharesRedeemed ==
STAmount{share, sleIssuance->at(sfOutstandingAmount)};
427 JLOG(
j_.debug()) <<
"VaultWithdraw: cannot empty vault while AssetsDeployed is non-zero";
431 auto const assetsAvailable = vault->at(sfAssetsAvailable);
432 if (fix340Enabled && !isFinalWithdrawal)
437 if (amount.asset() == share && assetsWithdrawn ==
beast::kZero &&
440 JLOG(
j_.debug()) <<
"VaultWithdraw: fixed-share withdrawal rounds to zero assets";
461 JLOG(
j_.debug()) <<
"VaultWithdraw: account doesn't hold enough shares";
471 if (fix340Enabled && !isFinalWithdrawal && assetsWithdrawn >
beast::kZero)
478 if (*assetsAvailable < assetsWithdrawn)
480 JLOG(
j_.debug()) <<
"VaultWithdraw: vault doesn't hold enough assets";
494 return maybeClamped.error();
495 assetsWithdrawn = *maybeClamped;
503 <<
"VaultWithdraw: overflow error with"
504 <<
" scale=" << (int)vault->at(sfScale).value()
505 <<
", assetsTotal=" << vault->at(sfAssetsTotal).value()
506 <<
", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
507 <<
", amount=" << amount.value();
516 if (*assetsAvailable < assetsWithdrawn)
518 JLOG(
j_.debug()) <<
"VaultWithdraw: vault doesn't hold enough assets";
528 bool const finalPayout =
view().
rules().
enabled(fixCleanup3_2_0) && isFinalWithdrawal;
538 "xrpl::VaultWithdraw::doApply : final withdrawal with non-zero unrealized loss");
541 "Cannot burn all outstanding shares while unrealized loss is non-zero";
546 STAmount const allAvailable{vaultAsset, *assetsAvailable};
547 if (assetsWithdrawn != allAvailable)
550 <<
"VaultWithdraw: final withdrawal share-value mismatch;"
551 <<
" computed=" << assetsWithdrawn.
getText()
552 <<
" assetsAvailable=" << allAvailable.
getText();
554 assetsWithdrawn = allAvailable;
560 JLOG(
j_.debug()) <<
"VaultWithdraw: transfer fee reduces the payout to zero";
567 vault->at(sfAssetsTotal) = 0;
568 vault->at(sfAssetsAvailable) = 0;
576 auto const& vaultAccount = vault->at(sfAccount);
594 <<
"VaultWithdraw: removed empty MPToken for vault shares"
602 <<
"VaultWithdraw: failed to remove MPToken for vault shares"
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.
constexpr bool native() const
AccountID const & getIssuer() const
Number is a floating point type that can represent a wide range of values.
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.
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...
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...
STAmount subtractTransferFee(STAmount const &amount, Rate const &rate)
Returns the amount a receiver gets when amount leaves the sender and the issuer takes the transfer fe...
TER doWithdraw(ApplyViewContext ctx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &destinationAmount, STAmount const &sourceAmount, beast::Journal j)
Pays out a withdrawal from a vault or loan broker pseudo-account.
static Rate withdrawalTransferRate(ReadView const &view, AccountID const &account, AccountID const &destination, Asset const &asset)
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.
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)
TER adjustVaultCash(SLE::Ref vault, STAmount const &delta, beast::Journal j)
Apply a signed cash movement to a Vault of any version.
std::string to_string(BaseUInt< Bits, Tag > const &a)
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 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,...
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
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.
Rate const kParityRate
A transfer rate signifying a 1:1 exchange.
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
STAmount addTransferFee(STAmount const &amount, Rate const &rate)
Returns the amount a sender must part with for amount to reach the receiver once the issuer takes the...
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.
VaultVersion getVaultVersion(SLE::ConstRef vault)
Resolves a Vault's LEVersion.
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.