xrpld
Loading...
Searching...
No Matches
AMMWithdraw.cpp
1#include <xrpl/tx/transactors/dex/AMMWithdraw.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/core/ServiceRegistry.h>
8#include <xrpl/ledger/Sandbox.h>
9#include <xrpl/ledger/helpers/AMMHelpers.h>
10#include <xrpl/ledger/helpers/AccountRootHelpers.h>
11#include <xrpl/ledger/helpers/MPTokenHelpers.h>
12#include <xrpl/ledger/helpers/RippleStateHelpers.h>
13#include <xrpl/ledger/helpers/TokenHelpers.h>
14#include <xrpl/protocol/AMMCore.h>
15#include <xrpl/protocol/AccountID.h>
16#include <xrpl/protocol/Asset.h>
17#include <xrpl/protocol/Feature.h>
18#include <xrpl/protocol/IOUAmount.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/Issue.h>
21#include <xrpl/protocol/Keylet.h>
22#include <xrpl/protocol/LedgerFormats.h>
23#include <xrpl/protocol/MPTIssue.h>
24#include <xrpl/protocol/SField.h>
25#include <xrpl/protocol/STAmount.h>
26#include <xrpl/protocol/STLedgerEntry.h>
27#include <xrpl/protocol/STTx.h>
28#include <xrpl/protocol/TER.h>
29#include <xrpl/protocol/TxFlags.h>
30#include <xrpl/protocol/XRPAmount.h>
31#include <xrpl/tx/Transactor.h>
32
33#include <algorithm>
34#include <bit>
35#include <cstdint>
36#include <exception>
37#include <optional>
38#include <stdexcept>
39#include <tuple>
40#include <utility>
41
42namespace xrpl {
43
44bool
46{
47 auto const amount = ctx.tx[~sfAmount];
48 auto const amount2 = ctx.tx[~sfAmount2];
49
50 return ctx.rules.enabled(featureMPTokensV2) ||
51 (!ctx.tx[sfAsset].holds<MPTIssue>() && !ctx.tx[sfAsset2].holds<MPTIssue>() &&
52 !(amount && amount->holds<MPTIssue>()) && !(amount2 && amount2->holds<MPTIssue>()));
53}
54
57{
58 return tfAMMWithdrawMask;
59}
60
63{
64 auto const flags = ctx.tx.getFlags();
65
66 auto const amount = ctx.tx[~sfAmount];
67 auto const amount2 = ctx.tx[~sfAmount2];
68 auto const ePrice = ctx.tx[~sfEPrice];
69 auto const lpTokens = ctx.tx[~sfLPTokenIn];
70 // Valid combinations are:
71 // LPTokens
72 // tfWithdrawAll
73 // Amount
74 // tfOneAssetWithdrawAll & Amount
75 // Amount and Amount2
76 // Amount and LPTokens
77 // Amount and EPrice
78 if (std::popcount(flags & tfWithdrawSubTx) != 1)
79 {
80 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid flags.";
81 return temMALFORMED;
82 }
83 if (ctx.tx.isFlag(tfLPToken))
84 {
85 if (!lpTokens || amount || amount2 || ePrice)
86 return temMALFORMED;
87 }
88 else if (ctx.tx.isFlag(tfWithdrawAll))
89 {
90 if (lpTokens || amount || amount2 || ePrice)
91 return temMALFORMED;
92 }
93 else if (ctx.tx.isFlag(tfOneAssetWithdrawAll) || ctx.tx.isFlag(tfSingleAsset))
94 {
95 if (!amount || lpTokens || amount2 || ePrice)
96 return temMALFORMED;
97 }
98 else if (ctx.tx.isFlag(tfTwoAsset))
99 {
100 if (!amount || !amount2 || lpTokens || ePrice)
101 return temMALFORMED;
102 }
103 else if (ctx.tx.isFlag(tfOneAssetLPToken))
104 {
105 if (!amount || !lpTokens || amount2 || ePrice)
106 return temMALFORMED;
107 }
108 else if (ctx.tx.isFlag(tfLimitLPToken))
109 {
110 if (!amount || !ePrice || lpTokens || amount2)
111 return temMALFORMED;
112 }
113
114 auto const asset = ctx.tx[sfAsset];
115 auto const asset2 = ctx.tx[sfAsset2];
116 if (auto const res = invalidAMMAssetPair(asset, asset2))
117 {
118 JLOG(ctx.j.debug()) << "AMM Withdraw: Invalid asset pair.";
119 return res;
120 }
121
122 if (amount && amount2 && amount->asset() == amount2->asset())
123 {
124 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens, same issue." << amount->asset() << " "
125 << amount2->asset();
126 return temBAD_AMM_TOKENS;
127 }
128
129 if (lpTokens && *lpTokens <= beast::kZero)
130 {
131 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens.";
132 return temBAD_AMM_TOKENS;
133 }
134
135 if (amount)
136 {
137 if (auto const res = invalidAMMAmount(
138 *amount,
139 std::make_optional(std::make_pair(asset, asset2)),
140 ((flags & (tfOneAssetWithdrawAll | tfOneAssetLPToken)) != 0u) || ePrice))
141 {
142 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid Asset1Out";
143 return res;
144 }
145 }
146
147 if (amount2)
148 {
149 if (auto const res =
150 invalidAMMAmount(*amount2, std::make_optional(std::make_pair(asset, asset2))))
151 {
152 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid Asset2OutAmount";
153 return res;
154 }
155 }
156
157 if (ePrice)
158 {
159 if (auto const res = invalidAMMAmount(*ePrice))
160 {
161 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid EPrice";
162 return res;
163 }
164 }
165
166 return tesSUCCESS;
167}
168
171 STAmount const& lpTokens,
172 std::optional<STAmount> const& tokensIn,
173 std::uint32_t flags)
174{
175 if ((flags & (tfWithdrawAll | tfOneAssetWithdrawAll)) != 0u)
176 return lpTokens;
177 return tokensIn;
178}
179
180TER
182{
183 auto const accountID = ctx.tx[sfAccount];
184
185 auto const ammSle = ctx.view.read(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2]));
186 if (!ammSle)
187 {
188 JLOG(ctx.j.debug()) << "AMM Withdraw: Invalid asset pair.";
189 return terNO_AMM;
190 }
191
192 auto const amount = ctx.tx[~sfAmount];
193 auto const amount2 = ctx.tx[~sfAmount2];
194
195 auto const expected = ammHolds(
196 ctx.view,
197 *ammSle,
198 amount ? amount->asset() : std::optional<Asset>{},
199 amount2 ? amount2->asset() : std::optional<Asset>{},
202 ctx.j);
203 if (!expected)
204 return expected.error();
205 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
206 if (lptAMMBalance == beast::kZero)
207 return tecAMM_EMPTY;
208 if (amountBalance <= beast::kZero || amount2Balance <= beast::kZero ||
209 lptAMMBalance < beast::kZero)
210 {
211 // LCOV_EXCL_START
212 JLOG(ctx.j.debug()) << "AMM Withdraw: reserves or tokens balance is zero.";
213 return tecINTERNAL;
214 // LCOV_EXCL_STOP
215 }
216
217 auto const ammAccountID = ammSle->getAccountID(sfAccount);
218
219 auto const checkAmount = [&](std::optional<STAmount> const& amount,
220 auto const& balance) -> TER {
221 if (amount)
222 {
223 if (amount > balance)
224 {
225 JLOG(ctx.j.debug())
226 << "AMM Withdraw: withdrawing more than the balance, " << *amount;
227 return tecAMM_BALANCE;
228 }
229 // WeakAuth - MPToken is created if it doesn't exist.
230 if (auto const ter =
231 requireAuth(ctx.view, amount->asset(), accountID, AuthType::WeakAuth))
232 {
233 JLOG(ctx.j.debug())
234 << "AMM Withdraw: account is not authorized, " << amount->asset();
235 return ter;
236 }
237 if (ctx.view.rules().enabled(fixCleanup3_3_0))
238 {
239 if (auto const ret = checkWithdrawFreeze(
240 ctx.view, ammAccountID, accountID, accountID, amount->asset()))
241 {
242 JLOG(ctx.j.debug()) << "AMM Withdraw: frozen, " << to_string(accountID) << " "
243 << to_string(amount->asset());
244 return ret;
245 }
246 }
247 else
248 {
249 // AMM account or currency frozen
250 if (auto const ter = checkFrozen(ctx.view, ammAccountID, amount->asset());
251 !isTesSuccess(ter))
252 {
253 JLOG(ctx.j.debug())
254 << "AMM Withdraw: AMM account or currency is frozen or locked, "
255 << to_string(accountID);
256 return ter;
257 }
258 // Account frozen
259 if (auto const ter = checkIndividualFrozen(ctx.view, accountID, amount->asset());
260 !isTesSuccess(ter))
261 {
262 JLOG(ctx.j.debug())
263 << "AMM Withdraw: account is frozen or locked, " << to_string(accountID)
264 << " " << to_string(amount->asset());
265 return ter;
266 }
267 }
268 }
269 return tesSUCCESS;
270 };
271
272 if (auto const ter = checkAmount(amount, amountBalance))
273 return ter;
274
275 if (auto const ter = checkAmount(amount2, amount2Balance))
276 return ter;
277
278 auto const lpTokens = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j);
279 auto const lpTokensWithdraw = tokensWithdraw(lpTokens, ctx.tx[~sfLPTokenIn], ctx.tx.getFlags());
280
281 if (lpTokens <= beast::kZero)
282 {
283 JLOG(ctx.j.debug()) << "AMM Withdraw: tokens balance is zero.";
284 return tecAMM_BALANCE;
285 }
286
287 if (lpTokensWithdraw && lpTokensWithdraw->asset() != lpTokens.asset())
288 {
289 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid LPTokens.";
290 return temBAD_AMM_TOKENS;
291 }
292
293 if (lpTokensWithdraw && *lpTokensWithdraw > lpTokens)
294 {
295 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens.";
297 }
298
299 if (auto const ePrice = ctx.tx[~sfEPrice]; ePrice && ePrice->asset() != lpTokens.asset())
300 {
301 JLOG(ctx.j.debug()) << "AMM Withdraw: invalid EPrice.";
302 return temBAD_AMM_TOKENS;
303 }
304
305 if ((ctx.tx.getFlags() & (tfLPToken | tfWithdrawAll)) != 0u)
306 {
307 if (auto const ter = checkAmount(amountBalance, amountBalance))
308 return ter;
309 if (auto const ter = checkAmount(amount2Balance, amount2Balance))
310 return ter;
311 }
312
313 return tesSUCCESS;
314}
315
318{
319 // When the withdrawer is the issuer of a pool asset, the issuer can
320 // always receive their own token — even when the pool is frozen.
321 // Use IgnoreFreeze so ammHolds returns real balances instead of zero.
322 if (!ctx_.view().rules().enabled(fixCleanup3_3_0))
324
325 auto const asset1 = Asset{ctx_.tx[sfAsset]};
326 auto const asset2 = Asset{ctx_.tx[sfAsset2]};
327 if (!asset1.native() && accountID_ == asset1.getIssuer())
329 if (!asset2.native() && accountID_ == asset2.getIssuer())
331
333}
334
337{
338 auto const amount = ctx_.tx[~sfAmount];
339 auto const amount2 = ctx_.tx[~sfAmount2];
340 auto const ePrice = ctx_.tx[~sfEPrice];
341 auto ammSle = sb.peek(keylet::amm(ctx_.tx[sfAsset], ctx_.tx[sfAsset2]));
342 if (!ammSle)
343 return {tecINTERNAL, false}; // LCOV_EXCL_LINE
344 auto const ammAccountID = (*ammSle)[sfAccount];
345 auto const accountSle = sb.read(keylet::account(ammAccountID));
346 if (!accountSle)
347 return {tecINTERNAL, false}; // LCOV_EXCL_LINE
348 auto const lpTokens = ammLPHolds(ctx_.view(), *ammSle, ctx_.tx[sfAccount], ctx_.journal);
349 auto const lpTokensWithdraw =
350 tokensWithdraw(lpTokens, ctx_.tx[~sfLPTokenIn], ctx_.tx.getFlags());
351
352 // Due to rounding, the LPTokenBalance of the last LP
353 // might not match the LP's trustline balance
354 if (auto const res = verifyAndAdjustLPTokenBalance(sb, lpTokens, ammSle, accountID_); !res)
355 return {res.error(), false}; // LCOV_EXCL_LINE
356
357 auto const tfee = getTradingFee(ctx_.view(), *ammSle, accountID_);
358
359 auto const freezeHandling = issuerFreezeHandling();
360
361 auto const expected = ammHolds(
362 sb,
363 *ammSle,
364 amount ? amount->asset() : std::optional<Asset>{},
365 amount2 ? amount2->asset() : std::optional<Asset>{},
366 freezeHandling,
368 ctx_.journal);
369 if (!expected)
370 return {expected.error(), false};
371 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
372 auto const subTxType = ctx_.tx.getFlags() & tfWithdrawSubTx;
373
374 auto dispatchToWithdraw = [&,
375 &amountBalance = amountBalance,
376 &amount2Balance = amount2Balance,
377 &lptAMMBalance = lptAMMBalance] -> std::pair<TER, STAmount> {
378 if (subTxType & tfTwoAsset)
379 {
380 return equalWithdrawLimit(
381 sb,
382 *ammSle,
383 ammAccountID,
384 amountBalance,
385 amount2Balance,
386 lptAMMBalance,
387 *amount,
388 *amount2,
389 tfee);
390 }
391 if (subTxType & tfOneAssetLPToken || subTxType & tfOneAssetWithdrawAll)
392 {
394 sb,
395 *ammSle,
396 ammAccountID,
397 amountBalance,
398 lptAMMBalance,
399 *amount,
400 *lpTokensWithdraw,
401 tfee);
402 }
403 if (subTxType & tfLimitLPToken)
404 {
406 sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, *ePrice, tfee);
407 }
408 if (subTxType & tfSingleAsset)
409 {
410 return singleWithdraw(
411 sb, *ammSle, ammAccountID, amountBalance, lptAMMBalance, *amount, tfee);
412 }
413 if (subTxType & tfLPToken || subTxType & tfWithdrawAll)
414 {
415 return equalWithdrawTokens(
416 sb,
417 *ammSle,
418 ammAccountID,
419 amountBalance,
420 amount2Balance,
421 lptAMMBalance,
422 lpTokens,
423 *lpTokensWithdraw,
424 tfee);
425 }
426 // should not happen.
427 // LCOV_EXCL_START
428 JLOG(j_.error()) << "AMM Withdraw: invalid options.";
430 // LCOV_EXCL_STOP
431 };
432
433 auto const [result, newLPTokenBalance] = [&] -> std::pair<TER, STAmount> {
434 try
435 {
436 return dispatchToWithdraw();
437 }
438 catch (std::runtime_error const& e)
439 {
440 // Defense in-depth for amount overflow/out-of-range: the withdrawal
441 // counterpart of the AMMDeposit guard. Unlike deposit, no known
442 // withdraw path can throw here - preclaim bounds the requested
443 // amounts by the pool balances, and the only historical throw
444 // (denom == 0 in singleWithdrawEPrice) is guarded under
445 // fixCleanup3_3_0. Gated by fixCleanup3_4_0 to preserve the
446 // legacy tefEXCEPTION pre-amendment.
447 if (!sb.rules().enabled(fixCleanup3_4_0))
448 throw;
449 // LCOV_EXCL_START
450 JLOG(j_.error()) << "AMMWithdraw: amount out of range " << e.what();
452 // LCOV_EXCL_STOP
453 }
454 }();
455
456 if (!isTesSuccess(result))
457 return {result, false};
458
459 if (sb.rules().enabled(fixCleanup3_3_0) && sb.rules().enabled(fixAMMv1_3))
460 {
461 if (auto const ter = checkAMMPrecisionLoss(
462 sb, ammAccountID, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], newLPTokenBalance, j_);
463 !isTesSuccess(ter))
464 {
465 return {ter, false};
466 }
467 }
468
469 auto const res = deleteAMMAccountIfEmpty(
470 sb, ammSle, newLPTokenBalance, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_);
471 // LCOV_EXCL_START
472 if (!res.second)
473 return {res.first, false};
474 // LCOV_EXCL_STOP
475
476 JLOG(ctx_.journal.trace()) << "AMM Withdraw: tokens " << to_string(newLPTokenBalance.iou())
477 << " " << to_string(lpTokens.iou()) << " "
478 << to_string(lptAMMBalance.iou());
479
480 return {tesSUCCESS, true};
481}
482
483TER
485{
486 // This is the ledger view that we work against. Transactions are applied
487 // as we go on processing transactions.
488 Sandbox sb(&ctx_.view());
489
490 auto const result = applyGuts(sb);
491 if (result.second)
492 sb.apply(ctx_.rawView());
493
494 return result.first;
495}
496
499 Sandbox& view,
500 SLE const& ammSle,
501 AccountID const& ammAccount,
502 STAmount const& amountBalance,
503 STAmount const& amountWithdraw,
504 std::optional<STAmount> const& amount2Withdraw,
505 STAmount const& lpTokensAMMBalance,
506 STAmount const& lpTokensWithdraw,
507 std::uint16_t tfee)
508{
509 TER ter;
510 STAmount newLPTokenBalance;
511 std::tie(ter, newLPTokenBalance, std::ignore, std::ignore) = withdraw(
512 view,
513 ammSle,
514 ammAccount,
515 std::nullopt,
517 amountBalance,
518 amountWithdraw,
519 amount2Withdraw,
520 lpTokensAMMBalance,
521 lpTokensWithdraw,
522 tfee,
528 j_);
529 return {ter, newLPTokenBalance};
530}
531
534 Sandbox& view,
535 SLE const& ammSle,
536 AccountID const& ammAccount,
537 std::optional<AccountID> const& clawbackIssuer,
538 AccountID const& account,
539 STAmount const& amountBalance,
540 STAmount const& amountWithdraw,
541 std::optional<STAmount> const& amount2Withdraw,
542 STAmount const& lpTokensAMMBalance,
543 STAmount const& lpTokensWithdraw,
544 std::uint16_t tfee,
545 FreezeHandling freezeHandling,
546 AuthHandling authHandling,
547 ReserveHandling reserveHandling,
548 WithdrawAll withdrawAll,
549 XRPAmount const& priorBalance,
550 beast::Journal const& journal)
551{
552 auto const lpTokens = ammLPHolds(view, ammSle, account, journal);
553 auto const expected = ammHolds(
554 view, ammSle, amountWithdraw.asset(), std::nullopt, freezeHandling, authHandling, journal);
555 // LCOV_EXCL_START
556 if (!expected)
557 return {expected.error(), STAmount{}, STAmount{}, STAmount{}};
558 // LCOV_EXCL_STOP
559 auto const [curBalance, curBalance2, _] = *expected;
560 (void)_;
561
562 auto const [amountWithdrawActual, amount2WithdrawActual, lpTokensWithdrawActual] =
564 if (withdrawAll == WithdrawAll::No)
565 {
567 amountBalance,
568 amountWithdraw,
569 amount2Withdraw,
570 lpTokensAMMBalance,
571 lpTokensWithdraw,
572 tfee,
574 }
575 return std::make_tuple(amountWithdraw, amount2Withdraw, lpTokensWithdraw);
576 }();
577
578 if (lpTokensWithdrawActual <= beast::kZero || lpTokensWithdrawActual > lpTokens)
579 {
580 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, invalid LP tokens: "
581 << lpTokensWithdrawActual << " " << lpTokens << " "
582 << lpTokensAMMBalance;
584 }
585
586 // Should not happen since the only LP on last withdraw
587 // has the balance set to the lp token trustline balance.
588 if (lpTokensWithdrawActual > lpTokensAMMBalance)
589 {
590 // LCOV_EXCL_START
591 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw, unexpected LP tokens: "
592 << lpTokensWithdrawActual << " " << lpTokens << " "
593 << lpTokensAMMBalance;
594 return {tecINTERNAL, STAmount{}, STAmount{}, STAmount{}};
595 // LCOV_EXCL_STOP
596 }
597
598 // Withdrawing one side of the pool
599 if ((amountWithdrawActual == curBalance && amount2WithdrawActual != curBalance2) ||
600 (amount2WithdrawActual == curBalance2 && amountWithdrawActual != curBalance))
601 {
602 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw one side of the pool "
603 << " curBalance: " << curBalance << " " << amountWithdrawActual
604 << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance "
605 << lpTokensAMMBalance;
606 return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}};
607 }
608
609 // May happen if withdrawing an amount close to one side of the pool
610 if (lpTokensWithdrawActual == lpTokensAMMBalance &&
611 (amountWithdrawActual != curBalance || amount2WithdrawActual != curBalance2))
612 {
613 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw all tokens "
614 << " curBalance: " << curBalance << " " << amountWithdrawActual
615 << " curBalance2: " << amount2WithdrawActual.value_or(STAmount{0})
616 << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance "
617 << lpTokensAMMBalance;
618 return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}};
619 }
620
621 // Withdrawing more than the pool's balance
622 if (amountWithdrawActual > curBalance || amount2WithdrawActual > curBalance2)
623 {
624 JLOG(journal.debug()) << "AMM Withdraw: withdrawing more than the pool's balance "
625 << " curBalance: " << curBalance << " " << amountWithdrawActual
626 << " curBalance2: " << curBalance2 << " "
627 << (amount2WithdrawActual ? *amount2WithdrawActual : STAmount{})
628 << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance "
629 << lpTokensAMMBalance;
630 return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}};
631 }
632
633 // Updated pool state must be valid - either all balances are zero
634 // or all balances are non-zero.
635 if (view.rules().enabled(featureMPTokensV2))
636 {
637 bool const newBalanceZero = (curBalance - amountWithdrawActual) == beast::kZero;
638 bool const newBalance2Zero =
639 (curBalance2 - amount2WithdrawActual.value_or(curBalance2.asset())) == beast::kZero;
640 bool const newLPTokensZero = (lpTokensAMMBalance - lpTokensWithdrawActual) == beast::kZero;
641 // newBalance2Zero can be zero if that side of the pool is frozen.
642 // ignore newBalance2Zero if one-sided withdrawal.
643 bool const valid = [&] {
644 if (!amount2WithdrawActual)
645 return newBalanceZero == newLPTokensZero;
646 return newBalanceZero == newBalance2Zero && newBalance2Zero == newLPTokensZero;
647 }();
648 if (!valid)
649 {
650 JLOG(journal.debug()) << "AMM Withdraw: some balances are zero"
651 << " curBalance: " << curBalance << " " << amountWithdrawActual
652 << " curBalance2: " << curBalance2 << " "
653 << (amount2WithdrawActual ? *amount2WithdrawActual : STAmount{})
654 << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance "
655 << lpTokensAMMBalance;
656 return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}};
657 }
658 }
659
660 // Check the reserve in case a trustline or MPT has to be created
661 bool const enabledFixAmMv12 = view.rules().enabled(fixAMMv1_2);
662 // If seated after a call to sufficientReserve() then MPToken must be
663 // authorized
664 std::optional<Keylet> mptokenKey;
665 auto const sufficientReserve = [&](Asset const& asset) -> TER {
666 mptokenKey = std::nullopt;
667 if (!enabledFixAmMv12 || isXRP(asset))
668 return tesSUCCESS;
669 bool const assetNotExists = asset.visit(
670 [&](Issue const& issue) { return !view.exists(keylet::trustLine(account, issue)); },
671 [&](MPTIssue const& issue) {
672 auto const issuanceKey = keylet::mptokenIssuance(issue);
673 mptokenKey = keylet::mptoken(issuanceKey.key, account);
674 if (!view.exists(*mptokenKey))
675 return true;
676 mptokenKey = std::nullopt;
677 return false;
678 });
679 if (assetNotExists)
680 {
681 // Intentionally ignore the reserve check for AMMClawback, so the
682 // holder can not avoid clawback by deleting the trustline/MPToken
683 // and keeping a low spendable balance. AMMClawback has a higher
684 // priority than the reserve check.
685 if (view.rules().enabled(fixCleanup3_4_0) &&
686 reserveHandling == ReserveHandling::IgnoreReserve)
687 return tesSUCCESS;
688
689 auto const sleAccount = view.peek(keylet::account(account));
690 if (!sleAccount)
691 return tecINTERNAL; // LCOV_EXCL_LINE
692
693 auto const balance = (*sleAccount)[sfBalance]->xrp();
694 // See also TrustSet::doApply() and MPTokenAuthorize::authorize()
695 XRPAmount const reserve(
696 (ownerCount(sleAccount, journal) < 2)
698 : accountReserve(view, sleAccount, journal, {.ownerCountDelta = 1}));
699
700 auto const balanceAdj = std::max(priorBalance, balance);
701 if (balanceAdj < reserve)
703 }
704 return tesSUCCESS;
705 };
706
707 // Create MPToken if it doesn't exist
708 auto const createMPToken = [&](Asset const& asset) -> TER {
709 // If mptoken is seated then must authorize
710 if (mptokenKey && account != asset.getIssuer())
711 {
712 auto const& mptIssue = asset.get<MPTIssue>();
713 std::uint32_t createFlags = 0;
714 if (auto const err = requireAuth(view, mptIssue, account, AuthType::WeakAuth);
715 !isTesSuccess(err))
716 {
717 if (authHandling != AuthHandling::IgnoreAuth || err != tecNO_AUTH)
718 {
719 // Unreachable in practice. Normal withdraws (authHandling
720 // != IgnoreAuth) are rejected for unauthorized holders in
721 // preclaim, so they never get here. Under clawback
722 // (IgnoreAuth) requireAuth returns a non-tecNO_AUTH error
723 // (e.g. tecEXPIRED) only for a domain-authorized MPT, but no
724 // such MPT can be in an AMM pool: a directly domain-gated
725 // RequireAuth MPT fails AMMCreate/deposit with tecNO_AUTH,
726 // and vault shares (whose recursive auth could yield
727 // tecEXPIRED) are rejected by AMMCreate with tecWRONG_ASSET.
728 return err; // LCOV_EXCL_LINE
729 }
730
731 // AMMClawback ignores authorization so the issuer can recover
732 // MPT locked in the pool even if the holder deleted their
733 // MPToken. Only auto-authorize the recreated MPToken for the
734 // clawback issuer's own asset: authorization is granted by an
735 // asset's issuer, and the clawback transaction is signed by
736 // that issuer only for its own asset. For a paired asset issued
737 // by a different account, recreate the MPToken *unauthorized* so
738 // the clawback does not grant authorization on behalf of that
739 // issuer (which would bypass its lsfMPTRequireAuth). The holder
740 // still receives the paired asset (accountSend only requires the
741 // MPToken to exist, not to be authorized); the balance remains
742 // gated by its issuer until that issuer authorizes it.
743 if (clawbackIssuer && asset.getIssuer() == *clawbackIssuer)
744 createFlags = lsfMPTAuthorized;
745 }
746
747 if (auto const err = checkCreateMPT(view, mptIssue, account, {}, createFlags, journal);
748 !isTesSuccess(err))
749 {
750 // checkCreateMPT only fails on tecDIR_FULL (its source line is
751 // itself LCOV-excluded) or a missing account, which cannot
752 // happen since `account` is the withdrawing LP. Defensive and
753 // unreachable in practice.
754 return err; // LCOV_EXCL_LINE
755 }
756 }
757 return tesSUCCESS;
758 };
759
760 if (auto const err = sufficientReserve(amountWithdrawActual.asset()))
761 return {err, STAmount{}, STAmount{}, STAmount{}};
762
763 if (auto const res = createMPToken(amountWithdrawActual.asset()); !isTesSuccess(res))
764 return {res, STAmount{}, STAmount{}, STAmount{}};
765
766 // Withdraw amountWithdraw
767 auto res = accountSend(
768 view, ammAccount, account, amountWithdrawActual, journal, {}, WaiveTransferFee::Yes);
769 if (!isTesSuccess(res))
770 {
771 // LCOV_EXCL_START
772 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw " << amountWithdrawActual;
773 return {res, STAmount{}, STAmount{}, STAmount{}};
774 // LCOV_EXCL_STOP
775 }
776
777 // Withdraw amount2Withdraw
778 if (amount2WithdrawActual)
779 {
780 if (auto const err = sufficientReserve(amount2WithdrawActual->asset()); !isTesSuccess(err))
781 return {err, STAmount{}, STAmount{}, STAmount{}};
782
783 if (auto const res = createMPToken(amount2WithdrawActual->asset()); !isTesSuccess(res))
784 return {res, STAmount{}, STAmount{}, STAmount{}};
785
786 res = accountSend(
787 view, ammAccount, account, *amount2WithdrawActual, journal, {}, WaiveTransferFee::Yes);
788 if (!isTesSuccess(res))
789 {
790 // LCOV_EXCL_START
791 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw " << *amount2WithdrawActual;
792 return {res, STAmount{}, STAmount{}, STAmount{}};
793 // LCOV_EXCL_STOP
794 }
795 }
796
797 // Withdraw LP tokens
798 res = redeemIOU(
799 view, account, lpTokensWithdrawActual, lpTokensWithdrawActual.get<Issue>(), journal);
800 if (!isTesSuccess(res))
801 {
802 // LCOV_EXCL_START
803 JLOG(journal.debug()) << "AMM Withdraw: failed to withdraw LPTokens";
804 return {res, STAmount{}, STAmount{}, STAmount{}};
805 // LCOV_EXCL_STOP
806 }
807
808 return std::make_tuple(
810 lpTokensAMMBalance - lpTokensWithdrawActual,
811 amountWithdrawActual,
812 amount2WithdrawActual);
813}
814
815static STAmount
817 Rules const& rules,
818 STAmount const& lptAMMBalance,
819 STAmount const& lpTokensWithdraw,
820 WithdrawAll withdrawAll)
821{
822 if (!rules.enabled(fixAMMv1_3) || withdrawAll == WithdrawAll::Yes)
823 return lpTokensWithdraw;
824 return adjustLPTokens(lptAMMBalance, lpTokensWithdraw, IsDeposit::No);
825}
826
832 Sandbox& view,
833 SLE const& ammSle,
834 AccountID const& ammAccount,
835 STAmount const& amountBalance,
836 STAmount const& amount2Balance,
837 STAmount const& lptAMMBalance,
838 STAmount const& lpTokens,
839 STAmount const& lpTokensWithdraw,
840 std::uint16_t tfee)
841{
842 TER ter;
843 STAmount newLPTokenBalance;
844 std::tie(ter, newLPTokenBalance, std::ignore, std::ignore) = equalWithdrawTokens(
845 view,
846 ammSle,
848 std::nullopt,
849 ammAccount,
850 amountBalance,
851 amount2Balance,
852 lptAMMBalance,
853 lpTokens,
854 lpTokensWithdraw,
855 tfee,
861 ctx_.journal);
862 return {ter, newLPTokenBalance};
863}
864
867 Sandbox& sb,
868 SLE::pointer const ammSle,
869 STAmount const& lpTokenBalance,
870 Asset const& asset1,
871 Asset const& asset2,
872 beast::Journal const& journal)
873{
874 TER ter;
875 bool updateBalance = true;
876 if (lpTokenBalance == beast::kZero)
877 {
878 ter = deleteAMMAccount(sb, asset1, asset2, journal);
879 if (!isTesSuccess(ter) && ter != tecINCOMPLETE)
880 return {ter, false}; // LCOV_EXCL_LINE
881
882 updateBalance = (ter == tecINCOMPLETE);
883 }
884
885 if (updateBalance)
886 {
887 ammSle->setFieldAmount(sfLPTokenBalance, lpTokenBalance);
888 sb.update(ammSle);
889 }
890
891 return {ter, true};
892}
893
899 Sandbox& view,
900 SLE const& ammSle,
901 AccountID const account,
902 std::optional<AccountID> const& clawbackIssuer,
903 AccountID const& ammAccount,
904 STAmount const& amountBalance,
905 STAmount const& amount2Balance,
906 STAmount const& lptAMMBalance,
907 STAmount const& lpTokens,
908 STAmount const& lpTokensWithdraw,
909 std::uint16_t tfee,
910 FreezeHandling freezeHandling,
911 AuthHandling authHandling,
912 ReserveHandling reserveHandling,
913 WithdrawAll withdrawAll,
914 XRPAmount const& priorBalance,
915 beast::Journal const& journal)
916{
917 try
918 {
919 // Withdrawing all tokens in the pool
920 if (lpTokensWithdraw == lptAMMBalance)
921 {
922 return withdraw(
923 view,
924 ammSle,
925 ammAccount,
926 clawbackIssuer,
927 account,
928 amountBalance,
929 amountBalance,
930 amount2Balance,
931 lptAMMBalance,
932 lpTokensWithdraw,
933 tfee,
934 freezeHandling,
935 authHandling,
936 reserveHandling,
938 priorBalance,
939 journal);
940 }
941
942 auto const tokensAdj =
943 adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, withdrawAll);
944 if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero)
945 return {tecAMM_INVALID_TOKENS, STAmount{}, STAmount{}, std::nullopt};
946 // the adjusted tokens are factored in
947 auto const frac = divide(tokensAdj, lptAMMBalance, noIssue());
948 auto const amountWithdraw =
949 getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No);
950 auto const amount2Withdraw =
951 getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No);
952 // LP is making equal withdrawal by tokens but the requested amount
953 // of LP tokens is likely too small and results in one-sided pool
954 // withdrawal due to round off. Fail so the user withdraws
955 // more tokens.
956 if (amountWithdraw == beast::kZero || amount2Withdraw == beast::kZero)
957 return {tecAMM_FAILED, STAmount{}, STAmount{}, STAmount{}};
958
959 return withdraw(
960 view,
961 ammSle,
962 ammAccount,
963 clawbackIssuer,
964 account,
965 amountBalance,
966 amountWithdraw,
967 amount2Withdraw,
968 lptAMMBalance,
969 tokensAdj,
970 tfee,
971 freezeHandling,
972 authHandling,
973 reserveHandling,
974 withdrawAll,
975 priorBalance,
976 journal);
977 }
978 // LCOV_EXCL_START
979 catch (std::exception const& e)
980 {
981 JLOG(journal.error()) << "AMMWithdraw::equalWithdrawTokens exception " << e.what();
982 }
983 return {tecINTERNAL, STAmount{}, STAmount{}, STAmount{}};
984 // LCOV_EXCL_STOP
985}
986
1015 Sandbox& view,
1016 SLE const& ammSle,
1017 AccountID const& ammAccount,
1018 STAmount const& amountBalance,
1019 STAmount const& amount2Balance,
1020 STAmount const& lptAMMBalance,
1021 STAmount const& amount,
1022 STAmount const& amount2,
1023 std::uint16_t tfee)
1024{
1025 auto frac = Number{amount} / amountBalance;
1026 auto tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::No);
1027 if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero)
1028 return {tecAMM_INVALID_TOKENS, STAmount{}};
1029 // factor in the adjusted tokens
1030 frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac);
1031 auto const amount2Withdraw = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No);
1032 if (amount2Withdraw <= amount2)
1033 {
1034 return withdraw(
1035 view,
1036 ammSle,
1037 ammAccount,
1038 amountBalance,
1039 amount,
1040 amount2Withdraw,
1041 lptAMMBalance,
1042 tokensAdj,
1043 tfee);
1044 }
1045
1046 frac = Number{amount2} / amount2Balance;
1047 auto amountWithdraw = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No);
1048 tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::No);
1049 if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero)
1050 return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE
1051 // factor in the adjusted tokens
1052 frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac);
1053 amountWithdraw = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::No);
1054 if (!view.rules().enabled(fixAMMv1_3))
1055 {
1056 // LCOV_EXCL_START
1057 XRPL_ASSERT(
1058 amountWithdraw <= amount,
1059 "xrpl::AMMWithdraw::equalWithdrawLimit : maximum amountWithdraw");
1060 // LCOV_EXCL_STOP
1061 }
1062 else if (amountWithdraw > amount)
1063 {
1064 return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE
1065 }
1066 return withdraw(
1067 view,
1068 ammSle,
1069 ammAccount,
1070 amountBalance,
1071 amountWithdraw,
1072 amount2,
1073 lptAMMBalance,
1074 tokensAdj,
1075 tfee);
1076}
1077
1086 Sandbox& view,
1087 SLE const& ammSle,
1088 AccountID const& ammAccount,
1089 STAmount const& amountBalance,
1090 STAmount const& lptAMMBalance,
1091 STAmount const& amount,
1092 std::uint16_t tfee)
1093{
1094 auto const tokens = adjustLPTokensIn(
1095 view.rules(),
1096 lptAMMBalance,
1097 lpTokensIn(amountBalance, amount, lptAMMBalance, tfee),
1098 isWithdrawAll(ctx_.tx));
1099 if (tokens == beast::kZero)
1100 {
1101 if (!view.rules().enabled(fixAMMv1_3))
1102 {
1103 return {tecAMM_FAILED, STAmount{}}; // LCOV_EXCL_LINE
1104 }
1105
1106 return {tecAMM_INVALID_TOKENS, STAmount{}};
1107 }
1108 // factor in the adjusted tokens
1109 auto const [tokensAdj, amountWithdrawAdj] =
1110 adjustAssetOutByTokens(view.rules(), amountBalance, amount, lptAMMBalance, tokens, tfee);
1111 if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero)
1112 return {tecAMM_INVALID_TOKENS, STAmount{}}; // LCOV_EXCL_LINE
1113 return withdraw(
1114 view,
1115 ammSle,
1116 ammAccount,
1117 amountBalance,
1118 amountWithdrawAdj,
1119 std::nullopt,
1120 lptAMMBalance,
1121 tokensAdj,
1122 tfee);
1123}
1124
1138 Sandbox& view,
1139 SLE const& ammSle,
1140 AccountID const& ammAccount,
1141 STAmount const& amountBalance,
1142 STAmount const& lptAMMBalance,
1143 STAmount const& amount,
1144 STAmount const& lpTokensWithdraw,
1145 std::uint16_t tfee)
1146{
1147 auto const tokensAdj =
1148 adjustLPTokensIn(view.rules(), lptAMMBalance, lpTokensWithdraw, isWithdrawAll(ctx_.tx));
1149 if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::kZero)
1150 return {tecAMM_INVALID_TOKENS, STAmount{}};
1151 // the adjusted tokens are factored in
1152 auto const amountWithdraw = ammAssetOut(amountBalance, lptAMMBalance, tokensAdj, tfee);
1153 if (amount == beast::kZero || amountWithdraw >= amount)
1154 {
1155 return withdraw(
1156 view,
1157 ammSle,
1158 ammAccount,
1159 amountBalance,
1160 amountWithdraw,
1161 std::nullopt,
1162 lptAMMBalance,
1163 tokensAdj,
1164 tfee);
1165 }
1166
1167 return {tecAMM_FAILED, STAmount{}};
1168}
1169
1192 Sandbox& view,
1193 SLE const& ammSle,
1194 AccountID const& ammAccount,
1195 STAmount const& amountBalance,
1196 STAmount const& lptAMMBalance,
1197 STAmount const& amount,
1198 STAmount const& ePrice,
1199 std::uint16_t tfee)
1200{
1201 // LPTokens is asset in => E = t / a and formula (8) is:
1202 // a = A*(t1**2 + t1*(f - 2))/(t1*f - 1)
1203 // substitute a as t/E =>
1204 // t/E = A*(t1**2 + t1*(f - 2))/(t1*f - 1), t1=t/T => t = t1*T
1205 // t1*T/E = A*((t/T)**2 + t*(f - 2)/T)/(t*f/T - 1) =>
1206 // T/E = A*(t1 + f-2)/(t1*f - 1) =>
1207 // T*(t1*f - 1) = A*E*(t1 + f - 2) =>
1208 // t1*T*f - T = t1*A*E + A*E*(f - 2) =>
1209 // t1*(T*f - A*E) = T + A*E*(f - 2) =>
1210 // t = T*(T + A*E*(f - 2))/(T*f - A*E)
1211 Number const ae = amountBalance * ePrice;
1212 auto const f = getFee(tfee);
1213 auto const denom = lptAMMBalance * f - ae;
1214 // fixCleanup3_3_0: guard against division by zero
1215 // when ePrice == lptAMMBalance*f/amountBalance
1216 if (view.rules().enabled(fixCleanup3_3_0) && denom == beast::kZero)
1217 return {tecAMM_FAILED, STAmount{}};
1218 auto const tokNoRoundCb = [&] {
1219 return lptAMMBalance * (lptAMMBalance + ae * (f - 2)) / denom;
1220 };
1221 auto const tokProdCb = [&] { return (lptAMMBalance + ae * (f - 2)) / denom; };
1222 auto const tokensAdj =
1223 getRoundedLPTokens(view.rules(), tokNoRoundCb, lptAMMBalance, tokProdCb, IsDeposit::No);
1224 if (tokensAdj <= beast::kZero)
1225 {
1226 if (!view.rules().enabled(fixAMMv1_3))
1227 {
1228 return {tecAMM_FAILED, STAmount{}};
1229 }
1230
1231 return {tecAMM_INVALID_TOKENS, STAmount{}};
1232 }
1233 auto const amtNoRoundCb = [&] { return tokensAdj / ePrice; };
1234 auto const amtProdCb = [&] { return tokensAdj / ePrice; };
1235 // the adjusted tokens are factored in
1236 auto const amountWithdraw =
1237 getRoundedAsset(view.rules(), amtNoRoundCb, amount, amtProdCb, IsDeposit::No);
1238 if (amount == beast::kZero || amountWithdraw >= amount)
1239 {
1240 return withdraw(
1241 view,
1242 ammSle,
1243 ammAccount,
1244 amountBalance,
1245 amountWithdraw,
1246 std::nullopt,
1247 lptAMMBalance,
1248 tokensAdj,
1249 tfee);
1250 }
1251
1252 return {tecAMM_FAILED, STAmount{}};
1253}
1254
1257{
1258 if ((tx[sfFlags] & (tfWithdrawAll | tfOneAssetWithdrawAll)) != 0u)
1259 return WithdrawAll::Yes;
1260 return WithdrawAll::No;
1261}
1262void
1264{
1265 // No transaction-specific invariants yet (future work).
1266}
1267
1268bool
1270{
1271 // No transaction-specific invariants yet (future work).
1272 return true;
1273}
1274
1275} // 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
FreezeHandling issuerFreezeHandling() const
Returns IgnoreFreeze when the withdrawer is the issuer of a pool asset (post-fixCleanup3_3_0),...
static std::tuple< TER, STAmount, STAmount, std::optional< STAmount > > withdraw(Sandbox &view, SLE const &ammSle, AccountID const &ammAccount, std::optional< AccountID > const &clawbackIssuer, AccountID const &account, STAmount const &amountBalance, STAmount const &amountWithdraw, std::optional< STAmount > const &amount2Withdraw, STAmount const &lpTokensAMMBalance, STAmount const &lpTokensWithdraw, std::uint16_t tfee, FreezeHandling freezeHandling, AuthHandling authHandling, ReserveHandling reserveHandling, WithdrawAll withdrawAll, XRPAmount const &priorBalance, beast::Journal const &journal)
Withdraw requested assets and token from AMM into LP account.
static std::pair< TER, bool > deleteAMMAccountIfEmpty(Sandbox &sb, SLE::pointer const ammSle, STAmount const &lpTokenBalance, Asset const &asset1, Asset const &asset2, beast::Journal const &journal)
static WithdrawAll isWithdrawAll(STTx const &tx)
Check from the flags if it's withdraw all.
static NotTEC preflight(PreflightContext const &ctx)
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
static TER preclaim(PreclaimContext const &ctx)
TER doApply() override
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
std::pair< TER, STAmount > equalWithdrawLimit(Sandbox &view, SLE const &ammSle, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount2Balance, STAmount const &lptAMMBalance, STAmount const &amount, STAmount const &amount2, std::uint16_t tfee)
Withdraw both assets (Asset1Out, Asset2Out) with the constraints on the maximum amount of each asset ...
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.
std::pair< TER, STAmount > singleWithdrawTokens(Sandbox &view, SLE const &ammSle, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &lptAMMBalance, STAmount const &amount, STAmount const &lpTokensWithdraw, std::uint16_t tfee)
Single asset withdrawal (Asset1Out, LPTokens) proportional to the share specified by tokens.
std::pair< TER, STAmount > singleWithdraw(Sandbox &view, SLE const &ammSle, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &lptAMMBalance, STAmount const &amount, std::uint16_t tfee)
Single asset withdrawal (Asset1Out) equivalent to the amount specified in Asset1Out.
static bool checkExtraFeatures(PreflightContext const &ctx)
std::pair< TER, bool > applyGuts(Sandbox &view)
static std::tuple< TER, STAmount, STAmount, std::optional< STAmount > > equalWithdrawTokens(Sandbox &view, SLE const &ammSle, AccountID const account, std::optional< AccountID > const &clawbackIssuer, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount2Balance, STAmount const &lptAMMBalance, STAmount const &lpTokens, STAmount const &lpTokensWithdraw, std::uint16_t tfee, FreezeHandling freezeHandling, AuthHandling authHandling, ReserveHandling reserveHandling, WithdrawAll withdrawAll, XRPAmount const &priorBalance, beast::Journal const &journal)
Equal-asset withdrawal (LPTokens) of some AMM instance pools shares represented by the number of LPTo...
std::pair< TER, STAmount > singleWithdrawEPrice(Sandbox &view, SLE const &ammSle, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &lptAMMBalance, STAmount const &amount, STAmount const &ePrice, std::uint16_t tfee)
Withdraw single asset (Asset1Out, EPrice) with two constraints.
A currency issued by an account.
Definition Issue.h:18
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.
Rules controlling protocol behavior.
Definition Rules.h:40
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFlag(std::uint32_t) const
Definition STObject.cpp:511
std::uint32_t getFlags() const
Definition STObject.cpp:517
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
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
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
Rules const & rules() const override
Returns the tx processing rules.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
T make_optional(T... args)
T make_pair(T... args)
T make_tuple(T... args)
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
Definition AMMCore.cpp:96
STAmount divide(STAmount const &amount, Rate const &rate)
Definition Rate2.cpp:69
@ terNO_AMM
Definition TER.h:229
STAmount ammLPHolds(ReadView const &view, Asset const &asset1, Asset const &asset2, AccountID const &ammAccount, AccountID const &lpAccount, beast::Journal const j)
Get the balance of LP tokens.
FreezeHandling
Controls the treatment of frozen account balances.
WithdrawAll
AMMWithdraw implements AMM withdraw Transactor.
TER checkIndividualFrozen(ReadView const &view, AccountID const &account, Asset const &asset)
std::uint32_t ownerCount(SLE::ConstRef sle, beast::Journal j, std::int32_t ownerCountAdj=0)
Return number of the objects which reserve is covered by the account(sle) (so called "ownercount").
TER checkCreateMPT(xrpl::ApplyView &view, xrpl::MPTIssue const &mptIssue, xrpl::AccountID const &holder, SLE::Ref sponsorSle, std::uint32_t flags, beast::Journal j)
bool isXRP(AccountID const &c)
Definition AccountID.h:84
Number adjustFracByTokens(Rules const &rules, STAmount const &lptAMMBalance, STAmount const &tokens, Number const &frac)
Find a fraction of tokens after the tokens are adjusted.
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
Definition AMMCore.cpp:81
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
ReserveHandling
Controls whether the recipient owner-reserve check is enforced when auto-creating a trustline or MPTo...
static std::optional< STAmount > tokensWithdraw(STAmount const &lpTokens, std::optional< STAmount > const &tokensIn, std::uint32_t flags)
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
STAmount ammAssetOut(STAmount const &assetBalance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset withdrawal by tokens.
STAmount getRoundedLPTokens(Rules const &rules, STAmount const &balance, Number const &frac, IsDeposit isDeposit)
Round AMM deposit/withdrawal LPToken amount.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
STLedgerEntry SLE
static STAmount adjustLPTokensIn(Rules const &rules, STAmount const &lptAMMBalance, STAmount const &lpTokensWithdraw, WithdrawAll withdrawAll)
std::pair< STAmount, STAmount > adjustAssetOutByTokens(Rules const &rules, STAmount const &balance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &tokens, std::uint16_t tfee)
TER deleteAMMAccount(Sandbox &view, Asset const &asset, Asset const &asset2, beast::Journal j)
Delete trustlines to AMM.
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.
STAmount getRoundedAsset(Rules const &rules, STAmount const &balance, A const &frac, IsDeposit isDeposit)
Round AMM equal deposit/withdrawal amount.
Definition AMMHelpers.h:586
AuthHandling
Controls the treatment of unauthorized MPT balances.
TER checkAMMPrecisionLoss(Number const &poolProductMean, STAmount const &newLPTokenBalance)
Check AMM pool product invariant after an AMM operation that changes LP tokens (deposit/withdraw/claw...
std::expected< bool, TER > verifyAndAdjustLPTokenBalance(Sandbox &sb, STAmount const &lpTokens, SLE::pointer const &ammSle, AccountID const &account)
Due to rounding, the LPTokenBalance of the last LP might not match the LP's trustline balance.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
std::tuple< STAmount, std::optional< STAmount >, STAmount > adjustAmountsByLPTokens(STAmount const &amountBalance, STAmount const &amount, std::optional< STAmount > const &amount2, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee, IsDeposit isDeposit)
Calls adjustLPTokens() and adjusts deposit or withdraw amounts if the adjusted LP tokens are less tha...
TER redeemIOU(ApplyView &view, AccountID const &account, STAmount const &amount, Issue const &issue, beast::Journal j)
@ temBAD_AMM_TOKENS
Definition TER.h:117
@ temMALFORMED
Definition TER.h:75
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
STAmount lpTokensIn(STAmount const &asset1Balance, STAmount const &asset1Withdraw, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's withdraw amount.
Number getFee(std::uint16_t tfee)
Convert to the fee from the basis points.
Definition AMMCore.h:83
TERSubset< CanCvtToTER > TER
Definition TER.h:657
XRPAmount accountReserve(ReadView const &view, SLE::ConstRef sle, beast::Journal j, Adjustment adj={})
Returns the account reserve, in drops.
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.
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:118
@ tecAMM_EMPTY
Definition TER.h:343
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecAMM_FAILED
Definition TER.h:341
@ tecINCOMPLETE
Definition TER.h:346
@ tecNO_AUTH
Definition TER.h:311
@ tecINTERNAL
Definition TER.h:321
@ tecAMM_BALANCE
Definition TER.h:340
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
TER createMPToken(ApplyView &view, MPTID const &mptIssuanceID, AccountID const &account, SLE::Ref sponsorSle, std::uint32_t const flags)
std::expected< std::tuple< STAmount, STAmount, STAmount >, TER > ammHolds(ReadView const &view, SLE const &ammSle, std::optional< Asset > const &optAsset1, std::optional< Asset > const &optAsset2, FreezeHandling freezeHandling, AuthHandling authHandling, beast::Journal const j)
Get AMM pool and LP token balances.
std::uint16_t getTradingFee(ReadView const &view, SLE const &ammSle, AccountID const &account)
Get AMM trading fee for the given account.
constexpr FlagValue tfWithdrawSubTx
Definition TxFlags.h:415
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.
@ tesSUCCESS
Definition TER.h:253
T popcount(T... args)
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
T tie(T... args)
T what(T... args)