xrpld
Loading...
Searching...
No Matches
AMMHelpers.h
1#pragma once
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/ledger/ReadView.h>
7#include <xrpl/ledger/Sandbox.h>
8#include <xrpl/ledger/helpers/RippleStateHelpers.h>
9#include <xrpl/ledger/helpers/TokenHelpers.h>
10#include <xrpl/protocol/AMMCore.h>
11#include <xrpl/protocol/AmountConversions.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/IOUAmount.h>
14#include <xrpl/protocol/Issue.h>
15#include <xrpl/protocol/Quality.h>
16#include <xrpl/protocol/Rules.h>
17#include <xrpl/protocol/STAmount.h>
18#include <xrpl/protocol/STLedgerEntry.h>
19
20#include <expected>
21
22namespace xrpl {
23
24namespace detail {
25
26Number
27reduceOffer(auto const& amount)
28{
29 static Number const kReducedOfferPct(9999, -4);
30
31 // Make sure the result is always less than amount or zero.
33 return amount * kReducedOfferPct;
34}
35
36} // namespace detail
37
38enum class IsDeposit : bool { No = false, Yes = true };
39
41
47STAmount
48ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue);
49
57STAmount
59 STAmount const& asset1Balance,
60 STAmount const& asset1Deposit,
61 STAmount const& lptAMMBalance,
62 std::uint16_t tfee);
63
71STAmount
73 STAmount const& asset1Balance,
74 STAmount const& lptAMMBalance,
75 STAmount const& lpTokens,
76 std::uint16_t tfee);
77
86STAmount
88 STAmount const& asset1Balance,
89 STAmount const& asset1Withdraw,
90 STAmount const& lptAMMBalance,
91 std::uint16_t tfee);
92
100STAmount
102 STAmount const& assetBalance,
103 STAmount const& lptAMMBalance,
104 STAmount const& lpTokens,
105 std::uint16_t tfee);
106
114inline bool
115withinRelativeDistance(Quality const& calcQuality, Quality const& reqQuality, Number const& dist)
116{
117 if (calcQuality == reqQuality)
118 return true;
119 auto const [min, max] = std::minmax(calcQuality, reqQuality);
120 // Relative distance is (max - min)/max. Can't use basic operations
121 // on Quality. Have to use Quality::rate() instead, which
122 // is inverse of quality: (1/max.rate - 1/min.rate)/(1/max.rate)
123 return ((min.rate() - max.rate()) / min.rate()) < dist;
124}
125
133template <typename Amt>
134 requires(
138bool
139withinRelativeDistance(Amt const& calc, Amt const& req, Number const& dist)
140{
141 if (calc == req)
142 return true;
143 auto const [min, max] = std::minmax(calc, req);
144 return ((max - min) / max) < dist;
145}
146
151solveQuadraticEqSmallest(Number const& a, Number const& b, Number const& c);
152
176template <typename TIn, typename TOut>
179 TAmounts<TIn, TOut> const& pool,
180 Quality const& targetQuality,
181 std::uint16_t const& tfee)
182{
183 if (targetQuality.rate() == beast::kZero)
184 return std::nullopt;
185
187 auto const f = feeMult(tfee);
188 auto const a = 1;
189 auto const b = pool.in * (1 - 1 / f) / targetQuality.rate() - 2 * pool.out;
190 auto const c = pool.out * pool.out - (pool.in * pool.out) / targetQuality.rate();
191
192 auto nTakerGets = solveQuadraticEqSmallest(a, b, c);
193 if (!nTakerGets || *nTakerGets <= 0)
194 return std::nullopt; // LCOV_EXCL_LINE
195
196 auto const nTakerGetsConstraint = pool.out - pool.in / (targetQuality.rate() * f);
197 if (nTakerGetsConstraint <= 0)
198 return std::nullopt;
199
200 // Select the smallest to maximize the quality
201 if (nTakerGetsConstraint < *nTakerGets)
202 nTakerGets = nTakerGetsConstraint;
203
204 auto getAmounts = [&pool, &tfee](Number const& nTakerGetsProposed) {
205 // Round downward to minimize the offer and to maximize the quality.
206 // This has the most impact when takerGets is XRP.
207 auto const takerGets =
208 toAmount<TOut>(getAsset(pool.out), nTakerGetsProposed, Number::RoundingMode::Downward);
209 return TAmounts<TIn, TOut>{swapAssetOut(pool, takerGets, tfee), takerGets};
210 };
211
212 // Try to reduce the offer size to improve the quality.
213 // The quality might still not match the targetQuality for a tiny offer.
214 auto amounts = getAmounts(*nTakerGets);
215 if (Quality{amounts} < targetQuality)
216 return getAmounts(detail::reduceOffer(amounts.out));
217 return amounts;
218}
219
243template <typename TIn, typename TOut>
246 TAmounts<TIn, TOut> const& pool,
247 Quality const& targetQuality,
248 std::uint16_t tfee)
249{
250 if (targetQuality.rate() == beast::kZero)
251 return std::nullopt;
252
254 auto const f = feeMult(tfee);
255 auto const& a = f;
256 auto const b = pool.in * (1 + f);
257 auto const c = pool.in * pool.in - pool.in * pool.out * targetQuality.rate();
258
259 auto nTakerPays = solveQuadraticEqSmallest(a, b, c);
260 if (!nTakerPays || nTakerPays <= 0)
261 return std::nullopt; // LCOV_EXCL_LINE
262
263 auto const nTakerPaysConstraint = pool.out * targetQuality.rate() - pool.in / f;
264 if (nTakerPaysConstraint <= 0)
265 return std::nullopt;
266
267 // Select the smallest to maximize the quality
268 if (nTakerPaysConstraint < *nTakerPays)
269 nTakerPays = nTakerPaysConstraint;
270
271 auto getAmounts = [&pool, &tfee](Number const& nTakerPaysProposed) {
272 // Round downward to minimize the offer and to maximize the quality.
273 // This has the most impact when takerPays is XRP.
274 auto const takerPays =
275 toAmount<TIn>(getAsset(pool.in), nTakerPaysProposed, Number::RoundingMode::Downward);
276 return TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)};
277 };
278
279 // Try to reduce the offer size to improve the quality.
280 // The quality might still not match the targetQuality for a tiny offer.
281 auto amounts = getAmounts(*nTakerPays);
282 if (Quality{amounts} < targetQuality)
283 return getAmounts(detail::reduceOffer(amounts.in));
284 return amounts;
285}
286
303template <typename TIn, typename TOut>
306 TAmounts<TIn, TOut> const& pool,
307 Quality const& quality,
308 std::uint16_t tfee,
309 Rules const& rules,
311{
312 if (!rules.enabled(fixAMMv1_1))
313 {
314 // Finds takerPays (i) and takerGets (o) such that given pool
315 // composition poolGets(I) and poolPays(O): (O - o) / (I + i) = quality.
316 // Where takerGets is calculated as the swapAssetIn (see below).
317 // The above equation produces the quadratic equation:
318 // i^2*(1-fee) + i*I*(2-fee) + I^2 - I*O/quality,
319 // which is solved for i, and o is found with swapAssetIn().
320 auto const f = feeMult(tfee); // 1 - fee
321 auto const& a = f;
322 auto const b = pool.in * (1 + f);
323 Number const c = pool.in * pool.in - pool.in * pool.out * quality.rate();
324 auto const res = b * b - 4 * a * c;
325 if (res < 0)
326 {
327 return std::nullopt; // LCOV_EXCL_LINE
328 }
329 if (auto const nTakerPaysPropose = (-b + root2(res)) / (2 * a); nTakerPaysPropose > 0)
330 {
331 auto const nTakerPays = [&]() {
332 // The fee might make the AMM offer quality less than CLOB
333 // quality. Therefore, AMM offer has to satisfy this constraint:
334 // o / i >= q. Substituting o with swapAssetIn() gives: i <= O /
335 // q - I / (1 - fee).
336 auto const nTakerPaysConstraint = pool.out * quality.rate() - pool.in / f;
337 if (nTakerPaysPropose > nTakerPaysConstraint)
338 return nTakerPaysConstraint;
339 return nTakerPaysPropose;
340 }();
341 if (nTakerPays <= 0)
342 {
343 JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in)
344 << " " << to_string(pool.out) << " " << quality << " " << tfee;
345 return std::nullopt;
346 }
347 auto const takerPays =
349 // should not fail
350 if (auto amounts = TAmounts<TIn, TOut>{takerPays, swapAssetIn(pool, takerPays, tfee)};
351 Quality{amounts} < quality &&
352 !withinRelativeDistance(Quality{amounts}, quality, Number(1, -7)))
353 {
354 JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " "
355 << to_string(pool.out) << " "
356 << " " << quality << " " << tfee << " " << to_string(amounts.in)
357 << " " << to_string(amounts.out);
358 Throw<std::runtime_error>("changeSpotPriceQuality failed");
359 }
360 else
361 {
362 JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " "
363 << to_string(pool.out) << " "
364 << " " << quality << " " << tfee << " " << to_string(amounts.in)
365 << " " << to_string(amounts.out);
366 return amounts;
367 }
368 }
369 JLOG(j.trace()) << "changeSpotPriceQuality calc failed: " << to_string(pool.in) << " "
370 << to_string(pool.out) << " " << quality << " " << tfee;
371 return std::nullopt;
372 }
373
374 // Generate the offer starting with XRP side. Return seated offer amounts
375 // if the offer can be generated, otherwise nullopt.
376 auto amounts = [&]() {
377 if (isXRP(getAsset(pool.out)))
378 return getAMMOfferStartWithTakerGets(pool, quality, tfee);
379 return getAMMOfferStartWithTakerPays(pool, quality, tfee);
380 }();
381 if (!amounts)
382 {
383 JLOG(j.trace()) << "changeSpotPrice calc failed: " << to_string(pool.in) << " "
384 << to_string(pool.out) << " " << quality << " " << tfee;
385 return std::nullopt;
386 }
387
388 if (Quality{*amounts} < quality)
389 {
390 JLOG(j.error()) << "changeSpotPriceQuality failed: " << to_string(pool.in) << " "
391 << to_string(pool.out) << " " << quality << " " << tfee << " "
392 << to_string(amounts->in) << " " << to_string(amounts->out);
393 return std::nullopt;
394 }
395
396 JLOG(j.trace()) << "changeSpotPriceQuality succeeded: " << to_string(pool.in) << " "
397 << to_string(pool.out) << " "
398 << " " << quality << " " << tfee << " " << to_string(amounts->in) << " "
399 << to_string(amounts->out);
400
401 return amounts;
402}
403
415
425template <typename TIn, typename TOut>
426TOut
427swapAssetIn(TAmounts<TIn, TOut> const& pool, TIn const& assetIn, std::uint16_t tfee)
428{
429 if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1))
430 {
431 // set rounding to always favor the amm. Clip to zero.
432 // calculate:
433 // pool.out -
434 // (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)),
435 // and explicitly set the rounding modes
436 // Favoring the amm means we should:
437 // minimize:
438 // pool.out -
439 // (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)),
440 // maximize:
441 // (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)),
442 // (pool.in * pool.out)
443 // minimize:
444 // (pool.in + assetIn * feeMult(tfee)),
445 // minimize:
446 // assetIn * feeMult(tfee)
447 // feeMult is: (1-fee), fee is tfee/100000
448 // minimize:
449 // 1-fee
450 // maximize:
451 // fee
453
455 auto const numerator = pool.in * pool.out;
456 auto const fee = getFee(tfee);
457
459 auto const denom = pool.in + assetIn * (1 - fee);
460
461 if (denom.signum() <= 0)
462 return toAmount<TOut>(getAsset(pool.out), 0);
463
465 auto const ratio = numerator / denom;
466
468 auto const swapOut = pool.out - ratio;
469
470 if (swapOut.signum() < 0)
471 return toAmount<TOut>(getAsset(pool.out), 0);
472
474 }
475
476 return toAmount<TOut>(
477 getAsset(pool.out),
478 pool.out - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)),
480}
481
491template <typename TIn, typename TOut>
492TIn
493swapAssetOut(TAmounts<TIn, TOut> const& pool, TOut const& assetOut, std::uint16_t tfee)
494{
495 if (auto const& rules = getCurrentTransactionRules(); rules && rules->enabled(fixAMMv1_1))
496 {
497 // set rounding to always favor the amm. Clip to zero.
498 // calculate:
499 // ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) /
500 // (1-tfee/100000)
501 // maximize:
502 // ((pool.in * pool.out) / (pool.out - assetOut) - pool.in)
503 // maximize:
504 // (pool.in * pool.out) / (pool.out - assetOut)
505 // maximize:
506 // (pool.in * pool.out)
507 // minimize
508 // (pool.out - assetOut)
509 // minimize:
510 // (1-tfee/100000)
511 // maximize:
512 // tfee/100000
513
515
517 auto const numerator = pool.in * pool.out;
518
520 auto const denom = pool.out - assetOut;
521 if (denom.signum() <= 0)
522 {
523 return toMaxAmount<TIn>(getAsset(pool.in));
524 }
525
527 auto const ratio = numerator / denom;
528 auto const numerator2 = ratio - pool.in;
529 auto const fee = getFee(tfee);
530
532 auto const feeMult = 1 - fee;
533
535 auto const swapIn = numerator2 / feeMult;
536 if (swapIn.signum() < 0)
537 return toAmount<TIn>(getAsset(pool.in), 0);
538
540 }
541
542 return toAmount<TIn>(
543 getAsset(pool.in),
544 ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / feeMult(tfee),
546}
547
550Number
551square(Number const& n);
552
564STAmount
565adjustLPTokens(STAmount const& lptAMMBalance, STAmount const& lpTokens, IsDeposit isDeposit);
566
580 STAmount const& amountBalance,
581 STAmount const& amount,
582 std::optional<STAmount> const& amount2,
583 STAmount const& lptAMMBalance,
584 STAmount const& lpTokens,
585 std::uint16_t tfee,
586 IsDeposit isDeposit);
587
591Number
592solveQuadraticEq(Number const& a, Number const& b, Number const& c);
593
594STAmount
595multiply(STAmount const& amount, Number const& frac, Number::RoundingMode rm);
596
597namespace detail {
598
601{
602 // Minimize on deposit, maximize on withdraw to ensure
603 // AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance
606}
607
610{
611 // Maximize on deposit, minimize on withdraw to ensure
612 // AMM invariant sqrt(poolAsset1 * poolAsset2) >= LPTokensBalance
613 return isDeposit == IsDeposit::Yes ? Number::RoundingMode::Upward
615}
616
617} // namespace detail
618
624template <typename A>
625STAmount
626getRoundedAsset(Rules const& rules, STAmount const& balance, A const& frac, IsDeposit isDeposit)
627{
628 if (!rules.enabled(fixAMMv1_3))
629 {
630 if constexpr (std::is_same_v<A, STAmount>)
631 {
632 return multiply(balance, frac, balance.asset());
633 }
634 else
635 {
636 return toSTAmount(balance.asset(), balance * frac);
637 }
638 }
639 auto const rm = detail::getAssetRounding(isDeposit);
640 return multiply(balance, frac, rm);
641}
642
652STAmount
654 Rules const& rules,
655 std::function<Number()> const& noRoundCb,
656 STAmount const& balance,
657 std::function<Number()> const& productCb,
658 IsDeposit isDeposit);
659
667STAmount
669 Rules const& rules,
670 STAmount const& balance,
671 Number const& frac,
672 IsDeposit isDeposit);
673
685STAmount
687 Rules const& rules,
688 std::function<Number()> const& noRoundCb,
689 STAmount const& lptAMMBalance,
690 std::function<Number()> const& productCb,
691 IsDeposit isDeposit);
692
693/* Next two functions adjust asset in/out amount to factor in the adjusted
694 * lptokens. The lptokens are calculated from the asset in/out. The lptokens are
695 * then adjusted to factor in the loss in precision. The adjusted lptokens might
696 * be less than the initially calculated tokens. Therefore, the asset in/out
697 * must be adjusted. The rounding might result in the adjusted amount being
698 * greater than the original asset in/out amount. If this happens,
699 * then the original amount is reduced by the difference in the adjusted amount
700 * and the original amount. The actual tokens and the actual adjusted amount
701 * are then recalculated. The minimum of the original and the actual
702 * adjusted amount is returned.
703 */
706 Rules const& rules,
707 STAmount const& balance,
708 STAmount const& amount,
709 STAmount const& lptAMMBalance,
710 STAmount const& tokens,
711 std::uint16_t tfee);
714 Rules const& rules,
715 STAmount const& balance,
716 STAmount const& amount,
717 STAmount const& lptAMMBalance,
718 STAmount const& tokens,
719 std::uint16_t tfee);
720
724Number
726 Rules const& rules,
727 STAmount const& lptAMMBalance,
728 STAmount const& tokens,
729 Number const& frac);
730
735 ReadView const& view,
736 AccountID const& ammAccountID,
737 Asset const& asset1,
738 Asset const& asset2,
739 FreezeHandling freezeHandling,
740 AuthHandling authHandling,
741 beast::Journal const j);
742
749TER
750checkAMMPrecisionLoss(Number const& poolProductMean, STAmount const& newLPTokenBalance);
751
758TER
760 ReadView const& view,
761 AccountID const& ammAccountID,
762 Asset const& asset1,
763 Asset const& asset2,
764 STAmount const& newLPTokenBalance,
765 beast::Journal const j);
766
771std::expected<std::tuple<STAmount, STAmount, STAmount>, TER>
773 ReadView const& view,
774 SLE const& ammSle,
775 std::optional<Asset> const& optAsset1,
776 std::optional<Asset> const& optAsset2,
777 FreezeHandling freezeHandling,
778 AuthHandling authHandling,
779 beast::Journal const j);
780
783STAmount
785 ReadView const& view,
786 Asset const& asset1,
787 Asset const& asset2,
788 AccountID const& ammAccount,
789 AccountID const& lpAccount,
790 beast::Journal const j);
791
792STAmount
794 ReadView const& view,
795 SLE const& ammSle,
796 AccountID const& lpAccount,
797 beast::Journal const j);
798
804getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account);
805
808STAmount
809ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Asset const& asset);
810
814TER
815deleteAMMAccount(Sandbox& view, Asset const& asset, Asset const& asset2, beast::Journal j);
816
819void
821 ApplyView& view,
822 SLE::pointer& ammSle,
823 AccountID const& account,
824 Asset const& lptAsset,
825 std::uint16_t tfee);
826
831std::expected<bool, TER>
832isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID const& lpAccount);
833
838std::expected<bool, TER>
840 Sandbox& sb,
841 STAmount const& lpTokens,
842 SLE::pointer& ammSle,
843 AccountID const& account);
844
845} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:38
Stream error() const
Definition Journal.h:315
Stream trace() const
Severity stream access functions.
Definition Journal.h:291
Number is a floating point type that can represent a wide range of values.
Definition Number.h:306
static RoundingMode setround(RoundingMode inMode)
Definition Number.cpp:111
static RoundingMode getround()
Definition Number.cpp:105
Represents the logical ratio of output currency to input currency.
Definition Quality.h:91
STAmount rate() const
Returns the quality as STAmount.
Definition Quality.h:149
Rules controlling protocol behavior.
Definition Rules.h:33
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:171
Asset const & asset() const
Definition STAmount.h:478
std::shared_ptr< STLedgerEntry > pointer
T is_same_v
T minmax(T... args)
Number reduceOffer(auto const &amount)
Definition AMMHelpers.h:27
Number::RoundingMode getLPTokenRounding(IsDeposit isDeposit)
Definition AMMHelpers.h:600
Number::RoundingMode getAssetRounding(IsDeposit isDeposit)
Definition AMMHelpers.h:609
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
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.
bool isXRP(AccountID const &c)
Definition AccountID.h:70
Number adjustFracByTokens(Rules const &rules, STAmount const &lptAMMBalance, STAmount const &tokens, Number const &frac)
Find a fraction of tokens after the tokens are adjusted.
T toMaxAmount(Asset const &asset)
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Asset const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
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.
std::expected< bool, TER > verifyAndAdjustLPTokenBalance(Sandbox &sb, STAmount const &lpTokens, SLE::pointer &ammSle, AccountID const &account)
Due to rounding, the LPTokenBalance of the last LP might not match the LP's trustline balance.
IsDeposit
Definition AMMHelpers.h:38
void initializeFeeAuctionVote(ApplyView &view, SLE::pointer &ammSle, AccountID const &account, Asset const &lptAsset, std::uint16_t tfee)
Initialize Auction and Voting slots and set the trading/discounted fee.
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
std::optional< Rules > const & getCurrentTransactionRules()
Definition Rules.cpp:30
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).
TOut swapAssetIn(TAmounts< TIn, TOut > const &pool, TIn const &assetIn, std::uint16_t tfee)
AMM pool invariant - the product (A * B) after swap in/out has to remain at least the same: (A + in) ...
Definition AMMHelpers.h:427
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:633
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.
T toAmount(STAmount const &amt)=delete
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)
std::optional< TAmounts< TIn, TOut > > getAMMOfferStartWithTakerGets(TAmounts< TIn, TOut > const &pool, Quality const &targetQuality, std::uint16_t const &tfee)
Generate AMM offer starting with takerGets when AMM pool from the payment perspective is IOU(in)/XRP(...
Definition AMMHelpers.h:178
STAmount ammAccountHolds(ReadView const &view, AccountID const &ammAccountID, Asset const &asset)
Returns total amount held by AMM for the given token.
Asset getAsset(T const &amt)
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.
std::optional< TAmounts< TIn, TOut > > getAMMOfferStartWithTakerPays(TAmounts< TIn, TOut > const &pool, Quality const &targetQuality, std::uint16_t tfee)
Generate AMM offer starting with takerPays when AMM pool from the payment perspective is XRP(in)/IOU(...
Definition AMMHelpers.h:245
STAmount getRoundedAsset(Rules const &rules, STAmount const &balance, A const &frac, IsDeposit isDeposit)
Round AMM equal deposit/withdrawal amount.
Definition AMMHelpers.h:626
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:87
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.
Number root2(Number f)
Definition Number.cpp:1275
std::optional< TAmounts< TIn, TOut > > changeSpotPriceQuality(TAmounts< TIn, TOut > const &pool, Quality const &quality, std::uint16_t tfee, Rules const &rules, beast::Journal j)
Generate AMM offer so that either updated Spot Price Quality (SPQ) is equal to LOB quality (in this c...
Definition AMMHelpers.h:305
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:28
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...
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:78
TIn swapAssetOut(TAmounts< TIn, TOut > const &pool, TOut const &assetOut, std::uint16_t tfee)
Swap assetOut out of the pool and swap in a proportional amount of the other asset.
Definition AMMHelpers.h:493
TERSubset< CanCvtToTER > TER
Definition TER.h:634
Number const kAMMInvariantRelativeTolerance
Definition AMMHelpers.h:40
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:115
STAmount multiply(STAmount const &amount, Number const &frac, Number::RoundingMode rm)
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.
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:49
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
STAmount lpTokensOut(STAmount const &asset1Balance, STAmount const &asset1Deposit, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's deposit amount.
Represents a pair of input and output currencies.
Definition Quality.h:26