xrpld
Loading...
Searching...
No Matches
VaultWithdraw.cpp
1#include <xrpl/tx/transactors/vault/VaultWithdraw.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/base_uint.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/ledger/ReadView.h>
8#include <xrpl/ledger/View.h>
9#include <xrpl/ledger/helpers/TokenHelpers.h>
10#include <xrpl/ledger/helpers/VaultHelpers.h>
11#include <xrpl/protocol/AccountID.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/LedgerFormats.h> // IWYU pragma: keep
15#include <xrpl/protocol/MPTIssue.h>
16#include <xrpl/protocol/Protocol.h>
17#include <xrpl/protocol/SField.h>
18#include <xrpl/protocol/STLedgerEntry.h>
19#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
20#include <xrpl/protocol/STTakesAsset.h>
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/protocol/TER.h>
23#include <xrpl/protocol/XRPAmount.h>
24#include <xrpl/tx/Transactor.h>
25
26#include <stdexcept>
27
28namespace xrpl {
29
31shouldWaiveWithdrawal(ReadView const& view, AccountID const& account, SLE::const_ref issuance)
32{
33 XRPL_ASSERT(
34 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
35 "xrpl::shouldWaiveWithdrawal : valid issuance sle");
36
37 return view.rules().enabled(fixCleanup3_2_0) && isSoleShareholder(view, account, issuance)
40}
41
44{
45 if (ctx.tx[sfVaultID] == beast::kZero)
46 {
47 JLOG(ctx.j.debug()) << "VaultWithdraw: zero/empty vault ID.";
48 return temMALFORMED;
49 }
50
51 if (ctx.tx[sfAmount] <= beast::kZero)
52 return temBAD_AMOUNT;
53
54 if (auto const destination = ctx.tx[~sfDestination])
55 {
56 if (*destination == beast::kZero)
57 {
58 return temMALFORMED;
59 }
60 }
61
62 return tesSUCCESS;
63}
64
65TER
67{
68 auto const fix313Enabled = ctx.view.rules().enabled(fixCleanup3_1_3);
69 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
70 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
71
72 auto const vault = ctx.view.read(keylet::vault(ctx.tx[sfVaultID]));
73 if (!vault)
74 return tecNO_ENTRY;
75
76 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
77 {
78 if (getVaultPhase(ctx.view, vault) == VaultPhase::Investment)
79 {
80 JLOG(ctx.j.debug())
81 << "VaultWithdraw: vault withdrawal is not allowed in the investment phase.";
82 return tecTOO_SOON;
83 }
84 }
85
86 auto const amount = ctx.tx[sfAmount];
87 auto const vaultAsset = vault->at(sfAsset);
88 auto const vaultShare = vault->at(sfShareMPTID);
89 if (amount.asset() != vaultAsset && amount.asset() != vaultShare)
90 return tecWRONG_ASSET;
91
92 auto const& vaultAccount = vault->at(sfAccount);
93 auto const& account = ctx.tx[sfAccount];
94 auto const& dstAcct = ctx.tx[~sfDestination].value_or(account);
95 // Post-fixCleanup3_2_0: withdraw is a recovery path that bypasses the
96 // lsfMPTCanTransfer flag check, so an issuer cannot trap depositor funds.
97 // Other transferability checks (IOU NoRipple, freeze, requireAuth) still
98 // apply.
99 auto const waive = fix320Enabled ? WaiveMPTCanTransfer::Yes : WaiveMPTCanTransfer::No;
100 if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct, waive);
101 !isTesSuccess(ter))
102 {
103 JLOG(ctx.j.debug()) << "VaultWithdraw: vault assets are non-transferable.";
104 return ter;
105 }
106
107 // Enforce valid withdrawal policy
108 if (vault->at(sfWithdrawalPolicy) != kVaultStrategyFirstComeFirstServe)
109 {
110 // LCOV_EXCL_START
111 JLOG(ctx.j.error()) << "VaultWithdraw: invalid withdrawal policy.";
112 return tefINTERNAL;
113 // LCOV_EXCL_STOP
114 }
115
116 if (fix313Enabled && amount.asset() == vaultShare)
117 {
118 // Post-fixCleanup3_1_3: if the user specified shares, convert
119 // to the equivalent asset amount before checking withdrawal
120 // limits. Pre-amendment the limit check was skipped for
121 // share-denominated withdrawals.
122 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(vaultShare));
123 if (!sleIssuance)
124 {
125 // LCOV_EXCL_START
126 JLOG(ctx.j.error()) << "VaultWithdraw: missing issuance of vault shares.";
127 return tefINTERNAL;
128 // LCOV_EXCL_STOP
129 }
130
131 // When the user is the sole shareholder they own both the available and future value.
132 // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of
133 // their shares but keeping future value in the vault.
134 auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(ctx.view, account, sleIssuance);
135 try
136 {
137 auto const maybeAssets =
138 sharesToAssetsWithdraw(vault, sleIssuance, amount, waiveUnrealizedLoss);
139 if (!maybeAssets)
140 return tefINTERNAL; // LCOV_EXCL_LINE
141
142 if (auto const ret = canWithdraw(
143 ctx.view,
144 account,
145 dstAcct,
146 *maybeAssets,
147 ctx.tx.isFieldPresent(sfDestinationTag)))
148 return ret;
149 }
150 catch (std::overflow_error const&)
151 {
152 // It's easy to hit this exception from Number with large enough Scale
153 // so we avoid spamming the log and only use debug here.
154 JLOG(ctx.j.debug()) //
155 << "VaultWithdraw: overflow error with"
156 << " scale=" << (int)vault->at(sfScale) //
157 << ", assetsTotal=" << vault->at(sfAssetsTotal)
158 << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
159 << ", amount=" << amount.value();
160 return tecPATH_DRY;
161 }
162 }
163 else
164 {
165 if (auto const ret = canWithdraw(ctx.view, ctx.tx))
166 return ret;
167 }
168
169 // If sending to Account (i.e. not a transfer), we will also create (only
170 // if authorized) a trust line or MPToken as needed, in doApply().
171 // Destination MPToken or trust line must exist if _not_ sending to Account.
172 AuthType const authType = account == dstAcct ? AuthType::WeakAuth : AuthType::StrongAuth;
173 if (auto const ter = requireAuth(ctx.view, vaultAsset, dstAcct, authType); !isTesSuccess(ter))
174 return ter;
175
176 if (fix330Enabled)
177 {
178 // checkWithdrawFreeze checks the underlying asset on the source
179 // (vault pseudo-account), the submitter, and the destination.
180 // A separate share-level freeze check is unnecessary: vault shares
181 // are issued by the vault pseudo-account, which cannot submit
182 // MPTokenIssuanceSet to individually lock a holder's MPToken.
183 // The only way shares become locked is transitively via the
184 // underlying asset, which checkWithdrawFreeze covers.
185 if (auto const ret =
186 checkWithdrawFreeze(ctx.view, vaultAccount, account, dstAcct, vaultAsset))
187 return ret;
188 }
189 else
190 {
191 // Cannot withdraw from a Vault an Asset frozen for the destination account
192 if (auto const ret = checkFrozen(ctx.view, dstAcct, vaultAsset))
193 return ret;
194
195 // Cannot return shares to the vault, if the underlying asset was frozen for
196 // the submitter
197 if (auto const ret = checkFrozen(ctx.view, account, Asset{vaultShare}))
198 return ret;
199 }
200 return tesSUCCESS;
201}
202
203TER
205{
206 auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
207 auto applyViewContext = ctx_.getApplyViewContext();
208 if (!vault)
209 return tefINTERNAL; // LCOV_EXCL_LINE
210
211 auto const mptIssuanceID = *((*vault)[sfShareMPTID]);
212 auto const sleIssuance = view().read(keylet::mptokenIssuance(mptIssuanceID));
213 if (!sleIssuance)
214 {
215 // LCOV_EXCL_START
216 JLOG(j_.error()) << "VaultWithdraw: missing issuance of vault shares.";
217 return tefINTERNAL;
218 // LCOV_EXCL_STOP
219 }
220
221 // Note, we intentionally do not check lsfVaultPrivate flag on the Vault. If
222 // you have a share in the vault, it means you were at some point authorized
223 // to deposit into it, and this means you are also indefinitely authorized
224 // to withdraw from it.
225
226 auto const amount = ctx_.tx[sfAmount];
227 Asset const vaultAsset = vault->at(sfAsset);
228
229 MPTIssue const share{mptIssuanceID};
230 STAmount sharesRedeemed = {share};
231 STAmount assetsWithdrawn;
232
233 // When the user is the sole shareholder they own both the available and future value.
234 // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of their
235 // shares but keeping future value in the vault.
236 auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(view(), accountID_, sleIssuance);
237 try
238 {
239 if (amount.asset() == vaultAsset)
240 {
241 // Fixed assets, variable shares.
242 {
243 auto const maybeShares = assetsToSharesWithdraw(
244 vault, sleIssuance, amount, TruncateShares::No, waiveUnrealizedLoss);
245 if (!maybeShares)
246 return tecINTERNAL; // LCOV_EXCL_LINE
247 sharesRedeemed = *maybeShares;
248 }
249
250 if (sharesRedeemed == beast::kZero)
251 return tecPRECISION_LOSS;
252 auto const maybeAssets =
253 sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss);
254 if (!maybeAssets)
255 return tecINTERNAL; // LCOV_EXCL_LINE
256 assetsWithdrawn = *maybeAssets;
257 }
258 else if (amount.asset() == share)
259 {
260 // Fixed shares, variable assets.
261 sharesRedeemed = amount;
262 auto const maybeAssets =
263 sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss);
264 if (!maybeAssets)
265 return tecINTERNAL; // LCOV_EXCL_LINE
266 assetsWithdrawn = *maybeAssets;
267 }
268 else
269 {
270 return tefINTERNAL; // LCOV_EXCL_LINE
271 }
272 }
273 catch (std::overflow_error const&)
274 {
275 // It's easy to hit this exception from Number with large enough Scale
276 // so we avoid spamming the log and only use debug here.
277 JLOG(j_.debug()) //
278 << "VaultWithdraw: overflow error with"
279 << " scale=" << (int)vault->at(sfScale).value() //
280 << ", assetsTotal=" << vault->at(sfAssetsTotal).value()
281 << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount)
282 << ", amount=" << amount.value();
283 return tecPATH_DRY;
284 }
285
286 // Post-fixCleanup3_3_0: preclaim already validated all freeze conditions
287 // (checkWithdrawFreeze), so IgnoreFreeze avoids a redundant check that
288 // would incorrectly return zero for vault pseudo-accounts whose shares
289 // are frozen via a transitively frozen underlying asset.
290 auto const freezeHandling = view().rules().enabled(fixCleanup3_3_0)
293 if (accountHolds(view(), accountID_, share, freezeHandling, AuthHandling::IgnoreAuth, j_) <
294 sharesRedeemed)
295 {
296 JLOG(j_.debug()) << "VaultWithdraw: account doesn't hold enough shares";
298 }
299
300 auto assetsAvailable = vault->at(sfAssetsAvailable);
301 auto assetsTotal = vault->at(sfAssetsTotal);
302 auto const lossUnrealized = vault->at(sfLossUnrealized);
303 XRPL_ASSERT(
304 lossUnrealized <= (assetsTotal - assetsAvailable),
305 "xrpl::VaultWithdraw::doApply : loss and assets do balance");
306
307 // The vault must have enough assets on hand.
308 if (*assetsAvailable < assetsWithdrawn)
309 {
310 JLOG(j_.debug()) << "VaultWithdraw: vault doesn't hold enough assets";
312 }
313
314 // Post-fixCleanup3_2_0 "final withdrawal" rule:
315 // a transaction that would burn every outstanding share is only permitted when the vault is in
316 // a clean state — no outstanding receivables and no unrealized loss. Otherwise the resulting
317 // (shares == 0, assetsTotal > 0) state would violate the zero-sized-vault invariant.
318 //
319 // When the rule applies, the payout is the remaining sfAssetsAvailable; in a clean vault
320 // the helper result should already equal that value, and any mismatch is a rounding artifact
321 // worth logging.
322 bool const isFinalWithdrawal =
323 sharesRedeemed == STAmount{share, sleIssuance->at(sfOutstandingAmount)};
324 if (view().rules().enabled(fixCleanup3_2_0) && isFinalWithdrawal)
325 {
326 // Unreachable: a final withdrawal with lossUnrealized > 0 has
327 // assetsWithdrawn == assetsTotal > assetsAvailable, which the
328 // insufficient-funds guard above already rejected.
329 if (*lossUnrealized != beast::kZero)
330 {
331 // LCOV_EXCL_START
332 UNREACHABLE(
333 "xrpl::VaultWithdraw::doApply : final withdrawal with non-zero unrealized loss");
334 JLOG(j_.fatal())
335 << "VaultWithdraw: " //
336 "Cannot burn all outstanding shares while unrealized loss is non-zero";
337 return tefINTERNAL;
338 // LCOV_EXCL_STOP
339 }
340
341 STAmount const allAvailable{vaultAsset, *assetsAvailable};
342 if (assetsWithdrawn != allAvailable)
343 {
344 JLOG(j_.error()) //
345 << "VaultWithdraw: final withdrawal share-value mismatch;"
346 << " computed=" << assetsWithdrawn.getText()
347 << " assetsAvailable=" << allAvailable.getText();
348 }
349 assetsWithdrawn = allAvailable;
350
351 // Do not let dust accumulate in the Vault.
352 assetsTotal = 0;
353 assetsAvailable = 0;
354 }
355 else
356 {
357 assetsTotal -= assetsWithdrawn;
358 assetsAvailable -= assetsWithdrawn;
359 }
360 view().update(vault);
361
362 auto const& vaultAccount = vault->at(sfAccount);
363
364 // Transfer shares from depositor to vault.
365 if (auto const ter = accountSend(
366 view(), accountID_, vaultAccount, sharesRedeemed, j_, {}, WaiveTransferFee::Yes);
367 !isTesSuccess(ter))
368 return ter;
369
370 // Try to remove MPToken for shares, if the account balance is zero. Vault
371 // pseudo-account will never set lsfMPTAuthorized, so we ignore flags.
372 // Keep MPToken if holder is the vault owner.
373 if (accountID_ != vault->at(sfOwner))
374 {
375 if (auto const ter =
376 removeEmptyHolding(applyViewContext, accountID_, sharesRedeemed.asset(), j_);
377 isTesSuccess(ter))
378 {
379 JLOG(j_.debug()) //
380 << "VaultWithdraw: removed empty MPToken for vault shares"
381 << " MPTID=" << to_string(mptIssuanceID) //
382 << " account=" << toBase58(accountID_);
383 }
384 else if (ter != tecHAS_OBLIGATIONS)
385 {
386 // LCOV_EXCL_START
387 JLOG(j_.error()) //
388 << "VaultWithdraw: failed to remove MPToken for vault shares"
389 << " MPTID=" << to_string(mptIssuanceID) //
390 << " account=" << toBase58(accountID_) //
391 << " with result: " << transToken(ter);
392 return ter;
393 // LCOV_EXCL_STOP
394 }
395 // else quietly ignore, account balance is not zero
396 }
397
398 associateAsset(*vault, vaultAsset);
399
400 auto const dstAcct = ctx_.tx[~sfDestination].value_or(accountID_);
401 return doWithdraw(
402 applyViewContext, accountID_, dstAcct, vaultAccount, preFeeBalance_, assetsWithdrawn, j_);
403}
404
405void
407{
408 // No transaction-specific invariants yet (future work).
409}
410
411bool
413 STTx const&,
414 TER,
415 XRPAmount,
416 ReadView const&,
417 beast::Journal const&)
418{
419 // No transaction-specific invariants yet (future work).
420 return true;
421}
422
423} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
Stream debug() const
Definition Journal.h:344
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.
A view into a ledger.
Definition ReadView.h:41
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.
Definition Rules.cpp:180
std::string getText() const override
Definition STAmount.cpp:646
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry const > const & const_ref
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
beast::Journal const j_
Definition Transactor.h:155
ApplyView & view()
Definition Transactor.h:175
AccountID const accountID_
Definition Transactor.h:157
XRPAmount preFeeBalance_
Definition Transactor.h:158
ApplyContext & ctx_
Definition Transactor.h:153
void visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override
Inspect a single ledger entry modified by this transaction.
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.
TER doApply() override
static TER preclaim(PreclaimContext const &ctx)
static NotTEC preflight(PreflightContext const &ctx)
constexpr Zero kZero
Definition Zero.h:30
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:561
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:537
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
std::optional< STAmount > assetsToSharesWithdraw(SLE::const_ref vault, SLE::const_ref 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 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.
VaultPhase getVaultPhase(ReadView const &view, SLE::const_ref vault)
Returns the current lifecycle phase of a vault.
TER removeEmptyHolding(ApplyViewContext ctx, AccountID const &accountID, MPTIssue const &mptIssue, beast::Journal journal)
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
@ tefINTERNAL
Definition TER.h:165
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
std::optional< STAmount > sharesToAssetsWithdraw(SLE::const_ref vault, SLE::const_ref 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...
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)
Definition TER.cpp:251
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:651
TER doWithdraw(ApplyViewContext ctx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &amount, beast::Journal j)
Definition View.cpp:442
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:607
static WaiveUnrealizedLoss shouldWaiveWithdrawal(ReadView const &view, AccountID const &account, SLE::const_ref issuance)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:676
constexpr std::uint8_t kVaultStrategyFirstComeFirstServe
Vault withdrawal policies.
Definition Protocol.h:307
TERSubset< CanCvtToTER > TER
Definition TER.h:647
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.
@ tecWRONG_ASSET
Definition TER.h:363
@ tecNO_ENTRY
Definition TER.h:309
@ tecPATH_DRY
Definition TER.h:297
@ tecINTERNAL
Definition TER.h:313
@ tecTOO_SOON
Definition TER.h:321
@ tecINSUFFICIENT_FUNDS
Definition TER.h:328
@ tecPRECISION_LOSS
Definition TER.h:366
@ tecHAS_OBLIGATIONS
Definition TER.h:320
bool isSoleShareholder(ReadView const &view, AccountID const &account, SLE::const_ref issuance)
Returns true iff account holds all of the vault's outstanding shares — i.e.
TER canWithdraw(ReadView const &view, AccountID const &from, AccountID const &to, SLE::const_ref toSle, STAmount const &amount, bool hasDestinationTag)
Checks that can withdraw funds from an object to itself or a destination.
Definition View.cpp:396
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 &currency, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
@ tesSUCCESS
Definition TER.h:245
WaiveUnrealizedLoss
Controls whether the withdraw conversion helpers (assetsToSharesWithdraw and sharesToAssetsWithdraw) ...
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:83
ReadView const & view
Definition Transactor.h:86
beast::Journal const j
Definition Transactor.h:91
State information when preflighting a tx.
Definition Transactor.h:38
beast::Journal const j
Definition Transactor.h:45