20#include <xrpld/app/tx/detail/AMMDeposit.h>
22#include <xrpld/app/misc/AMMHelpers.h>
23#include <xrpld/app/misc/AMMUtils.h>
24#include <xrpld/ledger/Sandbox.h>
25#include <xrpld/ledger/View.h>
26#include <xrpl/protocol/AMMCore.h>
27#include <xrpl/protocol/Feature.h>
28#include <xrpl/protocol/STAccount.h>
29#include <xrpl/protocol/TxFlags.h>
47 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid flags.";
51 auto const amount = ctx.
tx[~sfAmount];
52 auto const amount2 = ctx.
tx[~sfAmount2];
53 auto const ePrice = ctx.
tx[~sfEPrice];
54 auto const lpTokens = ctx.
tx[~sfLPTokenOut];
55 auto const tradingFee = ctx.
tx[~sfTradingFee];
65 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid flags.";
71 if (!lpTokens || ePrice || (amount && !amount2) ||
72 (!amount && amount2) || tradingFee)
78 if (!amount || amount2 || ePrice || tradingFee)
84 if (!amount || !amount2 || ePrice || tradingFee)
89 if (!amount || !lpTokens || amount2 || ePrice || tradingFee)
94 if (!amount || !ePrice || lpTokens || amount2 || tradingFee)
99 if (!amount || !amount2 || ePrice || lpTokens)
103 auto const asset = ctx.
tx[sfAsset].get<
Issue>();
104 auto const asset2 = ctx.
tx[sfAsset2].get<
Issue>();
107 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid asset pair.";
111 if (amount && amount2 && amount->issue() == amount2->issue())
113 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid tokens, same issue."
114 << amount->issue() <<
" " << amount2->issue();
118 if (lpTokens && *lpTokens <= beast::zero)
120 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens";
131 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount";
141 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid amount2";
147 if (amount && ePrice)
154 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid EPrice";
161 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid trading fee.";
171 auto const accountID = ctx.
tx[sfAccount];
177 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: Invalid asset pair.";
189 return expected.error();
190 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
193 if (lptAMMBalance != beast::zero)
195 if (amountBalance != beast::zero || amount2Balance != beast::zero)
198 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: tokens balance is not zero.";
205 if (lptAMMBalance == beast::zero)
207 if (amountBalance <= beast::zero || amount2Balance <= beast::zero ||
208 lptAMMBalance < beast::zero)
212 <<
"AMM Deposit: reserves or tokens balance is zero.";
223 auto balance = [&](
auto const&
deposit) ->
TER {
226 auto const lpIssue = (*ammSle)[sfLPTokenBalance].issue();
229 keylet::line(accountID, lpIssue.account, lpIssue.currency));
236 return (accountID ==
deposit.issue().account ||
251 auto checkAsset = [&](
Issue const& asset) ->
TER {
255 <<
"AMM Deposit: account is not authorized, " << asset;
262 <<
"AMM Deposit: account or currency is frozen, "
271 if (
auto const ter = checkAsset(ctx.
tx[sfAsset].get<
Issue>()))
274 if (
auto const ter = checkAsset(ctx.
tx[sfAsset2].get<
Issue>()))
278 auto const amount = ctx.
tx[~sfAmount];
279 auto const amount2 = ctx.
tx[~sfAmount2];
280 auto const ammAccountID = ammSle->getAccountID(sfAccount);
283 bool checkBalance) ->
TER {
294 <<
"AMM Deposit: account is not authorized, "
303 <<
"AMM Deposit: AMM account or currency is frozen, "
310 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: account is frozen, "
317 if (
auto const ter = balance(*amount))
320 <<
"AMM Deposit: account has insufficient funds, "
332 if (
auto const ter = checkAmount(amount,
true))
335 if (
auto const ter = checkAmount(amount2,
true))
340 if (
auto const ter = checkAmount(amountBalance,
false))
342 if (
auto const ter = checkAmount(amount2Balance,
false))
347 if (
auto const lpTokens = ctx.
tx[~sfLPTokenOut];
348 lpTokens && lpTokens->issue() != lptAMMBalance.issue())
350 JLOG(ctx.
j.
debug()) <<
"AMM Deposit: invalid LPTokens.";
360 if (xrpBalance <= beast::zero)
362 JLOG(ctx.
j.
debug()) <<
"AMM Instance: insufficient reserves";
373 auto const amount =
ctx_.
tx[~sfAmount];
374 auto const amount2 =
ctx_.
tx[~sfAmount2];
375 auto const ePrice =
ctx_.
tx[~sfEPrice];
376 auto const lpTokensDeposit =
ctx_.
tx[~sfLPTokenOut];
390 return {expected.error(),
false};
391 auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected;
392 auto const tfee = (lptAMMBalance == beast::zero)
393 ?
ctx_.
tx[~sfTradingFee].value_or(0)
398 auto const [result, newLPTokenBalance] =
400 &amountBalance = amountBalance,
401 &amount2Balance = amount2Balance,
458 lptAMMBalance.issue(),
462 JLOG(
j_.
error()) <<
"AMM Deposit: invalid options.";
470 newLPTokenBalance > beast::zero,
471 "ripple::AMMDeposit::applyGuts : valid new LP token balance");
472 ammSle->setFieldAmount(sfLPTokenBalance, newLPTokenBalance);
475 if (lptAMMBalance == beast::zero)
477 sb, ammSle,
account_, lptAMMBalance.issue(), tfee);
515 auto checkBalance = [&](
auto const& depositAmount) ->
TER {
516 if (depositAmount <= beast::zero)
518 if (
isXRP(depositAmount))
520 auto const& lpIssue = lpTokensDeposit.
issue();
528 account_ == depositAmount.issue().account ||
532 depositAmount.issue(),
540 [amountDepositActual, amount2DepositActual, lpTokensDepositActual] =
550 if (lpTokensDepositActual <= beast::zero)
556 if (amountDepositActual < depositMin ||
557 amount2DepositActual < deposit2Min ||
558 lpTokensDepositActual < lpTokensDepositMin)
561 <<
"AMM Deposit: min deposit fails " << amountDepositActual <<
" "
563 << amount2DepositActual.value_or(
STAmount{}) <<
" "
570 if (
auto const ter = checkBalance(amountDepositActual))
573 "checkBalance to deposit or is 0"
574 << amountDepositActual;
588 <<
"AMM Deposit: failed to deposit " << amountDepositActual;
593 if (amount2DepositActual)
595 if (
auto const ter = checkBalance(*amount2DepositActual))
598 <<
"AMM Deposit: account has insufficient checkBalance to "
600 << *amount2DepositActual;
608 *amount2DepositActual,
614 <<
"AMM Deposit: failed to deposit " << *amount2DepositActual;
628 return {
tesSUCCESS, lptAMMBalance + lpTokensDepositActual};
649 divide(lpTokensDeposit, lptAMMBalance, lptAMMBalance.
issue());
666 JLOG(
j_.
error()) <<
"AMMDeposit::equalDepositTokens exception "
713 auto frac =
Number{amount} / amountBalance;
715 if (tokens == beast::zero)
717 auto const amount2Deposit = amount2Balance * frac;
718 if (amount2Deposit <= amount2)
731 frac =
Number{amount2} / amount2Balance;
733 if (tokens == beast::zero)
735 auto const amountDeposit = amountBalance * frac;
736 if (amountDeposit <= amount)
770 auto const tokens =
lpTokensIn(amountBalance, amount, lptAMMBalance, tfee);
771 if (tokens == beast::zero)
804 auto const amountDeposit =
805 ammAssetIn(amountBalance, lptAMMBalance, lpTokensDeposit, tfee);
806 if (amountDeposit > amount)
857 if (amount != beast::zero)
860 lpTokensIn(amountBalance, amount, lptAMMBalance, tfee);
861 if (tokens <= beast::zero)
863 auto const ep =
Number{amount} / tokens;
898 auto const c = f1 * amountBalance / (ePrice * lptAMMBalance);
899 auto const d = f1 + c * f2 - c;
900 auto const a1 = c * c;
901 auto const b1 = c * c * f2 * f2 + 2 * c - d * d;
902 auto const c1 = 2 * c * f2 * f2 + 1 - 2 * d * f2;
904 amountBalance.
issue(),
906 if (amountDeposit <= beast::zero)
930 Issue const& lptIssue,
std::pair< TER, bool > applyGuts(Sandbox &view)
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 > 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.
static TER preclaim(PreclaimContext const &ctx)
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 > 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 > 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)
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 > 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.
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
virtual Rules const & rules() const =0
Returns the tx processing rules.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Issue const & issue() 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.
constexpr std::uint32_t tfSingleAsset
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Issue, Issue > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
STAmount divide(STAmount const &amount, Rate const &rate)
STAmount lpTokensIn(STAmount const &asset1Balance, STAmount const &asset1Deposit, STAmount const &lptAMMBalance, std::uint16_t tfee)
Calculate LP Tokens given asset's deposit amount.
bool isXRP(AccountID const &c)
bool isIndividualFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
std::uint16_t getTradingFee(ReadView const &view, SLE const &ammSle, AccountID const &account)
Get AMM trading fee for the given account.
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)
TER requireAuth(ReadView const &view, Issue const &issue, AccountID const &account)
Check if the account lacks required authorization.
STAmount toSTAmount(IOUAmount const &iou, Issue const &iss)
constexpr std::uint32_t tfLimitLPToken
STAmount ammAssetIn(STAmount const &asset1Balance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset deposit given LP Tokens.
STAmount multiply(STAmount const &amount, Rate const &rate)
bool ammEnabled(Rules const &)
Return true if required AMM amendments are enabled.
NotTEC preflight1(PreflightContext const &ctx)
Performs early sanity checks on the account and fee fields.
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, bool isDeposit)
Calls adjustLPTokens() and adjusts deposit or withdraw amounts if the adjusted LP tokens are less tha...
constexpr std::uint32_t tfOneAssetLPToken
bool isFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
AccountID ammAccountID(std::uint16_t prefix, uint256 const &parentHash, uint256 const &ammID)
Calculate AMM account ID.
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.
constexpr std::uint32_t tfTwoAsset
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.
constexpr std::uint32_t tfDepositSubTx
NotTEC preflight2(PreflightContext const &ctx)
Checks whether the signature appears valid.
constexpr std::uint32_t tfLPToken
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)
constexpr std::uint32_t tfDepositMask
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.
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Issue const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
std::string to_string(base_uint< Bits, Tag > const &a)
constexpr std::uint32_t tfTwoAssetIfEmpty
Number feeMultHalf(std::uint16_t tfee)
Get fee multiplier (1 - tfee / 2) @tfee trading fee in basis points.
TERSubset< CanCvtToTER > TER
std::uint16_t constexpr TRADING_FEE_THRESHOLD
TER accountSend(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee)
Calls static accountSendIOU if saAmount represents Issue.
TERSubset< CanCvtToNotTEC > NotTEC
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.