3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/ledger/ApplyView.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/Sandbox.h>
10#include <xrpl/ledger/helpers/TokenHelpers.h>
11#include <xrpl/protocol/AMMCore.h>
12#include <xrpl/protocol/AccountID.h>
13#include <xrpl/protocol/AmountConversions.h>
14#include <xrpl/protocol/Asset.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/IOUAmount.h>
17#include <xrpl/protocol/Issue.h>
18#include <xrpl/protocol/MPTAmount.h>
19#include <xrpl/protocol/Quality.h>
20#include <xrpl/protocol/Rules.h>
21#include <xrpl/protocol/STAmount.h>
22#include <xrpl/protocol/STLedgerEntry.h>
23#include <xrpl/protocol/TER.h>
24#include <xrpl/protocol/XRPAmount.h>
41 static Number const kReducedOfferPct(9999, -4);
45 return amount * kReducedOfferPct;
61ammLPTokens(STAmount
const& asset1, STAmount
const& asset2, Asset
const& lptIssue);
73 STAmount
const& asset1Balance,
74 STAmount
const& asset1Deposit,
75 STAmount
const& lptAMMBalance,
88 STAmount
const& asset1Balance,
89 STAmount
const& lptAMMBalance,
90 STAmount
const& lpTokens,
104 STAmount
const& asset1Balance,
105 STAmount
const& asset1Withdraw,
106 STAmount
const& lptAMMBalance,
119 STAmount
const& assetBalance,
120 STAmount
const& lptAMMBalance,
121 STAmount
const& lpTokens,
135 if (calcQuality == reqQuality)
137 auto const [min, max] =
std::minmax(calcQuality, reqQuality);
141 return ((min.rate() - max.rate()) / min.rate()) < dist;
152template <
typename Amt>
163 return ((max - min) / max) < dist;
197template <
typename TIn,
typename TOut>
210 auto const b = pool.
in * (1 - 1 / f) / targetQuality.
rate() - 2 * pool.
out;
211 auto const c = pool.
out * pool.
out - (pool.
in * pool.
out) / targetQuality.
rate();
214 if (!nTakerGets || *nTakerGets <= 0)
217 auto const nTakerGetsConstraint = pool.
out - pool.
in / (targetQuality.
rate() * f);
218 if (nTakerGetsConstraint <= 0)
222 if (nTakerGetsConstraint < *nTakerGets)
223 nTakerGets = nTakerGetsConstraint;
225 auto const getAmounts = [&pool, &tfee](
Number const& nTakerGetsProposed) {
228 auto const takerGets =
235 auto amounts = getAmounts(*nTakerGets);
236 if (
Quality{amounts} < targetQuality)
265template <
typename TIn,
typename TOut>
278 auto const b = pool.
in * (1 + f);
279 auto const c = pool.
in * pool.
in - pool.
in * pool.
out * targetQuality.
rate();
282 if (!nTakerPays || nTakerPays <= 0)
285 auto const nTakerPaysConstraint = pool.
out * targetQuality.
rate() - pool.
in / f;
286 if (nTakerPaysConstraint <= 0)
290 if (nTakerPaysConstraint < *nTakerPays)
291 nTakerPays = nTakerPaysConstraint;
293 auto const getAmounts = [&pool, &tfee](
Number const& nTakerPaysProposed) {
296 auto const takerPays =
303 auto amounts = getAmounts(*nTakerPays);
304 if (
Quality{amounts} < targetQuality)
326template <
typename TIn,
typename TOut>
345 if (outIntegral && (!inIntegral ||
Number(quality.rate()) >= 1))
351 JLOG(j.
trace()) <<
"changeSpotPrice calc failed: " <<
to_string(pool.
in) <<
" "
352 <<
to_string(pool.
out) <<
" " << quality <<
" " << tfee;
356 if (
Quality{*amounts} < quality)
358 JLOG(j.
error()) <<
"changeSpotPriceQuality failed: " <<
to_string(pool.
in) <<
" "
359 <<
to_string(pool.
out) <<
" " << quality <<
" " << tfee <<
" "
364 JLOG(j.
trace()) <<
"changeSpotPriceQuality succeeded: " <<
to_string(pool.
in) <<
" "
366 <<
" " << quality <<
" " << tfee <<
" " <<
to_string(amounts->in) <<
" "
395template <
typename TIn,
typename TOut>
423 auto const numerator = pool.
in * pool.
out;
424 auto const fee =
getFee(tfee);
427 auto const denom = pool.
in + assetIn * (1 - fee);
429 if (denom.signum() <= 0)
433 auto const ratio = numerator / denom;
436 auto const swapOut = pool.
out - ratio;
438 if (swapOut.signum() < 0)
454template <
typename TIn,
typename TOut>
478 auto const numerator = pool.
in * pool.
out;
481 auto const denom = pool.
out - assetOut;
482 if (denom.signum() <= 0)
488 auto const ratio = numerator / denom;
489 auto const numerator2 = ratio - pool.
in;
490 auto const fee =
getFee(tfee);
496 auto const swapIn = numerator2 /
feeMult;
497 if (swapIn.signum() < 0)
538 STAmount
const& amountBalance,
539 STAmount
const& amount,
541 STAmount
const& lptAMMBalance,
542 STAmount
const& lpTokens,
588 if (!rules.
enabled(fixAMMv1_3))
617 STAmount
const& balance,
632 STAmount
const& balance,
652 STAmount
const& lptAMMBalance,
670 STAmount
const& balance,
671 STAmount
const& amount,
672 STAmount
const& lptAMMBalance,
673 STAmount
const& tokens,
678 STAmount
const& balance,
679 STAmount
const& amount,
680 STAmount
const& lptAMMBalance,
681 STAmount
const& tokens,
691 STAmount
const& lptAMMBalance,
692 STAmount
const& tokens,
700 ReadView
const& view,
727 ReadView
const& view,
731 STAmount
const& newLPTokenBalance,
739std::expected<std::tuple<STAmount, STAmount, STAmount>,
TER>
741 ReadView
const& view,
754 ReadView
const& view,
763 ReadView
const& view,
794 ApplyView
const& view,
797 Asset
const& lptAsset,
805std::expected<bool, TER>
813std::expected<bool, TER>
816 STAmount
const& lpTokens,
A generic endpoint for log messages.
Stream trace() const
Severity stream access functions.
Number is a floating point type that can represent a wide range of values.
static RoundingMode setround(RoundingMode inMode)
static RoundingMode getround()
Represents the logical ratio of output currency to input currency.
STAmount rate() const
Returns the quality as STAmount.
Rules controlling protocol behavior.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Asset const & asset() const
std::shared_ptr< STLedgerEntry > pointer
Number reduceOffer(auto const &amount)
Number::RoundingMode getLPTokenRounding(IsDeposit isDeposit)
Number::RoundingMode getAssetRounding(IsDeposit isDeposit)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
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.
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.
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
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) ...
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)
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
@ Yes
We have consensus along with the network.
@ No
We do not have consensus.
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(...
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(...
STAmount getRoundedAsset(Rules const &rules, STAmount const &balance, A const &frac, IsDeposit isDeposit)
Round AMM equal deposit/withdrawal amount.
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.
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< TAmounts< TIn, TOut > > changeSpotPriceQuality(TAmounts< TIn, TOut > const &pool, Quality const &quality, std::uint16_t tfee, beast::Journal j)
Generate AMM offer so that either updated Spot Price Quality (SPQ) is equal to LOB quality (in this c...
std::optional< Number > solveQuadraticEqSmallest(Number const &a, Number const &b, Number const &c)
Solve quadratic equation to find takerGets or takerPays.
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.
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...
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.
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.
TERSubset< CanCvtToTER > TER
Number const kAMMInvariantRelativeTolerance
bool withinRelativeDistance(Quality const &calcQuality, Quality const &reqQuality, Number const &dist)
Check if the relative distance between the qualities is within the requested distance.
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.
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.