xrpld
Loading...
Searching...
No Matches
AMMHelpers.cpp
1#include <xrpl/ledger/helpers/AMMHelpers.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/basics/safe_cast.h>
7#include <xrpl/beast/utility/Journal.h>
8#include <xrpl/beast/utility/Zero.h>
9#include <xrpl/beast/utility/instrumentation.h>
10#include <xrpl/ledger/ApplyView.h>
11#include <xrpl/ledger/ReadView.h>
12#include <xrpl/ledger/Sandbox.h>
13#include <xrpl/ledger/View.h>
14#include <xrpl/ledger/helpers/MPTokenHelpers.h>
15#include <xrpl/ledger/helpers/RippleStateHelpers.h>
16#include <xrpl/ledger/helpers/TokenHelpers.h>
17#include <xrpl/protocol/AMMCore.h>
18#include <xrpl/protocol/AccountID.h>
19#include <xrpl/protocol/AmountConversions.h>
20#include <xrpl/protocol/Asset.h>
21#include <xrpl/protocol/Feature.h>
22#include <xrpl/protocol/Indexes.h>
23#include <xrpl/protocol/Issue.h>
24#include <xrpl/protocol/LedgerFormats.h>
25#include <xrpl/protocol/MPTIssue.h>
26#include <xrpl/protocol/Protocol.h>
27#include <xrpl/protocol/Rules.h>
28#include <xrpl/protocol/SField.h>
29#include <xrpl/protocol/STAmount.h>
30#include <xrpl/protocol/STArray.h>
31#include <xrpl/protocol/STLedgerEntry.h>
32#include <xrpl/protocol/TER.h>
33
34#include <algorithm>
35#include <chrono>
36#include <cstdint>
37#include <expected>
38#include <functional>
39#include <optional>
40#include <tuple>
41#include <utility>
42
43namespace xrpl {
44
46ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue)
47{
48 // AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance
49 auto const rounding =
51 NumberRoundModeGuard const g(rounding);
52 auto const tokens = root2(asset1 * asset2);
53 return toSTAmount(lptIssue, tokens);
54}
55
56/*
57 * Equation 3:
58 * t = T * [(b/B - (sqrt(f2**2 - b/(B*f1)) - f2)) /
59 * (1 + sqrt(f2**2 - b/(B*f1)) - f2)]
60 * where f1 = 1 - tfee, f2 = (1 - tfee/2)/f1
61 */
62STAmount
64 STAmount const& asset1Balance,
65 STAmount const& asset1Deposit,
66 STAmount const& lptAMMBalance,
67 std::uint16_t tfee)
68{
69 auto const f1 = feeMult(tfee);
70 auto const f2 = feeMultHalf(tfee) / f1;
71 Number const r = asset1Deposit / asset1Balance;
72 auto const c = root2(f2 * f2 + r / f1) - f2;
73 if (!isFeatureEnabled(fixAMMv1_3))
74 {
75 auto const t = lptAMMBalance * (r - c) / (1 + c);
76 return toSTAmount(lptAMMBalance.asset(), t);
77 }
78
79 // minimize tokens out
80 auto const frac = (r - c) / (1 + c);
81 return multiply(lptAMMBalance, frac, Number::RoundingMode::Downward);
82}
83
84/* Equation 4 solves equation 3 for b:
85 * Let f1 = 1 - tfee, f2 = (1 - tfee/2)/f1, t1 = t/T, t2 = 1 + t1, R = b/B
86 * then
87 * t1 = [R - sqrt(f2**2 + R/f1) + f2] / [1 + sqrt(f2**2 + R/f1] - f2] =>
88 * sqrt(f2**2 + R/f1)*(t1 + 1) = R + f2 + t1*f2 - t1 =>
89 * sqrt(f2**2 + R/f1)*t2 = R + t2*f2 - t1 =>
90 * sqrt(f2**2 + R/f1) = R/t2 + f2 - t1/t2, let d = f2 - t1/t2 =>
91 * sqrt(f2**2 + R/f1) = R/t2 + d =>
92 * f2**2 + R/f1 = (R/t2)**2 +2*d*R/t2 + d**2 =>
93 * (R/t2)**2 + R*(2*d/t2 - 1/f1) + d**2 - f2**2 = 0
94 */
95STAmount
97 STAmount const& asset1Balance,
98 STAmount const& lptAMMBalance,
99 STAmount const& lpTokens,
100 std::uint16_t tfee)
101{
102 auto const f1 = feeMult(tfee);
103 auto const f2 = feeMultHalf(tfee) / f1;
104 auto const t1 = lpTokens / lptAMMBalance;
105 auto const t2 = 1 + t1;
106 auto const d = f2 - t1 / t2;
107 auto const a = 1 / (t2 * t2);
108 auto const b = 2 * d / t2 - 1 / f1;
109 auto const c = d * d - f2 * f2;
110 if (!isFeatureEnabled(fixAMMv1_3))
111 {
112 return toSTAmount(asset1Balance.asset(), asset1Balance * solveQuadraticEq(a, b, c));
113 }
114
115 // maximize deposit
116 auto const frac = solveQuadraticEq(a, b, c);
117 return multiply(asset1Balance, frac, Number::RoundingMode::Upward);
118}
119
120/* Equation 7:
121 * t = T * (c - sqrt(c**2 - 4*R))/2
122 * where R = b/B, c = R*fee + 2 - fee
123 */
124STAmount
126 STAmount const& asset1Balance,
127 STAmount const& asset1Withdraw,
128 STAmount const& lptAMMBalance,
129 std::uint16_t tfee)
130{
131 Number const fr = asset1Withdraw / asset1Balance;
132 auto const f1 = getFee(tfee);
133 auto const c = fr * f1 + 2 - f1;
134 if (!isFeatureEnabled(fixAMMv1_3))
135 {
136 auto const t = lptAMMBalance * (c - root2(c * c - 4 * fr)) / 2;
137 return toSTAmount(lptAMMBalance.asset(), t);
138 }
139
140 // maximize tokens in
141 auto const frac = (c - root2(c * c - 4 * fr)) / 2;
142 return multiply(lptAMMBalance, frac, Number::RoundingMode::Upward);
143}
144
145/* Equation 8 solves equation 7 for b:
146 * c - 2*t/T = sqrt(c**2 - 4*R) =>
147 * c**2 - 4*c*t/T + 4*t**2/T**2 = c**2 - 4*R =>
148 * -4*c*t/T + 4*t**2/T**2 = -4*R =>
149 * -c*t/T + t**2/T**2 = -R -=>
150 * substitute c = R*f + 2 - f =>
151 * -(t/T)*(R*f + 2 - f) + (t/T)**2 = -R, let t1 = t/T =>
152 * -t1*R*f -2*t1 +t1*f +t1**2 = -R =>
153 * R = (t1**2 + t1*(f - 2)) / (t1*f - 1)
154 */
155STAmount
157 STAmount const& assetBalance,
158 STAmount const& lptAMMBalance,
159 STAmount const& lpTokens,
160 std::uint16_t tfee)
161{
162 auto const f = getFee(tfee);
163 Number const t1 = lpTokens / lptAMMBalance;
164 if (!isFeatureEnabled(fixAMMv1_3))
165 {
166 auto const b = assetBalance * (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1);
167 return toSTAmount(assetBalance.asset(), b);
168 }
169
170 // minimize withdraw
171 auto const frac = (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1);
172 return multiply(assetBalance, frac, Number::RoundingMode::Downward);
173}
174
175Number
176square(Number const& n)
177{
178 return n * n;
179}
180
181STAmount
182adjustLPTokens(STAmount const& lptAMMBalance, STAmount const& lpTokens, IsDeposit isDeposit)
183{
184 // Force rounding downward to ensure adjusted tokens are less or equal
185 // to requested tokens.
187 if (isDeposit == IsDeposit::Yes)
188 return (lptAMMBalance + lpTokens) - lptAMMBalance;
189 return (lpTokens - lptAMMBalance) + lptAMMBalance;
190}
191
194 STAmount const& amountBalance,
195 STAmount const& amount,
196 std::optional<STAmount> const& amount2,
197 STAmount const& lptAMMBalance,
198 STAmount const& lpTokens,
199 std::uint16_t tfee,
200 IsDeposit isDeposit)
201{
202 // AMMv1_3 amendment adjusts tokens and amounts in deposit/withdraw
203 if (isFeatureEnabled(fixAMMv1_3))
204 return std::make_tuple(amount, amount2, lpTokens);
205
206 auto const lpTokensActual = adjustLPTokens(lptAMMBalance, lpTokens, isDeposit);
207
208 if (lpTokensActual == beast::kZero)
209 {
210 auto const amount2Opt = amount2 ? std::make_optional(STAmount{}) : std::nullopt;
211 return std::make_tuple(STAmount{}, amount2Opt, lpTokensActual);
212 }
213
214 if (lpTokensActual < lpTokens)
215 {
216 // Equal trade
217 if (amount2)
218 {
219 Number const fr = lpTokensActual / lpTokens;
220 auto const amountActual = toSTAmount(amount.asset(), fr * amount);
221 auto const amount2Actual = toSTAmount(amount2->asset(), fr * *amount2);
222 return std::make_tuple(amountActual, amount2Actual, lpTokensActual);
223 }
224
225 // Single trade
226 auto const amountActual = isDeposit == IsDeposit::Yes
227 ? ammAssetIn(amountBalance, lptAMMBalance, lpTokensActual, tfee)
228 : ammAssetOut(amountBalance, lptAMMBalance, lpTokensActual, tfee);
229
230 return std::make_tuple(amountActual, std::nullopt, lpTokensActual);
231 }
232
233 XRPL_ASSERT(
234 lpTokensActual == lpTokens, "xrpl::adjustAmountsByLPTokens : LP tokens match actual");
235
236 return {amount, amount2, lpTokensActual};
237}
238
239Number
240solveQuadraticEq(Number const& a, Number const& b, Number const& c)
241{
242 return (-b + root2(b * b - 4 * a * c)) / (2 * a);
243}
244
245// Minimize takerGets or takerPays
247solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c)
248{
249 auto const d = b * b - 4 * a * c;
250 if (d < 0)
251 return std::nullopt;
252 // use numerically stable citardauq formula for quadratic equation solution
253 // https://people.csail.mit.edu/bkph/articles/Quadratics.pdf
254 if (b > 0)
255 {
256 return (2 * c) / (-b - root2(d));
257 }
258
259 return (2 * c) / (-b + root2(d));
260}
261
262STAmount
263multiply(STAmount const& amount, Number const& frac, Number::RoundingMode rm)
264{
265 NumberRoundModeGuard const g(rm);
266 auto const t = amount * frac;
267 return toSTAmount(amount.asset(), t, rm);
268}
269
270STAmount
272 Rules const& rules,
273 std::function<Number()> const& noRoundCb,
274 STAmount const& balance,
275 std::function<Number()> const& productCb,
276 IsDeposit isDeposit)
277{
278 if (!rules.enabled(fixAMMv1_3))
279 return toSTAmount(balance.asset(), noRoundCb());
280
281 auto const rm = detail::getAssetRounding(isDeposit);
282 if (isDeposit == IsDeposit::Yes)
283 return multiply(balance, productCb(), rm);
284 NumberRoundModeGuard const g(rm);
285 return toSTAmount(balance.asset(), productCb(), rm);
286}
287
288STAmount
290 Rules const& rules,
291 STAmount const& balance,
292 Number const& frac,
293 IsDeposit isDeposit)
294{
295 if (!rules.enabled(fixAMMv1_3))
296 return toSTAmount(balance.asset(), balance * frac);
297
298 auto const rm = detail::getLPTokenRounding(isDeposit);
299 auto const tokens = multiply(balance, frac, rm);
300 return adjustLPTokens(balance, tokens, isDeposit);
301}
302
303STAmount
305 Rules const& rules,
306 std::function<Number()> const& noRoundCb,
307 STAmount const& lptAMMBalance,
308 std::function<Number()> const& productCb,
309 IsDeposit isDeposit)
310{
311 if (!rules.enabled(fixAMMv1_3))
312 return toSTAmount(lptAMMBalance.asset(), noRoundCb());
313
314 auto const tokens = [&] {
315 auto const rm = detail::getLPTokenRounding(isDeposit);
316 if (isDeposit == IsDeposit::Yes)
317 {
318 NumberRoundModeGuard const g(rm);
319 return toSTAmount(lptAMMBalance.asset(), productCb(), rm);
320 }
321 return multiply(lptAMMBalance, productCb(), rm);
322 }();
323 return adjustLPTokens(lptAMMBalance, tokens, isDeposit);
324}
325
328 Rules const& rules,
329 STAmount const& balance,
330 STAmount const& amount,
331 STAmount const& lptAMMBalance,
332 STAmount const& tokens,
333 std::uint16_t tfee)
334{
335 if (!rules.enabled(fixAMMv1_3))
336 return {tokens, amount};
337 auto assetAdj = ammAssetIn(balance, lptAMMBalance, tokens, tfee);
338 auto tokensAdj = tokens;
339 // Rounding didn't work the right way.
340 // Try to adjust the original deposit amount by difference
341 // in adjust and original amount. Then adjust tokens and deposit amount.
342 if (assetAdj > amount)
343 {
344 auto const adjAmount = amount - (assetAdj - amount);
345 auto const t = lpTokensOut(balance, adjAmount, lptAMMBalance, tfee);
346 tokensAdj = adjustLPTokens(lptAMMBalance, t, IsDeposit::Yes);
347 assetAdj = ammAssetIn(balance, lptAMMBalance, tokensAdj, tfee);
348 }
349 return {tokensAdj, std::min(amount, assetAdj)};
350}
351
354 Rules const& rules,
355 STAmount const& balance,
356 STAmount const& amount,
357 STAmount const& lptAMMBalance,
358 STAmount const& tokens,
359 std::uint16_t tfee)
360{
361 if (!rules.enabled(fixAMMv1_3))
362 return {tokens, amount};
363 auto assetAdj = ammAssetOut(balance, lptAMMBalance, tokens, tfee);
364 auto tokensAdj = tokens;
365 // Rounding didn't work the right way.
366 // Try to adjust the original deposit amount by difference
367 // in adjust and original amount. Then adjust tokens and deposit amount.
368 if (assetAdj > amount)
369 {
370 auto const adjAmount = amount - (assetAdj - amount);
371 auto const t = lpTokensIn(balance, adjAmount, lptAMMBalance, tfee);
372 tokensAdj = adjustLPTokens(lptAMMBalance, t, IsDeposit::No);
373 assetAdj = ammAssetOut(balance, lptAMMBalance, tokensAdj, tfee);
374 }
375 return {tokensAdj, std::min(amount, assetAdj)};
376}
377
378Number
380 Rules const& rules,
381 STAmount const& lptAMMBalance,
382 STAmount const& tokens,
383 Number const& frac)
384{
385 if (!rules.enabled(fixAMMv1_3))
386 return frac;
387 return tokens / lptAMMBalance;
388}
389
392 ReadView const& view,
393 AccountID const& ammAccountID,
394 Asset const& asset1,
395 Asset const& asset2,
396 FreezeHandling freezeHandling,
397 AuthHandling authHandling,
398 beast::Journal const j)
399{
400 auto const assetInBalance =
401 accountHolds(view, ammAccountID, asset1, freezeHandling, authHandling, j);
402 auto const assetOutBalance =
403 accountHolds(view, ammAccountID, asset2, freezeHandling, authHandling, j);
404 return std::make_pair(assetInBalance, assetOutBalance);
405}
406
407TER
408checkAMMPrecisionLoss(Number const& poolProductMean, STAmount const& newLPTokenBalance)
409{
410 if (newLPTokenBalance <= beast::kZero)
411 return tesSUCCESS;
412 if (poolProductMean >= newLPTokenBalance)
413 return tesSUCCESS;
414 // Strong check failed. Allow the same relative tolerance as the invariant
415 // checker's weak check. Only return tecPRECISION_LOSS when both fail.
417 poolProductMean, Number{newLPTokenBalance}, kAMMInvariantRelativeTolerance))
418 return tesSUCCESS;
419 return tecPRECISION_LOSS;
420}
421
422TER
424 ReadView const& view,
425 AccountID const& ammAccountID,
426 Asset const& asset1,
427 Asset const& asset2,
428 STAmount const& newLPTokenBalance,
429 beast::Journal const j)
430{
431 if (newLPTokenBalance <= beast::kZero)
432 return tesSUCCESS;
433 auto const [amount, amount2] = ammPoolHolds(
434 view,
435 ammAccountID,
436 asset1,
437 asset2,
440 j);
441 return checkAMMPrecisionLoss(root2(amount * amount2), newLPTokenBalance);
442}
443
444std::expected<std::tuple<STAmount, STAmount, STAmount>, TER>
446 ReadView const& view,
447 SLE const& ammSle,
448 std::optional<Asset> const& optAsset1,
449 std::optional<Asset> const& optAsset2,
450 FreezeHandling freezeHandling,
451 AuthHandling authHandling,
452 beast::Journal const j)
453{
454 auto const assets = [&] -> std::optional<std::pair<Asset, Asset>> {
455 auto const asset1 = ammSle[sfAsset];
456 auto const asset2 = ammSle[sfAsset2];
457 if (optAsset1 && optAsset2)
458 {
460 *optAsset1, *optAsset2, std::make_optional(std::make_pair(asset1, asset2))))
461 {
462 // This error can only be hit if the AMM is corrupted
463 // LCOV_EXCL_START
464 JLOG(j.debug()) << "ammHolds: Invalid optAsset1 or optAsset2 " << *optAsset1 << " "
465 << *optAsset2;
466 return std::nullopt;
467 // LCOV_EXCL_STOP
468 }
469 return std::make_optional(std::make_pair(*optAsset1, *optAsset2));
470 }
471 auto const singleAsset = [&asset1, &asset2, &j](
472 Asset checkIssue,
473 char const* label) -> std::optional<std::pair<Asset, Asset>> {
474 if (checkIssue == asset1)
475 {
476 return std::make_optional(std::make_pair(asset1, asset2));
477 }
478 if (checkIssue == asset2)
479 {
480 return std::make_optional(std::make_pair(asset2, asset1));
481 }
482 // Unreachable unless AMM corrupted.
483 // LCOV_EXCL_START
484 JLOG(j.debug()) << "ammHolds: Invalid " << label << " " << checkIssue;
485 return std::nullopt;
486 // LCOV_EXCL_STOP
487 };
488 if (optAsset1)
489 {
490 return singleAsset(*optAsset1, "optAsset1");
491 }
492 if (optAsset2)
493 {
494 // Cannot have Amount2 without Amount.
495 return singleAsset(*optAsset2, "optAsset2"); // LCOV_EXCL_LINE
496 }
497 return std::make_optional(std::make_pair(asset1, asset2));
498 }();
499 if (!assets)
501 auto const [amount1, amount2] = ammPoolHolds(
502 view,
503 ammSle.getAccountID(sfAccount),
504 assets->first,
505 assets->second,
506 freezeHandling,
507 authHandling,
508 j);
509 return std::make_tuple(amount1, amount2, ammSle[sfLPTokenBalance]);
510}
511
512STAmount
514 ReadView const& view,
515 Asset const& asset1,
516 Asset const& asset2,
517 AccountID const& ammAccount,
518 AccountID const& lpAccount,
519 beast::Journal const j)
520{
521 // This function looks similar to `accountHolds`. However, it only checks if
522 // a LPToken holder has enough balance. On the other hand, `accountHolds`
523 // checks if the underlying assets of LPToken are frozen with the
524 // fixFrozenLPTokenTransfer amendment
525
526 auto const currency = ammLPTCurrency(asset1, asset2);
527 STAmount amount;
528
529 auto const sle = view.read(keylet::trustLine(lpAccount, ammAccount, currency));
530 if (!sle)
531 {
532 amount.clear(Issue{currency, ammAccount});
533 JLOG(j.trace()) << "ammLPHolds: no SLE "
534 << " lpAccount=" << to_string(lpAccount)
535 << " amount=" << amount.getFullText();
536 }
537 else if (isFrozen(view, lpAccount, currency, ammAccount))
538 {
539 amount.clear(Issue{currency, ammAccount});
540 JLOG(j.trace()) << "ammLPHolds: frozen currency "
541 << " lpAccount=" << to_string(lpAccount)
542 << " amount=" << amount.getFullText();
543 }
544 else
545 {
546 amount = sle->getFieldAmount(sfBalance);
547 if (lpAccount > ammAccount)
548 {
549 // Put balance in account terms.
550 amount.negate();
551 }
552 amount.get<Issue>().account = ammAccount;
553
554 JLOG(j.trace()) << "ammLPHolds:"
555 << " lpAccount=" << to_string(lpAccount)
556 << " amount=" << amount.getFullText();
557 }
558
559 return view.balanceHookIOU(lpAccount, ammAccount, amount);
560}
561
562STAmount
564 ReadView const& view,
565 SLE const& ammSle,
566 AccountID const& lpAccount,
567 beast::Journal const j)
568{
569 return ammLPHolds(view, ammSle[sfAsset], ammSle[sfAsset2], ammSle[sfAccount], lpAccount, j);
570}
571
573getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account)
574{
575 using namespace std::chrono;
576 XRPL_ASSERT(ammSle.isFieldPresent(sfAuctionSlot), "xrpl::getTradingFee : auction present");
577 if (ammSle.isFieldPresent(sfAuctionSlot))
578 {
579 auto const& auctionSlot = safeDowncast<STObject const&>(ammSle.peekAtField(sfAuctionSlot));
580 // Not expired
581 if (auto const expiration = auctionSlot[~sfExpiration];
583 expiration)
584 {
585 if (auctionSlot[~sfAccount] == account)
586 return auctionSlot[sfDiscountedFee];
587 if (auctionSlot.isFieldPresent(sfAuthAccounts))
588 {
589 for (auto const& acct : auctionSlot.getFieldArray(sfAuthAccounts))
590 {
591 if (acct[~sfAccount] == account)
592 return auctionSlot[sfDiscountedFee];
593 }
594 }
595 }
596 }
597 return ammSle[sfTradingFee];
598}
599
600STAmount
601ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Asset const& asset)
602{
603 // Get the actual AMM balance without factoring in the balance hook
604 return asset.visit(
605 [&](MPTIssue const& issue) {
606 if (auto const sle = view.read(keylet::mptoken(issue, ammAccountID));
607 sle && !isFrozen(view, ammAccountID, *sle))
608 return STAmount{issue, (*sle)[sfMPTAmount]};
609 return STAmount{asset};
610 },
611 [&](Issue const& issue) {
612 if (isXRP(issue))
613 {
614 if (auto const sle = view.read(keylet::account(ammAccountID)))
615 return (*sle)[sfBalance];
616 }
617 else if (
618 auto const sle =
619 view.read(keylet::trustLine(ammAccountID, issue.account, issue.currency));
620 sle && !isFrozen(view, ammAccountID, issue.currency, issue.account))
621 {
622 STAmount amount = (*sle)[sfBalance];
623 if (ammAccountID > issue.account)
624 amount.negate();
625 amount.get<Issue>().account = issue.account;
626 return amount;
627 }
628 return STAmount{asset};
629 });
630}
631
632static TER
634 Sandbox& sb,
635 AccountID const& ammAccountID,
636 std::uint16_t maxTrustlinesToDelete,
638{
640 sb,
641 keylet::ownerDir(ammAccountID),
642 [&](LedgerEntryType nodeType,
643 UInt256 const&,
645 // Skip AMM and MPToken
646 if (nodeType == ltAMM || nodeType == ltMPTOKEN)
647 return {tesSUCCESS, SkipEntry::Yes};
648
649 if (nodeType == ltRIPPLE_STATE)
650 {
651 // Trustlines must have zero balance
652 if (sleItem->getFieldAmount(sfBalance) != beast::kZero)
653 {
654 // LCOV_EXCL_START
655 JLOG(j.error()) << "deleteAMMObjects: deleting trustline with "
656 "non-zero balance.";
657 return {tecINTERNAL, SkipEntry::No};
658 // LCOV_EXCL_STOP
659 }
660
661 return {deleteAMMTrustLine(sb, sleItem, ammAccountID, j), SkipEntry::No};
662 }
663 // LCOV_EXCL_START
664 JLOG(j.error()) << "deleteAMMObjects: deleting non-trustline or non-MPT " << nodeType;
665 return {tecINTERNAL, SkipEntry::No};
666 // LCOV_EXCL_STOP
667 },
668 j,
669 maxTrustlinesToDelete);
670}
671
672static TER
674{
676 sb,
677 keylet::ownerDir(ammAccountID),
678 [&](LedgerEntryType nodeType,
679 UInt256 const&,
681 // Skip AMM
682 if (nodeType == ltAMM)
683 return {tesSUCCESS, SkipEntry::Yes};
684
685 if (nodeType == ltMPTOKEN)
686 {
687 // MPT must have zero balance
688 if (sleItem->getFieldU64(sfMPTAmount) != 0 ||
689 (*sleItem)[~sfLockedAmount].valueOr(0) != 0)
690 {
691 // LCOV_EXCL_START
692 JLOG(j.error()) << "deleteAMMObjects: deleting MPT with "
693 "non-zero balance.";
694 return {tecINTERNAL, SkipEntry::No};
695 // LCOV_EXCL_STOP
696 }
697
698 return {deleteAMMMPToken(sb, sleItem, ammAccountID, j), SkipEntry::No};
699 }
700 if (nodeType == ltRIPPLE_STATE)
701 {
702 // Trustlines should have been deleted
703 // LCOV_EXCL_START
704 JLOG(j.error()) << "deleteAMMObjects: trustlines should have been deleted";
705 return {tecINTERNAL, SkipEntry::No};
706 // LCOV_EXCL_STOP
707 }
708 // LCOV_EXCL_START
709 JLOG(j.error()) << "deleteAMMObjects: deleting non-trustline or non-MPT " << nodeType;
710 return {tecINTERNAL, SkipEntry::No};
711 // LCOV_EXCL_STOP
712 },
713 j,
714 3); // At most two MPToken plus AMM object
715}
716
717TER
718deleteAMMAccount(Sandbox& sb, Asset const& asset, Asset const& asset2, beast::Journal j)
719{
720 auto const ammSle = sb.peek(keylet::amm(asset, asset2));
721 if (!ammSle)
722 {
723 // LCOV_EXCL_START
724 JLOG(j.error()) << "deleteAMMAccount: AMM object does not exist " << asset << " " << asset2;
725 return tecINTERNAL;
726 // LCOV_EXCL_STOP
727 }
728
729 auto const ammAccountID = (*ammSle)[sfAccount];
730 auto const sleAMMRoot = sb.peek(keylet::account(ammAccountID));
731 if (!sleAMMRoot)
732 {
733 // LCOV_EXCL_START
734 JLOG(j.error()) << "deleteAMMAccount: AMM account does not exist "
735 << to_string(ammAccountID);
736 return tecINTERNAL;
737 // LCOV_EXCL_STOP
738 }
739
740 if (auto const ter = deleteAMMTrustLines(sb, ammAccountID, kMaxDeletableAmmTrustLines, j);
741 !isTesSuccess(ter))
742 return ter;
743
744 // Delete AMM's MPTokens only if all trustlines are deleted. If trustlines
745 // are not deleted then AMM can be re-created with Deposit and
746 // AMM's MPToken(s) must exist.
747 if (auto const ter = deleteAMMMPTokens(sb, ammAccountID, j); !isTesSuccess(ter))
748 return ter;
749
750 auto const ownerDirKeylet = keylet::ownerDir(ammAccountID);
751 if (!sb.dirRemove(ownerDirKeylet, (*ammSle)[sfOwnerNode], ammSle->key(), false))
752 {
753 // LCOV_EXCL_START
754 JLOG(j.error()) << "deleteAMMAccount: failed to remove dir link";
755 return tecINTERNAL;
756 // LCOV_EXCL_STOP
757 }
758 if (sb.exists(ownerDirKeylet) && !sb.emptyDirDelete(ownerDirKeylet))
759 {
760 // LCOV_EXCL_START
761 JLOG(j.error()) << "deleteAMMAccount: cannot delete root dir node of "
762 << toBase58(ammAccountID);
763 return tecINTERNAL;
764 // LCOV_EXCL_STOP
765 }
766
767 sb.erase(ammSle);
768 sb.erase(sleAMMRoot);
769
770 return tesSUCCESS;
771}
772
773void
775 ApplyView const& view,
776 SLE::pointer const& ammSle,
777 AccountID const& account,
778 Asset const& lptAsset,
779 std::uint16_t tfee)
780{
781 auto const& rules = view.rules();
782 // AMM creator gets the voting slot.
783 STArray voteSlots;
784 STObject voteEntry = STObject::makeInnerObject(sfVoteEntry);
785 if (tfee != 0)
786 voteEntry.setFieldU16(sfTradingFee, tfee);
787 voteEntry.setFieldU32(sfVoteWeight, kVoteWeightScaleFactor);
788 voteEntry.setAccountID(sfAccount, account);
789 voteSlots.pushBack(voteEntry);
790 ammSle->setFieldArray(sfVoteSlots, voteSlots);
791 // AMM creator gets the auction slot for free.
792 // AuctionSlot is created on AMMCreate and updated on AMMDeposit
793 // when AMM is in an empty state
794 if (!ammSle->isFieldPresent(sfAuctionSlot))
795 {
796 STObject auctionSlot = STObject::makeInnerObject(sfAuctionSlot);
797 ammSle->set(std::move(auctionSlot));
798 }
799 STObject& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot);
800 auctionSlot.setAccountID(sfAccount, account);
801 // current + sec in 24h
804 .count() +
806 auctionSlot.setFieldU32(sfExpiration, expiration);
807 auctionSlot.setFieldAmount(sfPrice, STAmount{lptAsset, 0});
808 // Set the fee
809 if (tfee != 0)
810 {
811 ammSle->setFieldU16(sfTradingFee, tfee);
812 }
813 else if (ammSle->isFieldPresent(sfTradingFee))
814 {
815 ammSle->makeFieldAbsent(sfTradingFee); // LCOV_EXCL_LINE
816 }
817 if (auto const dfee = tfee / kAuctionSlotDiscountedFeeFraction)
818 {
819 auctionSlot.setFieldU16(sfDiscountedFee, dfee);
820 }
821 else if (auctionSlot.isFieldPresent(sfDiscountedFee))
822 {
823 auctionSlot.makeFieldAbsent(sfDiscountedFee); // LCOV_EXCL_LINE
824 }
825 // Clear stale auth accounts from any previous auction slot holder.
826 if (rules.enabled(fixCleanup3_2_0) && auctionSlot.isFieldPresent(sfAuthAccounts))
827 auctionSlot.makeFieldAbsent(sfAuthAccounts);
828}
829
830std::expected<bool, TER>
831isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount)
832{
833 // Liquidity Provider (LP) must have one LPToken trustline
834 std::uint8_t nLPTokenTrustLines = 0;
835 // AMM account has at most two IOU (pool tokens, not LPToken) trustlines.
836 // One or both trustlines could be to the LP if LP is the issuer,
837 // or a different account if LP is not an issuer. For instance,
838 // if AMM has two tokens USD and EUR and LP is not the issuer of the tokens
839 // then the trustlines are between AMM account and the issuer.
840 // There is one LPToken trustline for each LP. Only remaining LP has
841 // exactly one LPToken trustlines and at most two IOU trustline for each
842 // pool token. One or both tokens could be MPT.
843 std::uint8_t nIOUTrustLines = 0;
844 // There are at most two MPT objects, one for each side of the pool.
845 std::uint8_t nMPT = 0;
846 // There is only one AMM object
847 bool hasAMM = false;
848 // AMM LP has at most three trustlines, at most two MPTs, and only one
849 // AMM object must exist. If there are more than four objects then
850 // it's either an error or there are more than one LP. Ten pages should
851 // be sufficient to include four objects.
852 std::uint8_t limit = 10;
853 auto const root = keylet::ownerDir(ammIssue.account);
854 auto currentIndex = root;
855
856 // Iterate over AMM owner directory objects.
857 while (limit-- >= 1)
858 {
859 auto const ownerDir = view.read(currentIndex);
860 if (!ownerDir)
861 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
862 for (auto const& key : ownerDir->getFieldV256(sfIndexes))
863 {
864 auto const sle = view.read(keylet::child(key));
865 if (!sle)
866 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
867 auto const entryType = sle->getFieldU16(sfLedgerEntryType);
868 // Only one AMM object
869 if (entryType == ltAMM)
870 {
871 if (hasAMM)
872 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
873 hasAMM = true;
874 continue;
875 }
876 if (entryType == ltMPTOKEN)
877 {
878 ++nMPT;
879 continue;
880 }
881 if (entryType != ltRIPPLE_STATE)
882 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
883 auto const lowLimit = sle->getFieldAmount(sfLowLimit);
884 auto const highLimit = sle->getFieldAmount(sfHighLimit);
885 auto const isLPTrustline =
886 lowLimit.getIssuer() == lpAccount || highLimit.getIssuer() == lpAccount;
887 auto const isLPTokenTrustline =
888 lowLimit.asset() == ammIssue || highLimit.asset() == ammIssue;
889
890 // Liquidity Provider trustline
891 if (isLPTrustline)
892 {
893 // LPToken trustline
894 if (isLPTokenTrustline)
895 {
896 // LP has exactly one LPToken trustline
897 if (++nLPTokenTrustLines > 1)
898 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
899 }
900 // AMM account has at most two IOU trustlines
901 else if (++nIOUTrustLines > 2)
902 {
903 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
904 }
905 }
906 // Another Liquidity Provider LPToken trustline
907 else if (isLPTokenTrustline)
908 {
909 return false;
910 }
911 // AMM account has at most two IOU trustlines
912 else if (++nIOUTrustLines > 2)
913 {
914 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
915 }
916 }
917 auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext);
918 if (uNodeNext == 0)
919 {
920 if (nLPTokenTrustLines != 1 || (nIOUTrustLines == 0 && nMPT == 0) ||
921 (nIOUTrustLines > 2 || nMPT > 2) || (nIOUTrustLines + nMPT) > 2)
922 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
923 return true;
924 }
925 currentIndex = keylet::page(root, uNodeNext);
926 }
927 return std::unexpected<TER>(tecINTERNAL); // LCOV_EXCL_LINE
928}
929
930std::expected<bool, TER>
932 Sandbox& sb,
933 STAmount const& lpTokens,
934 SLE::pointer const& ammSle,
935 AccountID const& account)
936{
937 auto const res = isOnlyLiquidityProvider(sb, lpTokens.get<Issue>(), account);
938 if (!res.has_value())
939 {
940 return std::unexpected<TER>(res.error());
941 }
942
943 if (res.value())
944 {
946 lpTokens, ammSle->getFieldAmount(sfLPTokenBalance), Number{1, -3}))
947 {
948 ammSle->setFieldAmount(sfLPTokenBalance, lpTokens);
949 sb.update(ammSle);
950 }
951 else
952 {
953 return std::unexpected<TER>(tecAMM_INVALID_TOKENS); // LCOV_EXCL_LINE
954 }
955 }
956 return true;
957}
958
959} // 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
Stream trace() const
Severity stream access functions.
Definition Journal.h:338
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
bool emptyDirDelete(Keylet const &directory)
Remove the specified directory, if it is empty.
bool dirRemove(Keylet const &directory, std::uint64_t page, UInt256 const &key, bool keepRoot)
Remove an entry from a directory.
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
Definition Asset.h:117
A currency issued by an account.
Definition Issue.h:18
AccountID account
Definition Issue.h:21
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static RoundingMode setround(RoundingMode inMode)
static RoundingMode getround()
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.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
virtual STAmount balanceHookIOU(AccountID const &account, AccountID const &issuer, STAmount const &amount) const
Definition ReadView.h:180
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
constexpr TIss const & get() const
std::string getFullText() const override
void negate()
Definition STAmount.h:586
Asset const & asset() const
Definition STAmount.h:496
void pushBack(STObject const &object)
Definition STArray.h:212
std::shared_ptr< STLedgerEntry > pointer
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
void setFieldArray(SField const &field, STArray const &v)
Definition STObject.cpp:833
STObject & peekFieldObject(SField const &field)
Definition STObject.cpp:475
void setFieldAmount(SField const &field, STAmount const &)
Definition STObject.cpp:803
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
void setFieldU16(SField const &field, std::uint16_t)
Definition STObject.cpp:737
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:79
STBase const & peekAtField(SField const &field) const
Definition STObject.cpp:409
void set(SOTemplate const &)
Definition STObject.cpp:138
std::uint64_t getFieldU64(SField const &field) const
Definition STObject.cpp:607
void setAccountID(SField const &field, AccountID const &)
Definition STObject.cpp:785
AccountID getAccountID(SField const &field) const
Definition STObject.cpp:643
void makeFieldAbsent(SField const &field)
Definition STObject.cpp:550
STAmount const & getFieldAmount(SField const &field) const
Definition STObject.cpp:657
Discardable, editable view to a ledger.
Definition Sandbox.h:18
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
void erase(SLE::Ref sle) override
Remove a peeked SLE.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
bool exists(Keylet const &k) const override
Determine if a state item exists.
T duration_cast(T... args)
T make_optional(T... args)
T make_pair(T... args)
T make_tuple(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
Number::RoundingMode getLPTokenRounding(IsDeposit isDeposit)
Definition AMMHelpers.h:559
Number::RoundingMode getAssetRounding(IsDeposit isDeposit)
Definition AMMHelpers.h:568
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Keylet page(UInt256 const &root, std::uint64_t const index=0) noexcept
A page in a directory.
Definition Indexes.cpp:421
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 child(UInt256 const &key) noexcept
Any item that can be in an owner dir.
Definition Indexes.cpp:239
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
static TER deleteAMMTrustLines(Sandbox &sb, AccountID const &ammAccountID, std::uint16_t maxTrustlinesToDelete, beast::Journal j)
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.
constexpr std::uint32_t kTotalTimeSlotSecs
Definition AMMCore.h:19
FreezeHandling
Controls the treatment of frozen account balances.
Number feeMultHalf(std::uint16_t tfee)
Get fee multiplier (1 - tfee / 2) @tfee trading fee in basis points.
Definition AMMCore.h:114
constexpr std::uint32_t kAuctionSlotDiscountedFeeFraction
Definition AMMCore.h:23
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.
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Asset const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
TER deleteAMMTrustLine(ApplyView &view, SLE::pointer sleState, std::optional< AccountID > const &ammAccountID, beast::Journal j)
Delete trustline to AMM.
std::expected< bool, TER > isOnlyLiquidityProvider(ReadView const &view, Issue const &ammIssue, AccountID const &lpAccount)
Return true if the Liquidity Provider is the only AMM provider, false otherwise.
IsDeposit
Definition AMMHelpers.h:50
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
Definition AMMCore.cpp:81
bool isFeatureEnabled(UInt256 const &feature, bool resultIfNoRules)
Check whether a feature is enabled in the current ledger rules.
Definition Rules.cpp:199
TER deleteAMMMPToken(ApplyView &view, SLE::pointer sleMPT, AccountID const &ammAccountID, beast::Journal j)
Delete AMMs MPToken.
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
Number root(Number f, unsigned d)
Number solveQuadraticEq(Number const &a, Number const &b, Number const &c)
Positive solution for quadratic equation: x = (-b + sqrt(b**2 + 4*a*c))/(2*a).
Currency ammLPTCurrency(Asset const &asset1, Asset const &asset2)
Calculate Liquidity Provider Token (LPT) Currency.
Definition AMMCore.cpp:28
STAmount ammAssetOut(STAmount const &assetBalance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset withdrawal by tokens.
constexpr std::uint16_t kMaxDeletableAmmTrustLines
The maximum number of trustlines to delete as part of AMM account deletion cleanup.
Definition Protocol.h:436
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
std::pair< STAmount, STAmount > ammPoolHolds(ReadView const &view, AccountID const &ammAccountID, Asset const &asset1, Asset const &asset2, FreezeHandling freezeHandling, AuthHandling authHandling, beast::Journal const j)
Get AMM pool balances.
STLedgerEntry SLE
std::pair< STAmount, STAmount > adjustAssetInByTokens(Rules const &rules, STAmount const &balance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &tokens, std::uint16_t tfee)
STAmount ammAccountHolds(ReadView const &view, AccountID const &ammAccountID, Asset const &asset)
Returns total amount held by AMM for the given token.
BaseUInt< 256 > UInt256
Definition base_uint.h:581
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.
static TER deleteAMMMPTokens(Sandbox &sb, AccountID const &ammAccountID, beast::Journal j)
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.
Number feeMult(std::uint16_t tfee)
Get fee multiplier (1 - tfee) @tfee trading fee in basis points.
Definition AMMCore.h:104
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::optional< Number > solveQuadraticEqSmallest(Number const &a, Number const &b, Number const &c)
Solve quadratic equation to find takerGets or takerPays.
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
Returns true if account cannot send or receive tokens of mptIssue because a freeze applies.
Number root2(Number f)
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.
STAmount ammAssetIn(STAmount const &asset1Balance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset deposit given LP Tokens.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
void initializeFeeAuctionVote(ApplyView const &view, SLE::pointer const &ammSle, AccountID const &account, Asset const &lptAsset, std::uint16_t tfee)
Initialize Auction and Voting slots and set the trading/discounted fee.
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...
Dest safeDowncast(Src *s) noexcept
Definition safe_cast.h:84
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
Number const kAMMInvariantRelativeTolerance
Definition AMMHelpers.h:52
LedgerEntryType
Identifiers for on-ledger objects.
bool withinRelativeDistance(Quality const &calcQuality, Quality const &reqQuality, Number const &dist)
Check if the relative distance between the qualities is within the requested distance.
Definition AMMHelpers.h:133
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecINTERNAL
Definition TER.h:321
@ tecPRECISION_LOSS
Definition TER.h:374
STAmount multiply(STAmount const &amount, Number const &frac, Number::RoundingMode rm)
constexpr std::uint32_t kVoteWeightScaleFactor
Definition AMMCore.h:30
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.
Number square(Number const &n)
Return square of n.
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
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
TER cleanupOnAccountDelete(ApplyView &view, Keylet const &ownerDirKeylet, EntryDeleter const &deleter, beast::Journal j, std::optional< std::uint16_t > maxNodesToDelete=std::nullopt)
Cleanup owner directory entries on account delete.
STAmount lpTokensOut(STAmount const &asset1Balance, STAmount const &asset1Deposit, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's deposit amount.
NetClock::time_point parentCloseTime
T time_since_epoch(T... args)
T unexpected(T... args)