1#include <xrpl/tx/transactors/dex/AMMDeposit.h>
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/ledger/Sandbox.h>
8#include <xrpl/ledger/helpers/AMMHelpers.h>
9#include <xrpl/ledger/helpers/AccountRootHelpers.h>
10#include <xrpl/ledger/helpers/MPTokenHelpers.h>
11#include <xrpl/ledger/helpers/TokenHelpers.h>
12#include <xrpl/protocol/AMMCore.h>
13#include <xrpl/protocol/AccountID.h>
14#include <xrpl/protocol/Asset.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/Indexes.h>
17#include <xrpl/protocol/MPTIssue.h>
18#include <xrpl/protocol/SField.h>
19#include <xrpl/protocol/STAmount.h>
20#include <xrpl/protocol/STLedgerEntry.h>
21#include <xrpl/protocol/STTx.h>
22#include <xrpl/protocol/TER.h>
23#include <xrpl/protocol/TxFlags.h>
24#include <xrpl/protocol/XRPAmount.h>
25#include <xrpl/tx/Transactor.h>
39 auto const amount = ctx.
tx[~sfAmount];
40 auto const amount2 = ctx.
tx[~sfAmount2];
44 !(amount && amount->holds<
MPTIssue>()) && !(amount2 && amount2->holds<
MPTIssue>()));
50 return tfAMMDepositMask;
57 auto const amount = ctx.
tx[~sfAmount];
58 auto const amount2 = ctx.
tx[~sfAmount2];
59 auto const ePrice = ctx.
tx[~sfEPrice];
60 auto const lpTokens = ctx.
tx[~sfLPTokenOut];
61 auto const tradingFee = ctx.
tx[~sfTradingFee];
71 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid flags.";
77 if (!lpTokens || ePrice || (amount && !amount2) || (!amount && amount2) || tradingFee)
80 else if (ctx.
tx.
isFlag(tfSingleAsset))
83 if (!amount || amount2 || ePrice || tradingFee)
89 if (!amount || !amount2 || ePrice || tradingFee)
92 else if (ctx.
tx.
isFlag(tfOneAssetLPToken))
94 if (!amount || !lpTokens || amount2 || ePrice || tradingFee)
97 else if (ctx.
tx.
isFlag(tfLimitLPToken))
99 if (!amount || !ePrice || lpTokens || amount2 || tradingFee)
102 else if (ctx.
tx.
isFlag(tfTwoAssetIfEmpty))
104 if (!amount || !amount2 || ePrice || lpTokens)
108 auto const asset = ctx.
tx[sfAsset];
109 auto const asset2 = ctx.
tx[sfAsset2];
112 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid asset pair.";
116 if (amount && amount2 && amount->asset() == amount2->asset())
118 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid tokens, same issue." << amount->asset() <<
" "
125 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens";
134 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount";
144 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount2";
149 if (amount && ePrice)
160 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid EPrice";
167 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid trading fee.";
177 auto const accountID = ctx.
tx[sfAccount];
182 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: Invalid asset pair.";
195 return expected.error();
196 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
197 if (ctx.
tx.
isFlag(tfTwoAssetIfEmpty))
204 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: tokens balance is not zero.";
217 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: reserves or tokens balance is zero.";
228 auto balance = [&](
auto const&
deposit) ->
TER {
231 auto const lpIssue = (*ammSle)[sfLPTokenBalance].get<
Issue>();
252 auto const amount = ctx.
tx[~sfAmount];
253 auto const amount2 = ctx.
tx[~sfAmount2];
254 auto const ammAccountID = ammSle->
getAccountID(sfAccount);
260 auto const checkAsset = [&](
Asset const& asset) ->
TER {
263 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account is not authorized, " << asset;
275 if (
auto const ter = checkAsset(ctx.
tx[sfAsset]))
278 if (
auto const ter = checkAsset(ctx.
tx[sfAsset2]))
285 auto const checkAsset = [&](
Asset const& asset) ->
TER {
291 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account is not authorized, " << asset;
297 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account or currency is frozen or locked, "
306 if (
auto const ter = checkAsset(ctx.
tx[sfAsset]))
309 if (
auto const ter = checkAsset(ctx.
tx[sfAsset2]))
319 if (
auto const ter =
requireAuth(ctx.
view, amount->asset(), accountID))
323 <<
"AMM Deposit: account is not authorized, " << amount->asset();
330 if (
auto const ter =
checkFrozen(ctx.
view, ammAccountID, amount->asset());
334 <<
"AMM Deposit: AMM account or currency is frozen or locked, "
343 <<
"AMM Deposit: account is frozen or locked, " <<
to_string(accountID)
350 if (
auto const ter = balance(*amount))
353 <<
"AMM Deposit: account has insufficient funds, " << *amount;
364 if (
auto const ter = checkAmount(amount,
true))
367 if (
auto const ter = checkAmount(amount2,
true))
372 if (
auto const ter = checkAmount(amountBalance,
false))
374 if (
auto const ter = checkAmount(amount2Balance,
false))
379 if (
auto const lpTokens = ctx.
tx[~sfLPTokenOut];
380 lpTokens && lpTokens->asset() != lptAMMBalance.asset())
382 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens.";
394 JLOG(ctx.
j.
debug()) <<
"AMM Instance: insufficient reserves";
412 auto const amount =
ctx_.tx[~sfAmount];
413 auto const amount2 =
ctx_.tx[~sfAmount2];
414 auto const ePrice =
ctx_.tx[~sfEPrice];
415 auto const lpTokensDeposit =
ctx_.tx[~sfLPTokenOut];
419 auto const ammAccountID = (*ammSle)[sfAccount];
430 return {expected.error(),
false};
431 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
433 ?
ctx_.tx[~sfTradingFee].value_or(0)
438 auto dispatchToDeposit = [&,
439 &amountBalance = amountBalance,
440 &amount2Balance = amount2Balance,
442 if (subTxType & tfTwoAsset)
455 if (subTxType & tfOneAssetLPToken)
458 sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *lpTokensDeposit, tfee);
460 if (subTxType & tfLimitLPToken)
463 sb, ammAccountID, amountBalance, *amount, lptAMMBalance, *ePrice, tfee);
465 if (subTxType & tfSingleAsset)
468 sb, ammAccountID, amountBalance, lptAMMBalance, *amount, lpTokensDeposit, tfee);
470 if (subTxType & tfLPToken)
483 if (subTxType & tfTwoAssetIfEmpty)
486 sb, ammAccountID, *amount, *amount2, lptAMMBalance.asset(), tfee);
490 JLOG(
j_.error()) <<
"AMM Deposit: invalid options.";
498 return dispatchToDeposit();
502 REACHABLE(
"xrpl::AMMDeposit::applyGuts : deposit amount out of range reached");
512 JLOG(
j_.error()) <<
"AMMDeposit: deposit amount out of range " << e.
what();
521 "xrpl::AMMDeposit::applyGuts : valid new LP token balance");
528 sb, ammAccountID,
ctx_.tx[sfAsset],
ctx_.tx[sfAsset2], newLPTokenBalance,
j_);
531 UNREACHABLE(
"xrpl::AMMDeposit::applyGuts : AMM precision loss");
535 ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance);
577 auto const checkBalance = [&](
auto const& depositAmount) ->
TER {
580 if (
isXRP(depositAmount))
582 auto const& lpIssue = lpTokensDeposit.
get<
Issue>();
596 ctx_.journal) >= depositAmount)
603 auto const [amountDepositActual, amount2DepositActual, lpTokensDepositActual] =
615 JLOG(
ctx_.journal.debug()) <<
"AMM Deposit: adjusted tokens zero";
619 if (amountDepositActual < depositMin || amount2DepositActual < deposit2Min ||
620 lpTokensDepositActual < lpTokensDepositMin)
622 JLOG(
ctx_.journal.debug())
623 <<
"AMM Deposit: min deposit fails " << amountDepositActual <<
" "
625 <<
" " << deposit2Min.
value_or(
STAmount{}) <<
" " << lpTokensDepositActual <<
" "
631 if (
auto const ter = checkBalance(amountDepositActual))
633 JLOG(
ctx_.journal.debug()) <<
"AMM Deposit: account has insufficient "
634 "checkBalance to deposit or is 0"
635 << amountDepositActual;
649 JLOG(
ctx_.journal.debug()) <<
"AMM Deposit: failed to deposit " << amountDepositActual;
654 if (amount2DepositActual)
656 if (
auto const ter = checkBalance(*amount2DepositActual))
658 JLOG(
ctx_.journal.debug()) <<
"AMM Deposit: account has insufficient checkBalance to "
660 << *amount2DepositActual;
668 *amount2DepositActual,
674 JLOG(
ctx_.journal.debug())
675 <<
"AMM Deposit: failed to deposit " << *amount2DepositActual;
684 JLOG(
ctx_.journal.debug()) <<
"AMM Deposit: failed to deposit LPTokens";
688 return {
tesSUCCESS, lptAMMBalance + lpTokensDepositActual};
697 if (!rules.
enabled(fixAMMv1_3))
698 return lpTokensDeposit;
723 auto const frac =
divide(tokensAdj, lptAMMBalance, lptAMMBalance.
asset());
725 auto const amountDeposit =
727 auto const amount2Deposit =
745 JLOG(
j_.error()) <<
"AMMDeposit::equalDepositTokens exception " << e.
what();
792 auto frac =
Number{amount} / amountBalance;
796 if (!
view.rules().enabled(fixAMMv1_3))
806 if (amount2Deposit <= amount2)
821 frac =
Number{amount2} / amount2Balance;
825 if (!
view.rules().enabled(fixAMMv1_3))
835 if (amountDeposit <= amount)
873 view.rules(), lptAMMBalance,
lpTokensOut(amountBalance, amount, lptAMMBalance, tfee));
876 if (!
view.rules().enabled(fixAMMv1_3))
884 auto const [tokensAdj, amountDepositAdj] =
924 auto const amountDeposit =
ammAssetIn(amountBalance, lptAMMBalance, tokensAdj, tfee);
925 if (amountDeposit > amount)
980 view.rules(), lptAMMBalance,
lpTokensOut(amountBalance, amount, lptAMMBalance, tfee));
983 if (!
view.rules().enabled(fixAMMv1_3))
991 auto const [tokensAdj, amountDepositAdj] =
995 auto const ep =
Number{amountDepositAdj} / tokensAdj;
1030 auto const f1 =
feeMult(tfee);
1032 auto const c = f1 * amountBalance / (ePrice * lptAMMBalance);
1033 auto const d = f1 + c * f2 - c;
1034 auto const a1 = c * c;
1035 auto const b1 = c * c * f2 * f2 + 2 * c - d * d;
1036 auto const c1 = 2 * c * f2 * f2 + 1 - 2 * d * f2;
1037 auto const amtNoRoundCb = [&] {
return f1 * amountBalance *
solveQuadraticEq(a1, b1, c1); };
1039 auto const amountDeposit =
1043 auto const tokNoRoundCb = [&] {
return amountDeposit / ePrice; };
1044 auto const tokProdCb = [&] {
return amountDeposit / ePrice; };
1049 view.rules(), amountBalance, amountDeposit, lptAMMBalance, tokens, tfee);
1073 Asset const& lptIssue,
A generic endpoint for log messages.
static TER preclaim(PreclaimContext const &ctx)
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 > equalDepositInEmptyState(Sandbox &view, AccountID const &ammAccount, STAmount const &amount, STAmount const &amount2, Asset const &lptIssue, std::uint16_t tfee)
Equal deposit in empty AMM state (LP tokens balance is 0).
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)
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
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)
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
std::pair< TER, STAmount > 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.
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 SLE::const_pointer 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.
constexpr TIss const & get() const
Asset const & asset() const
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFlag(std::uint32_t) const
AccountID getAccountID(SField const &field) const
std::uint32_t getFlags() const
Discardable, editable view to a ledger.
AccountID const accountID_
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
Rules const & rules() const override
Returns the tx processing rules.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
T make_optional(T... args)
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Keylet trustLine(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.
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
STAmount divide(STAmount const &amount, Rate const &rate)
constexpr std::uint16_t kTradingFeeThreshold
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.
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
Calculate liquid XRP balance for an account.
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.
TER checkIndividualFrozen(ReadView const &view, AccountID const &account, Asset const &asset)
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.
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Asset const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
TER checkDepositFreeze(ReadView const &view, AccountID const &srcAcct, AccountID const &pseudoAcct, Asset const &asset)
Checks freeze compliance for depositing an asset into a pseudo-account (e.g.
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
TER canMPTTradeAndTransfer(ReadView const &v, Asset const &asset, AccountID const &from, AccountID const &to)
Convenience to combine canTrade/Transfer.
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 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 > adjustAssetInByTokens(Rules const &rules, STAmount const &balance, STAmount const &amount, STAmount const &lptAMMBalance, STAmount const &tokens, std::uint16_t tfee)
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
TERSubset< CanCvtToNotTEC > NotTEC
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, SLE::Ref sponsorSle={}, WaiveTransferFee waiveFee=WaiveTransferFee::No, AllowMPTOverflow allowOverflow=AllowMPTOverflow::No)
Calls static accountSendIOU if saAmount represents Issue.
STAmount getRoundedAsset(Rules const &rules, STAmount const &balance, A const &frac, IsDeposit isDeposit)
Round AMM equal deposit/withdrawal amount.
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...
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...
bool isTesSuccess(TER x) noexcept
TERSubset< CanCvtToTER > TER
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
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.
STAmount lpTokensOut(STAmount const &asset1Balance, STAmount const &asset1Deposit, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's deposit amount.
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.