1#include <xrpl/ledger/Sandbox.h>
2#include <xrpl/ledger/View.h>
3#include <xrpl/ledger/helpers/AccountRootHelpers.h>
4#include <xrpl/protocol/AMMCore.h>
5#include <xrpl/protocol/Feature.h>
6#include <xrpl/protocol/TxFlags.h>
7#include <xrpl/tx/transactors/dex/AMMDeposit.h>
8#include <xrpl/tx/transactors/dex/AMMHelpers.h>
9#include <xrpl/tx/transactors/dex/AMMUtils.h>
22 return tfAMMDepositMask;
30 auto const amount = ctx.
tx[~sfAmount];
31 auto const amount2 = ctx.
tx[~sfAmount2];
32 auto const ePrice = ctx.
tx[~sfEPrice];
33 auto const lpTokens = ctx.
tx[~sfLPTokenOut];
34 auto const tradingFee = ctx.
tx[~sfTradingFee];
44 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid flags.";
47 if ((flags & tfLPToken) != 0u)
50 if (!lpTokens || ePrice || (amount && !amount2) || (!amount && amount2) || tradingFee)
53 else if ((flags & tfSingleAsset) != 0u)
56 if (!amount || amount2 || ePrice || tradingFee)
59 else if ((flags & tfTwoAsset) != 0u)
62 if (!amount || !amount2 || ePrice || tradingFee)
65 else if ((flags & tfOneAssetLPToken) != 0u)
67 if (!amount || !lpTokens || amount2 || ePrice || tradingFee)
70 else if ((flags & tfLimitLPToken) != 0u)
72 if (!amount || !ePrice || lpTokens || amount2 || tradingFee)
75 else if ((flags & tfTwoAssetIfEmpty) != 0u)
77 if (!amount || !amount2 || ePrice || lpTokens)
81 auto const asset = ctx.
tx[sfAsset].get<
Issue>();
82 auto const asset2 = ctx.
tx[sfAsset2].get<
Issue>();
85 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid asset pair.";
89 if (amount && amount2 && amount->issue() == amount2->issue())
91 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid tokens, same issue." << amount->issue() <<
" "
96 if (lpTokens && *lpTokens <= beast::zero)
98 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens";
107 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount";
117 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount2";
123 if (amount && ePrice)
128 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid EPrice";
135 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid trading fee.";
145 auto const accountID = ctx.
tx[sfAccount];
150 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: Invalid asset pair.";
157 return expected.error();
158 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
159 if ((ctx.
tx.
getFlags() & tfTwoAssetIfEmpty) != 0u)
161 if (lptAMMBalance != beast::zero)
163 if (amountBalance != beast::zero || amount2Balance != beast::zero)
166 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: tokens balance is not zero.";
173 if (lptAMMBalance == beast::zero)
175 if (amountBalance <= beast::zero || amount2Balance <= beast::zero ||
176 lptAMMBalance < beast::zero)
179 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: reserves or tokens balance is zero.";
190 auto balance = [&](
auto const&
deposit) ->
TER {
193 auto const lpIssue = (*ammSle)[sfLPTokenBalance].issue();
203 return (accountID ==
deposit.issue().account ||
215 auto checkAsset = [&](
Issue const& asset) ->
TER {
218 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account is not authorized, " << asset;
224 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account or currency is frozen, "
233 if (
auto const ter = checkAsset(ctx.
tx[sfAsset].get<
Issue>()))
236 if (
auto const ter = checkAsset(ctx.
tx[sfAsset2].get<
Issue>()))
240 auto const amount = ctx.
tx[~sfAmount];
241 auto const amount2 = ctx.
tx[~sfAmount2];
242 auto const ammAccountID = ammSle->
getAccountID(sfAccount);
250 if (
auto const ter =
requireAuth(ctx.
view, amount->issue(), accountID))
254 <<
"AMM Deposit: account is not authorized, " << amount->issue();
262 <<
"AMM Deposit: AMM account or currency is frozen, " <<
to_string(accountID);
268 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account is frozen, " <<
to_string(accountID)
269 <<
" " <<
to_string(amount->issue().currency);
274 if (
auto const ter = balance(*amount))
277 <<
"AMM Deposit: account has insufficient funds, " << *amount;
288 if (
auto const ter = checkAmount(amount,
true))
291 if (
auto const ter = checkAmount(amount2,
true))
296 if (
auto const ter = checkAmount(amountBalance,
false))
298 if (
auto const ter = checkAmount(amount2Balance,
false))
303 if (
auto const lpTokens = ctx.
tx[~sfLPTokenOut];
304 lpTokens && lpTokens->issue() != lptAMMBalance.issue())
306 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens.";
316 if (xrpBalance <= beast::zero)
318 JLOG(ctx.
j.
debug()) <<
"AMM Instance: insufficient reserves";
329 auto const amount =
ctx_.
tx[~sfAmount];
330 auto const amount2 =
ctx_.
tx[~sfAmount2];
331 auto const ePrice =
ctx_.
tx[~sfEPrice];
332 auto const lpTokensDeposit =
ctx_.
tx[~sfLPTokenOut];
336 auto const ammAccountID = (*ammSle)[sfAccount];
346 return {expected.error(),
false};
347 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
348 auto const tfee = (lptAMMBalance == beast::zero)
349 ?
ctx_.
tx[~sfTradingFee].value_or(0)
354 auto const [result, newLPTokenBalance] = [&,
355 &amountBalance = amountBalance,
356 &amount2Balance = amount2Balance,
359 if (subTxType & tfTwoAsset)
372 if (subTxType & tfOneAssetLPToken)
375 sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *lpTokensDeposit, tfee);
377 if (subTxType & tfLimitLPToken)
380 sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *ePrice, tfee);
382 if (subTxType & tfSingleAsset)
385 sb, ammAccountID, amountBalance, lptAMMBalance, *amount, lpTokensDeposit, tfee);
387 if (subTxType & tfLPToken)
400 if (subTxType & tfTwoAssetIfEmpty)
403 sb, ammAccountID, *amount, *amount2, lptAMMBalance.issue(), tfee);
407 JLOG(
j_.
error()) <<
"AMM Deposit: invalid options.";
415 newLPTokenBalance > beast::zero,
416 "xrpl::AMMDeposit::applyGuts : valid new LP token balance");
417 ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance);
420 if (lptAMMBalance == beast::zero)
459 auto checkBalance = [&](
auto const& depositAmount) ->
TER {
460 if (depositAmount <= beast::zero)
462 if (
isXRP(depositAmount))
464 auto const& lpIssue = lpTokensDeposit.
issue();
471 account_ == depositAmount.issue().account ||
475 depositAmount.issue(),
484 auto const [amountDepositActual, amount2DepositActual, lpTokensDepositActual] =
494 if (lpTokensDepositActual <= beast::zero)
500 if (amountDepositActual < depositMin || amount2DepositActual < deposit2Min ||
501 lpTokensDepositActual < lpTokensDepositMin)
504 <<
"AMM Deposit: min deposit fails " << amountDepositActual <<
" "
506 <<
" " << deposit2Min.
value_or(
STAmount{}) <<
" " << lpTokensDepositActual <<
" "
512 if (
auto const ter = checkBalance(amountDepositActual))
515 "checkBalance to deposit or is 0"
516 << amountDepositActual;
524 JLOG(
ctx_.
journal.
debug()) <<
"AMM Deposit: failed to deposit " << amountDepositActual;
529 if (amount2DepositActual)
531 if (
auto const ter = checkBalance(*amount2DepositActual))
533 JLOG(
ctx_.
journal.
debug()) <<
"AMM Deposit: account has insufficient checkBalance to "
535 << *amount2DepositActual;
544 <<
"AMM Deposit: failed to deposit " << *amount2DepositActual;
557 return {
tesSUCCESS, lptAMMBalance + lpTokensDepositActual};
566 if (!rules.
enabled(fixAMMv1_3))
567 return lpTokensDeposit;
591 auto const frac =
divide(tokensAdj, lptAMMBalance, lptAMMBalance.
issue());
593 auto const amountDeposit =
595 auto const amount2Deposit =
613 JLOG(
j_.
error()) <<
"AMMDeposit::equalDepositTokens exception " << e.
what();
659 auto frac =
Number{amount} / amountBalance;
661 if (tokensAdj == beast::zero)
673 if (amount2Deposit <= amount2)
688 frac =
Number{amount2} / amount2Balance;
690 if (tokensAdj == beast::zero)
702 if (amountDeposit <= amount)
740 if (tokens == beast::zero)
750 auto const [tokensAdj, amountDepositAdj] =
789 auto const amountDeposit =
ammAssetIn(amountBalance, lptAMMBalance, tokensAdj, tfee);
790 if (amountDeposit > amount)
841 if (amount != beast::zero)
845 if (tokens <= beast::zero)
855 auto const [tokensAdj, amountDepositAdj] =
859 auto const ep =
Number{amountDepositAdj} / tokensAdj;
896 auto const c = f1 * amountBalance / (ePrice * lptAMMBalance);
897 auto const d = f1 + c * f2 - c;
898 auto const a1 = c * c;
899 auto const b1 = c * c * f2 * f2 + 2 * c - d * d;
900 auto const c1 = 2 * c * f2 * f2 + 1 - 2 * d * f2;
901 auto amtNoRoundCb = [&] {
return f1 * amountBalance *
solveQuadraticEq(a1, b1, c1); };
903 auto const amountDeposit =
905 if (amountDeposit <= beast::zero)
907 auto tokNoRoundCb = [&] {
return amountDeposit / ePrice; };
908 auto tokProdCb = [&] {
return amountDeposit / ePrice; };
913 view.
rules(), amountBalance, amountDeposit, lptAMMBalance, tokens, tfee);
937 Issue const& lptIssue,
static TER preclaim(PreclaimContext const &ctx)
std::pair< TER, STAmount > equalDepositInEmptyState(Sandbox &view, AccountID const &ammAccount, STAmount const &amount, STAmount const &amount2, Issue const &lptIssue, std::uint16_t tfee)
Equal deposit in empty AMM state (LP tokens balance is 0)
static bool checkExtraFeatures(PreflightContext const &ctx)
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
std::pair< TER, STAmount > singleDepositTokens(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &lpTokensDeposit, std::uint16_t tfee)
Single asset deposit (Asset1In, LPTokens) by the tokens.
std::pair< TER, STAmount > equalDepositTokens(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount2Balance, STAmount const &lptAMMBalance, STAmount const &lpTokensDeposit, std::optional< STAmount > const &depositMin, std::optional< STAmount > const &deposit2Min, std::uint16_t tfee)
Equal asset deposit (LPTokens) for the specified share of the AMM instance pools.
std::pair< TER, STAmount > singleDepositEPrice(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &ePrice, std::uint16_t tfee)
Single asset deposit (Asset1In, EPrice) with two constraints.
std::pair< TER, bool > applyGuts(Sandbox &view)
std::pair< TER, STAmount > singleDeposit(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &lptAMMBalance, STAmount const &amount, std::optional< STAmount > const &lpTokensDepositMin, std::uint16_t tfee)
Single asset deposit (Asset1In) by the amount.
static NotTEC preflight(PreflightContext const &ctx)
std::pair< TER, STAmount > equalDepositLimit(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amount2Balance, STAmount const &lptAMMBalance, STAmount const &amount, STAmount const &amount2, std::optional< STAmount > const &lpTokensDepositMin, std::uint16_t tfee)
Equal asset deposit (Asset1In, Asset2In) with the constraint on the maximum amount of both assets tha...
std::pair< TER, STAmount > deposit(Sandbox &view, AccountID const &ammAccount, STAmount const &amountBalance, STAmount const &amountDeposit, std::optional< STAmount > const &amount2Deposit, STAmount const &lptAMMBalance, STAmount const &lpTokensDeposit, std::optional< STAmount > const &depositMin, std::optional< STAmount > const &deposit2Min, std::optional< STAmount > const &lpTokensDepositMin, std::uint16_t tfee)
Deposit requested assets and token amount into LP account.
beast::Journal const journal
A currency issued by an account.
Number is a floating point type that can represent a wide range of values.
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
Rules controlling protocol behavior.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Issue const & issue() const
AccountID getAccountID(SField const &field) const
std::uint32_t getFlags() const
Discardable, editable view to a ledger.
void update(std::shared_ptr< SLE > const &sle) override
Indicate changes to a peeked SLE.
std::shared_ptr< SLE > peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
T make_optional(T... args)
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
STAmount divide(STAmount const &amount, Rate const &rate)
std::uint16_t constexpr TRADING_FEE_THRESHOLD
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
static STAmount adjustLPTokensOut(Rules const &rules, STAmount const &lptAMMBalance, STAmount const &lpTokensDeposit)
Number feeMultHalf(std::uint16_t tfee)
Get fee multiplier (1 - tfee / 2) @tfee trading fee in basis points.
bool ammEnabled(Rules const &)
Return true if required AMM amendments are enabled.
constexpr FlagValue tfDepositSubTx
bool isXRP(AccountID const &c)
Number adjustFracByTokens(Rules const &rules, STAmount const &lptAMMBalance, STAmount const &tokens, Number const &frac)
Find a fraction of tokens after the tokens are adjusted.
bool isIndividualFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue)
std::string to_string(base_uint< Bits, Tag > const &a)
NotTEC invalidAMMAssetPair(Issue const &issue1, Issue const &issue2, std::optional< std::pair< Issue, Issue > > const &pair=std::nullopt)
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=shSIMPLE_BALANCE)
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)
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Issue const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
STAmount getRoundedLPTokens(Rules const &rules, STAmount const &balance, Number const &frac, IsDeposit isDeposit)
Round AMM deposit/withdrawal LPToken amount.
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee=WaiveTransferFee::No)
Calls static accountSendIOU if saAmount represents Issue.
std::pair< STAmount, STAmount > adjustAssetInByTokens(Rules const &rules, STAmount const &balance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &tokens, std::uint16_t tfee)
Expected< std::tuple< STAmount, STAmount, STAmount >, TER > ammHolds(ReadView const &view, SLE const &ammSle, std::optional< Issue > const &optIssue1, std::optional< Issue > const &optIssue2, FreezeHandling freezeHandling, beast::Journal const j)
Get AMM pool and LP token balances.
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, int depth=0)
TERSubset< CanCvtToTER > TER
STAmount getRoundedAsset(Rules const &rules, STAmount const &balance, A const &frac, IsDeposit isDeposit)
Round AMM equal deposit/withdrawal amount.
Number feeMult(std::uint16_t tfee)
Get fee multiplier (1 - tfee) @tfee trading fee in basis points.
void initializeFeeAuctionVote(ApplyView &view, std::shared_ptr< SLE > &ammSle, AccountID const &account, Issue const &lptIssue, std::uint16_t tfee)
Initialize Auction and Voting slots and set the trading/discounted fee.
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Issue, Issue > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
STAmount ammAssetIn(STAmount const &asset1Balance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset deposit given LP Tokens.
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...
bool isTesSuccess(TER x) noexcept
std::uint16_t getTradingFee(ReadView const &view, SLE const &ammSle, AccountID const &account)
Get AMM trading fee for the given account.
STAmount lpTokensOut(STAmount const &asset1Balance, STAmount const &asset1Deposit, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's deposit amount.
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, int depth=0)
Check if the account lacks required authorization for MPT.
STAmount ammLPHolds(ReadView const &view, Currency const &cur1, Currency const &cur2, AccountID const &ammAccount, AccountID const &lpAccount, beast::Journal const j)
Get the balance of LP tokens.
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.