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/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> // IWYU pragma: keep
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> // IWYU pragma: keep
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>
31
32#include <stdexcept>
33
34namespace xrpl {
35
36bool
38{
39 return !ctx.tx.isFieldPresent(sfCredentialIDs) ||
40 (ctx.rules.enabled(featureCredentials) && ctx.rules.enabled(fixCleanup3_4_0));
41}
42
44shouldWaiveWithdrawal(ReadView const& view, AccountID const& account, SLE::ConstRef issuance)
45{
46 XRPL_ASSERT(
47 issuance && issuance->getType() == ltMPTOKEN_ISSUANCE,
48 "xrpl::shouldWaiveWithdrawal : valid issuance sle");
49
50 return view.rules().enabled(fixCleanup3_2_0) && isSoleShareholder(view, account, issuance)
53}
54
55static Rate
57 ReadView const& view,
58 AccountID const& account,
59 AccountID const& destination,
60 Asset const& asset)
61{
62 // Pre-fixCleanup3_5_0: every vault withdrawal waives the transfer fee.
63 // Post-fixCleanup3_5_0: the fee applies only when a holder other than the issuer withdraws to
64 // another such holder.
65 if (!view.rules().enabled(fixCleanup3_5_0))
66 return kParityRate;
67
68 if (asset.native() || destination == account || account == asset.getIssuer() ||
69 destination == asset.getIssuer())
70 return kParityRate;
71
72 return transferRate(view, asset);
73}
74
77{
78 if (ctx.tx[sfVaultID] == beast::kZero)
79 {
80 JLOG(ctx.j.debug()) << "VaultWithdraw: zero/empty vault ID.";
81 return temMALFORMED;
82 }
83
84 if (ctx.tx[sfAmount] <= beast::kZero)
85 return temBAD_AMOUNT;
86
87 if (auto const destination = ctx.tx[~sfDestination])
88 {
89 if (*destination == beast::kZero)
90 {
91 return temMALFORMED;
92 }
93 }
94
95 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
96 return err;
97
98 return tesSUCCESS;
99}
100
101TER
103{
104 auto const fix313Enabled = ctx.view.rules().enabled(fixCleanup3_1_3);
105 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
106 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
107 auto const fix340Enabled = ctx.view.rules().enabled(fixCleanup3_4_0);
108
109 auto const vault = ctx.view.read(keylet::vault(ctx.tx[sfVaultID]));
110 if (!vault)
111 return tecNO_ENTRY;
112
113 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
114 {
115 if (getVaultPhase(ctx.view, vault) == VaultPhase::Investment)
116 {
117 JLOG(ctx.j.debug())
118 << "VaultWithdraw: vault withdrawal is not allowed in the investment phase.";
119 return tecTOO_SOON;
120 }
121 }
122
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)
127 return tecWRONG_ASSET;
128
129 auto const& vaultAccount = vault->at(sfAccount);
130 auto const& account = ctx.tx[sfAccount];
131 auto const& dstAcct = ctx.tx[~sfDestination].value_or(account);
132 // Post-fixCleanup3_2_0: withdraw is a recovery path that bypasses the
133 // lsfMPTCanTransfer flag check, so an issuer cannot trap depositor funds.
134 // Other transferability checks (IOU NoRipple, freeze, requireAuth) still
135 // apply.
136 auto const waive = fix320Enabled ? WaiveMPTCanTransfer::Yes : WaiveMPTCanTransfer::No;
137 if (auto ter = canTransfer(ctx.view, vaultAsset, vaultAccount, dstAcct, waive);
138 !isTesSuccess(ter))
139 {
140 JLOG(ctx.j.debug()) << "VaultWithdraw: vault assets are non-transferable.";
141 return ter;
142 }
143
144 // Enforce valid withdrawal policy
145 if (vault->at(sfWithdrawalPolicy) != kVaultStrategyFirstComeFirstServe)
146 {
147 // LCOV_EXCL_START
148 JLOG(ctx.j.error()) << "VaultWithdraw: invalid withdrawal policy.";
149 return tefINTERNAL;
150 // LCOV_EXCL_STOP
151 }
152
153 // Validate credentials (if any) before canWithdraw, since canWithdraw may
154 // call credentials::authorizedDepositPreauth which assumes credentials
155 // already exist.
156 if (auto const err = credentials::valid(ctx.tx, ctx.view, account, ctx.j); !isTesSuccess(err))
157 return err;
158
159 // A pseudo-account belongs to a ledger object rather than to a person and
160 // must never receive funds from a user-initiated transaction. Deposit
161 // authorization, which every pseudo-account carries, already refuses the
162 // payout, but it reports only that the destination declines deposits and
163 // leaves the real reason unsaid.
164 if (fix340Enabled && isPseudoAccount(ctx.view, dstAcct))
165 {
166 JLOG(ctx.j.debug()) << "VaultWithdraw: cannot withdraw into a pseudo-account.";
167 return tecPSEUDO_ACCOUNT;
168 }
169
170 if (fix313Enabled && amount.asset() == vaultShare)
171 {
172 // Post-fixCleanup3_1_3: if the user specified shares, convert
173 // to the equivalent asset amount before checking withdrawal
174 // limits. Pre-amendment the limit check was skipped for
175 // share-denominated withdrawals.
176 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(vaultShare));
177 if (!sleIssuance)
178 {
179 // LCOV_EXCL_START
180 JLOG(ctx.j.error()) << "VaultWithdraw: missing issuance of vault shares.";
181 return tefINTERNAL;
182 // LCOV_EXCL_STOP
183 }
184
185 // When the user is the sole shareholder they own both the available and future value.
186 // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of
187 // their shares but keeping future value in the vault.
188 auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(ctx.view, account, sleIssuance);
189 try
190 {
191 auto const maybeAssets =
192 sharesToAssetsWithdraw(vault, sleIssuance, amount, waiveUnrealizedLoss);
193 if (!maybeAssets)
194 return tefINTERNAL; // LCOV_EXCL_LINE
195
196 auto const rate = withdrawalTransferRate(ctx.view, account, dstAcct, vaultAsset);
197 auto const amountToReceive = subtractTransferFee(*maybeAssets, rate);
198 if (auto const ret = canWithdraw(
199 ctx.view,
200 account,
201 dstAcct,
202 amountToReceive,
203 ctx.tx.isFieldPresent(sfDestinationTag),
204 ctx.tx[~sfCredentialIDs]))
205 return ret;
206 }
207 catch (std::overflow_error const&)
208 {
209 // It's easy to hit this exception from Number with large enough Scale
210 // so we avoid spamming the log and only use debug here.
211 JLOG(ctx.j.debug()) //
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();
217 return tecPATH_DRY;
218 }
219 }
220 else
221 {
222 if (auto const ret = canWithdraw(ctx.view, ctx.tx))
223 return ret;
224 }
225
226 // If sending to Account (i.e. not a transfer), we will also create (only
227 // if authorized) a trust line or MPToken as needed, in doApply().
228 // Destination MPToken or trust line must exist if _not_ sending to Account.
229 AuthType const authType = account == dstAcct ? AuthType::WeakAuth : AuthType::StrongAuth;
230 if (auto const ter = requireAuth(ctx.view, vaultAsset, dstAcct, authType); !isTesSuccess(ter))
231 return ter;
232
233 // Fail early when self-destination would have to create a holding.
234 // Skip when a holding already exists: canAddHolding does not look at that,
235 // and would block a no-op create (the DefaultRipple-cleared self-withdraw).
236 if (fix340Enabled && account == dstAcct && !holdingExists(ctx.view, dstAcct, vaultAsset))
237 {
238 if (auto const ter = canAddHolding(ctx.view, vaultAsset); !isTesSuccess(ter))
239 return ter;
240 }
241
242 // The checks above only establish that an account may hold the asset. A
243 // private vault additionally restricts who may take part in it, so paying
244 // its asset out to a third party requires both ends of that payout to be
245 // inside the vault's permissioned domain. VaultDeposit applies the same
246 // domain check on the way in.
247 //
248 // Two cases deliberately skip the check. Withdrawing to self is never
249 // restricted: losing vault access must not strand funds already deposited.
250 // The asset issuer is always allowed to receive, which keeps the return
251 // path for frozen assets open even for a submitter who lost access.
252 if (fix340Enabled && vault->isFlag(lsfVaultPrivate) && dstAcct != account &&
253 dstAcct != vaultAsset.getIssuer())
254 {
255 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(vaultShare));
256 if (!sleIssuance)
257 {
258 // LCOV_EXCL_START
259 JLOG(ctx.j.error()) << "VaultWithdraw: missing issuance of vault shares.";
260 return tefINTERNAL;
261 // LCOV_EXCL_STOP
262 }
263
264 // Unlike VaultDeposit we do not suppress tecEXPIRED: there is no
265 // doApply step here that would clean up the expired credential.
266 if (auto const ter = checkVaultDomain(ctx.view, sleIssuance, account, SuppressExpired::No);
267 !isTesSuccess(ter))
268 return ter;
269
270 if (auto const ter = checkVaultDomain(ctx.view, sleIssuance, dstAcct, SuppressExpired::No);
271 !isTesSuccess(ter))
272 return ter;
273 }
274
275 if (fix330Enabled)
276 {
277 // checkWithdrawFreeze checks the underlying asset on the source
278 // (vault pseudo-account), the submitter, and the destination.
279 // A separate share-level freeze check is unnecessary: vault shares
280 // are issued by the vault pseudo-account, which cannot submit
281 // MPTokenIssuanceSet to individually lock a holder's MPToken.
282 // The only way shares become locked is transitively via the
283 // underlying asset, which checkWithdrawFreeze covers.
284 if (auto const ret =
285 checkWithdrawFreeze(ctx.view, vaultAccount, account, dstAcct, vaultAsset))
286 return ret;
287 }
288 else
289 {
290 // Cannot withdraw from a Vault an Asset frozen for the destination account
291 if (auto const ret = checkFrozen(ctx.view, dstAcct, vaultAsset))
292 return ret;
293
294 // Cannot return shares to the vault, if the underlying asset was frozen for
295 // the submitter
296 if (auto const ret = checkFrozen(ctx.view, account, Asset{vaultShare}))
297 return ret;
298 }
299 return tesSUCCESS;
300}
301
302TER
304{
305 bool const fix340Enabled = view().rules().enabled(fixCleanup3_4_0);
306 auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
307 auto const applyViewContext = ctx_.getApplyViewContext();
308 if (!vault)
309 return tefINTERNAL; // LCOV_EXCL_LINE
310
311 auto const mptIssuanceID = *(*vault)[sfShareMPTID];
312 auto const sleIssuance = view().read(keylet::mptokenIssuance(mptIssuanceID));
313 if (!sleIssuance)
314 {
315 // LCOV_EXCL_START
316 JLOG(j_.error()) << "VaultWithdraw: missing issuance of vault shares.";
317 return tefINTERNAL;
318 // LCOV_EXCL_STOP
319 }
320
321 // Note, we intentionally do not check lsfVaultPrivate flag on the Vault. If
322 // you have a share in the vault, it means you were at some point authorized
323 // to deposit into it, and this means you are also indefinitely authorized
324 // to withdraw it to yourself. Sending the proceeds to somebody else is a
325 // different matter, and preclaim checks such a withdrawal against the
326 // vault's permissioned domain.
327
328 auto const amount = ctx_.tx[sfAmount];
329 Asset const vaultAsset = vault->at(sfAsset);
330 auto const dstAcct = ctx_.tx[~sfDestination].value_or(accountID_);
331 auto const rate = withdrawalTransferRate(view(), accountID_, dstAcct, vaultAsset);
332
333 MPTIssue const share{mptIssuanceID};
334 STAmount sharesRedeemed = {share};
335 STAmount assetsWithdrawn;
336
337 // When the user is the sole shareholder they own both the available and future value.
338 // We waive the unrealized-loss subtraction in this case to avoid user withdrawing all of their
339 // shares but keeping future value in the vault.
340 auto const waiveUnrealizedLoss = shouldWaiveWithdrawal(view(), accountID_, sleIssuance);
341 // Number arithmetic can throw overflow_error when Scale and totals are large. Caught below.
342 try
343 {
344 if (amount.asset() == vaultAsset)
345 {
346 // Fixed assets, variable shares.
347 //
348 // Pre-fixCleanup3_4_0: shares were rounded to nearest, so the
349 // round-trip back to assets could exceed the requested amount.
350 // That over-delivers to the depositor and can bypass the
351 // preclaim canWithdraw check on the destination, which was
352 // validated against the requested amount only.
353 // Post-amendment: truncate shares so assetsWithdrawn <=
354 // requested amount by construction. If truncation yields zero
355 // shares, the tecPRECISION_LOSS guard below fires.
356 auto const truncate =
358 {
359 auto const maybeShares = assetsToSharesWithdraw(
360 vault,
361 sleIssuance,
362 addTransferFee(amount, rate),
363 truncate,
364 waiveUnrealizedLoss);
365 if (!maybeShares)
366 return tecINTERNAL; // LCOV_EXCL_LINE
367 sharesRedeemed = *maybeShares;
368 }
369
370 // Shares are MPT (integer). Small requested amounts truncate to zero; refuse rather
371 // than burn nothing while paying out assets.
372 if (sharesRedeemed == beast::kZero)
373 return tecPRECISION_LOSS;
374 // Convert shares back to assets so the payout matches the shares actually burned, not
375 // the requested amount. The extra would otherwise be paid from the vault for free.
376 auto const maybeAssets =
377 sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss);
378 if (!maybeAssets)
379 return tecINTERNAL; // LCOV_EXCL_LINE
380 assetsWithdrawn = *maybeAssets;
381 }
382 else if (amount.asset() == share)
383 {
384 // Fixed shares, variable assets. No round-trip: the share count is exactly what the
385 // caller specified; only the payout amount is derived.
386 sharesRedeemed = amount;
387 auto const maybeAssets =
388 sharesToAssetsWithdraw(vault, sleIssuance, sharesRedeemed, waiveUnrealizedLoss);
389 if (!maybeAssets)
390 return tecINTERNAL; // LCOV_EXCL_LINE
391 assetsWithdrawn = *maybeAssets;
392 }
393 else
394 {
395 return tefINTERNAL; // LCOV_EXCL_LINE
396 }
397 }
398 catch (std::overflow_error const&)
399 {
400 // It's easy to hit this exception from Number with large enough Scale
401 // so we avoid spamming the log and only use debug here.
402 JLOG(j_.debug()) //
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();
408 // Overflow means this transaction cannot apply, but ledger state is still consistent.
409 // Return tecPATH_DRY rather than a hard internal error.
410 return tecPATH_DRY;
411 }
412
413 // The "final withdrawal" rule below handles its own zero-value case using
414 // sfAssetsAvailable directly, so it is exempt from the checks below.
415 bool const isFinalWithdrawal =
416 sharesRedeemed == STAmount{share, sleIssuance->at(sfOutstandingAmount)};
417
418 // FixedPrecision: a final withdrawal must not leave AssetsDeployed behind
419 // with no shares to back it. A final withdrawal pays out AssetsAvailable
420 // + AssetsDeployed, rounded to 16 digits; on a coarsened vault, an
421 // AssetsDeployed below half a unit of AssetsAvailable's grid rounds
422 // away, so the payout equals AssetsAvailable exactly and the vault would
423 // be left with no shares and no cash but a non-zero AssetsDeployed.
424 if (isFinalWithdrawal && getVaultVersion(vault) == VaultVersion::FixedPrecision &&
425 Number(vault->at(sfAssetsDeployed)) != beast::kZero)
426 {
427 JLOG(j_.debug()) << "VaultWithdraw: cannot empty vault while AssetsDeployed is non-zero";
428 return tecHAS_OBLIGATIONS;
429 }
430
431 auto const assetsAvailable = vault->at(sfAssetsAvailable);
432 if (fix340Enabled && !isFinalWithdrawal)
433 {
434 // Fixed-shares path: a small share count can round to zero assets even though the vault has
435 // backing value. Reject rather than burn shares for a zero payout. The fixed-assets branch
436 // above has already rejected zero via the sharesRedeemed check.
437 if (amount.asset() == share && assetsWithdrawn == beast::kZero &&
438 assetsTotalForWithdrawal(vault, waiveUnrealizedLoss) != beast::kZero)
439 {
440 JLOG(j_.debug()) << "VaultWithdraw: fixed-share withdrawal rounds to zero assets";
441 return tecPRECISION_LOSS;
442 }
443
444 // A non-zero payout can be too small to change the stored balance at
445 // STAmount's precision. Shares would still be burned, reject it instead.
446 if (auto const ter = checkDebitNotDust(vault, assetsWithdrawn, j_, "VaultWithdraw");
447 !isTesSuccess(ter))
448 return ter;
449 }
450
451 // Post-fixCleanup3_3_0: preclaim already validated all freeze conditions
452 // (checkWithdrawFreeze), so IgnoreFreeze avoids a redundant check that
453 // would incorrectly return zero for vault pseudo-accounts whose shares
454 // are frozen via a transitively frozen underlying asset.
455 auto const freezeHandling = view().rules().enabled(fixCleanup3_3_0)
458 if (accountHolds(view(), accountID_, share, freezeHandling, AuthHandling::IgnoreAuth, j_) <
459 sharesRedeemed)
460 {
461 JLOG(j_.debug()) << "VaultWithdraw: account doesn't hold enough shares";
463 }
464
465 // Post-fixCleanup3_4_0: round the payout to the sfAssetsTotal scale so all three rails
466 // (trust line / MPT, sfAssetsAvailable, sfAssetsTotal) change by the same representable delta.
467 // Skip when assetsWithdrawn is already zero: the earlier fix340 guard above deliberately
468 // permits fixed-share zero-asset withdrawals in a fully-impaired vault (where
469 // assetsTotalForWithdrawal == 0), and clamping-then-rejecting would undo that. Also skip on
470 // the final-withdrawal path, which overwrites assetsWithdrawn with sfAssetsAvailable below.
471 if (fix340Enabled && !isFinalWithdrawal && assetsWithdrawn > beast::kZero)
472 {
473 // Check availability against the unclamped amount first, so a withdrawal that is both
474 // over the vault's available balance and sub-ULP at the posterior sfAssetsTotal scale
475 // reports tecINSUFFICIENT_FUNDS rather than tecPRECISION_LOSS. The clamp below only ever
476 // shrinks assetsWithdrawn, so this check stays valid; the post-clamp check further down
477 // remains in place to catch the (now smaller) clamped value too.
478 if (*assetsAvailable < assetsWithdrawn)
479 {
480 JLOG(j_.debug()) << "VaultWithdraw: vault doesn't hold enough assets";
482 }
483
484 // Number arithmetic can throw overflow_error when Scale and totals are large.
485 try
486 {
487 // Round down at the posterior scale of the balance the payout actually
488 // leaves -- AssetsAvailable on FixedPrecision, the AssetsTotal cache on
489 // Legacy/CashBasis -- so the payout never exceeds the value represented
490 // by the redeemed shares. sharesRedeemed is intentionally not
491 // re-derived: any trimmed residue stays with remaining shareholders.
492 auto const maybeClamped = clampVaultOutflow(vault, -assetsWithdrawn);
493 if (!maybeClamped)
494 return maybeClamped.error(); // LCOV_EXCL_LINE
495 assetsWithdrawn = *maybeClamped;
496 }
497 // LCOV_EXCL_START
498 catch (std::overflow_error const&)
499 {
500 // It's easy to hit this exception from Number with large enough Scale
501 // so we avoid spamming the log and only use debug here.
502 JLOG(j_.debug()) //
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();
508 // Overflow means this transaction cannot apply, but ledger state is still consistent.
509 // Return tecPATH_DRY rather than a hard internal error.
510 return tecPATH_DRY;
511 }
512 // LCOV_EXCL_STOP
513 }
514
515 // The vault must have enough assets on hand.
516 if (*assetsAvailable < assetsWithdrawn)
517 {
518 JLOG(j_.debug()) << "VaultWithdraw: vault doesn't hold enough assets";
520 }
521
522 // Post-fixCleanup3_2_0: burning every outstanding share is only allowed when the vault has no
523 // unrealized loss. Otherwise the resulting (shares == 0, assetsTotal > 0) state would violate
524 // the zero-sized-vault invariant.
525 //
526 // The payout is set to the remaining AssetsAvailable. The helper result should already
527 // equal that value in a clean vault; any mismatch is a rounding artifact and is logged.
528 bool const finalPayout = view().rules().enabled(fixCleanup3_2_0) && isFinalWithdrawal;
529 if (finalPayout)
530 {
531 // Unreachable: a final withdrawal with lossUnrealized > 0 has
532 // assetsWithdrawn == assetsTotal > assetsAvailable, which the
533 // insufficient-funds guard above already rejected.
534 if (*vault->at(sfLossUnrealized) != beast::kZero)
535 {
536 // LCOV_EXCL_START
537 UNREACHABLE(
538 "xrpl::VaultWithdraw::doApply : final withdrawal with non-zero unrealized loss");
539 JLOG(j_.fatal())
540 << "VaultWithdraw: " //
541 "Cannot burn all outstanding shares while unrealized loss is non-zero";
542 return tefINTERNAL;
543 // LCOV_EXCL_STOP
544 }
545
546 STAmount const allAvailable{vaultAsset, *assetsAvailable};
547 if (assetsWithdrawn != allAvailable)
548 {
549 JLOG(j_.error()) //
550 << "VaultWithdraw: final withdrawal share-value mismatch;"
551 << " computed=" << assetsWithdrawn.getText()
552 << " assetsAvailable=" << allAvailable.getText();
553 }
554 assetsWithdrawn = allAvailable;
555 }
556
557 auto const assetsDelivered = subtractTransferFee(assetsWithdrawn, rate);
558 if (assetsWithdrawn > beast::kZero && assetsDelivered == beast::kZero)
559 {
560 JLOG(j_.debug()) << "VaultWithdraw: transfer fee reduces the payout to zero";
561 return tecPRECISION_LOSS;
562 }
563
564 if (finalPayout && getVaultVersion(vault) != VaultVersion::FixedPrecision)
565 {
566 // Do not let dust accumulate in the Vault.
567 vault->at(sfAssetsTotal) = 0;
568 vault->at(sfAssetsAvailable) = 0;
569 }
570 else if (auto const ter = adjustVaultCash(vault, -assetsWithdrawn, j_); !isTesSuccess(ter))
571 {
572 return ter; // LCOV_EXCL_LINE
573 }
574 view().update(vault);
575
576 auto const& vaultAccount = vault->at(sfAccount);
577
578 // Transfer shares from depositor to vault.
579 if (auto const ter = accountSend(
580 view(), accountID_, vaultAccount, sharesRedeemed, j_, {}, WaiveTransferFee::Yes);
581 !isTesSuccess(ter))
582 return ter;
583
584 // Try to remove MPToken for shares, if the account balance is zero. Vault
585 // pseudo-account will never set lsfMPTAuthorized, so we ignore flags.
586 // Keep MPToken if holder is the vault owner.
587 if (accountID_ != vault->at(sfOwner))
588 {
589 if (auto const ter =
590 removeEmptyHolding(applyViewContext, accountID_, sharesRedeemed.asset(), j_);
591 isTesSuccess(ter))
592 {
593 JLOG(j_.debug()) //
594 << "VaultWithdraw: removed empty MPToken for vault shares"
595 << " MPTID=" << to_string(mptIssuanceID) //
596 << " account=" << toBase58(accountID_);
597 }
598 else if (ter != tecHAS_OBLIGATIONS)
599 {
600 // LCOV_EXCL_START
601 JLOG(j_.error()) //
602 << "VaultWithdraw: failed to remove MPToken for vault shares"
603 << " MPTID=" << to_string(mptIssuanceID) //
604 << " account=" << toBase58(accountID_) //
605 << " with result: " << transToken(ter);
606 return ter;
607 // LCOV_EXCL_STOP
608 }
609 // else quietly ignore, account balance is not zero
610 }
611
612 associateAsset(*vault, vaultAsset);
613
614 return doWithdraw(
615 applyViewContext,
617 dstAcct,
618 vaultAccount,
620 assetsDelivered,
621 assetsWithdrawn,
622 j_);
623}
624
625void
627{
628 // No transaction-specific invariants yet (future work).
629}
630
631bool
633 STTx const&,
634 TER,
635 XRPAmount,
636 ReadView const&,
637 beast::Journal const&)
638{
639 // No transaction-specific invariants yet (future work).
640 return true;
641}
642
643} // 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.
constexpr bool native() const
Definition Asset.h:125
AccountID const & getIssuer() const
Definition Asset.cpp:21
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
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:182
std::string getText() const override
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
AccountID const accountID_
Definition Transactor.h:166
XRPAmount preFeeBalance_
Definition Transactor.h:167
ApplyContext & ctx_
Definition Transactor.h:162
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.
TER doApply() override
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)
constexpr Zero kZero
Definition Zero.h:30
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
Definition Indexes.cpp:565
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
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.
Definition View.cpp:508
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)
@ tefINTERNAL
Definition TER.h:167
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.
Definition AccountID.cpp:95
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:259
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)
Definition base_uint.h:658
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
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.
Definition View.cpp:438
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.
Definition AccountID.h:34
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
constexpr std::uint8_t kVaultStrategyFirstComeFirstServe
Vault withdrawal policies.
Definition Protocol.h:308
TERSubset< CanCvtToTER > TER
Definition TER.h:657
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.
@ tecWRONG_ASSET
Definition TER.h:371
@ tecPSEUDO_ACCOUNT
Definition TER.h:373
@ tecNO_ENTRY
Definition TER.h:317
@ tecPATH_DRY
Definition TER.h:305
@ tecINTERNAL
Definition TER.h:321
@ tecTOO_SOON
Definition TER.h:329
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecHAS_OBLIGATIONS
Definition TER.h:328
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 &currency, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
@ tesSUCCESS
Definition TER.h:253
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.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46