1#include <xrpl/tx/transactors/dex/AMMBid.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/RippleStateHelpers.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/Feature.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/Issue.h>
17#include <xrpl/protocol/MPTIssue.h>
18#include <xrpl/protocol/SField.h>
19#include <xrpl/protocol/STLedgerEntry.h>
20#include <xrpl/protocol/STTx.h>
21#include <xrpl/protocol/TER.h>
22#include <xrpl/protocol/XRPAmount.h>
23#include <xrpl/tx/ApplyContext.h>
24#include <xrpl/tx/Transactor.h>
48 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid asset pair.";
52 if (
auto const bidMin = ctx.
tx[~sfBidMin])
56 JLOG(ctx.
j.
debug()) <<
"AMM Bid: invalid min slot price.";
61 if (
auto const bidMax = ctx.
tx[~sfBidMax])
65 JLOG(ctx.
j.
debug()) <<
"AMM Bid: invalid max slot price.";
75 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid number of AuthAccounts.";
82 for (
auto const& obj : authAccounts)
84 auto const authAccount = obj[sfAccount];
85 if (authAccount == account || unique.contains(authAccount))
87 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid auth.account.";
90 unique.insert(authAccount);
104 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid asset pair.";
108 auto const lpTokensBalance = (*ammSle)[sfLPTokenBalance];
118 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid Account.";
128 JLOG(ctx.
j.
debug()) <<
"AMM Bid: account is not LP.";
132 auto const bidMin = ctx.
tx[~sfBidMin];
136 if (bidMin->asset() != lpTokens.asset())
138 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid LPToken.";
141 if (*bidMin > lpTokens || *bidMin >= lpTokensBalance)
143 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid Tokens.";
148 auto const bidMax = ctx.
tx[~sfBidMax];
151 if (bidMax->asset() != lpTokens.asset())
153 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid LPToken.";
156 if (*bidMax > lpTokens || *bidMax >= lpTokensBalance)
158 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid Tokens.";
163 if (bidMin && bidMax && bidMin > bidMax)
165 JLOG(ctx.
j.
debug()) <<
"AMM Bid: Invalid Max/MinSlotPrice.";
179 STAmount const lptAMMBalance = (*ammSle)[sfLPTokenBalance];
182 XRPL_ASSERT(ammSle->isFieldPresent(sfAuctionSlot),
"xrpl::applyBid : has auction slot");
183 if (!ammSle->isFieldPresent(sfAuctionSlot))
186 auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot);
190 auto const ammTradingFee = (*ammSle)[sfTradingFee];
202 auto const validOwner = [&](
AccountID const& account) {
208 auto const updateSlot =
210 auctionSlot.setAccountID(sfAccount, account);
214 auctionSlot.setFieldU16(sfDiscountedFee, fee);
216 else if (auctionSlot.isFieldPresent(sfDiscountedFee))
218 auctionSlot.makeFieldAbsent(sfDiscountedFee);
220 auctionSlot.setFieldAmount(sfPrice,
toSTAmount(lpTokens.asset(), minPrice));
223 auctionSlot.setFieldArray(sfAuthAccounts, ctx.
tx.
getFieldArray(sfAuthAccounts));
227 auctionSlot.makeFieldAbsent(sfAuthAccounts);
232 if (saBurn >= lptAMMBalance)
237 <<
"AMM Bid: LP Token burn exceeds AMM balance " << burn <<
" " << lptAMMBalance;
244 JLOG(ctx.
journal.
debug()) <<
"AMM Bid: failed to redeem.";
247 ammSle->setFieldAmount(sfLPTokenBalance, lptAMMBalance - saBurn);
254 auto const bidMin = ctx.
tx[~sfBidMin];
255 auto const bidMax = ctx.
tx[~sfBidMax];
257 auto const getPayPrice = [&](
Number const& computedPrice) -> std::expected<Number, TER> {
258 auto effectivePrice = computedPrice;
266 if (bidMin && bidMax)
268 if (effectivePrice <= *bidMax)
270 JLOG(ctx.
journal.
debug()) <<
"AMM Bid: not in range " << effectivePrice <<
" "
271 << *bidMin <<
" " << *bidMax;
281 if (effectivePrice <= *bidMax)
282 return effectivePrice;
284 <<
"AMM Bid: not in range " << effectivePrice <<
" " << *bidMax;
288 return effectivePrice;
294 if (payPrice > lpTokens)
302 if (
auto const acct = auctionSlot[~sfAccount]; !acct || !validOwner(*acct))
304 auto const payPrice = getPayPrice(minSlotPrice);
307 return {payPrice.error(),
false};
310 res = updateSlot(discountedFee, *payPrice, *payPrice);
315 STAmount const pricePurchased = auctionSlot[sfPrice];
316 XRPL_ASSERT(timeSlot,
"xrpl::applyBid : timeSlot is set");
319 auto const fractionRemaining =
Number(1) - fractionUsed;
320 auto const computedPrice = [&] ->
Number {
321 auto const p105 =
Number(105, -2);
324 return pricePurchased * p105 + minSlotPrice;
326 return pricePurchased * p105 * (1 -
power(fractionUsed, 60)) + minSlotPrice;
330 auto const payPrice = getPayPrice(computedPrice);
333 return {payPrice.error(),
false};
337 auto const refund = fractionRemaining * pricePurchased;
338 if (refund > *payPrice)
342 <<
"AMM Bid: refund exceeds payPrice " << refund <<
" " << *payPrice;
346 sb, account, auctionSlot[sfAccount],
toSTAmount(lpTokens.asset(), refund), ctx.
journal);
349 JLOG(ctx.
journal.
debug()) <<
"AMM Bid: failed to refund.";
353 auto const burn = *payPrice - refund;
354 res = updateSlot(discountedFee, *payPrice, burn);
A generic endpoint for log messages.
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.
static NotTEC preflight(PreflightContext const &ctx)
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
static bool checkExtraFeatures(PreflightContext const &ctx)
static TER preclaim(PreclaimContext const &ctx)
State information when applying a tx.
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 SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
virtual LedgerHeader const & header() const =0
Returns information about the ledger.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Asset const & asset() const
std::shared_ptr< STLedgerEntry const > const & ConstRef
STArray const & getFieldArray(SField const &field) const
bool isFieldPresent(SField const &field) 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.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
T duration_cast(T... args)
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Keylet account(AccountID const &id) noexcept
AccountID root.
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 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.
constexpr std::uint32_t kTotalTimeSlotSecs
constexpr std::uint32_t kAuctionSlotDiscountedFeeFraction
Number ammAuctionMinSlotPrice(Number const &lptAMMBalance, std::uint16_t tradingFee)
Minimum auction slot price: LPTokens * TradingFee / kAuctionSlotMinFeeFraction.
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
STAmount adjustLPTokens(STAmount const &lptAMMBalance, STAmount const &lpTokens, IsDeposit isDeposit)
Adjust LP tokens to deposit/withdraw.
Number power(Number const &f, unsigned n)
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.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
static std::pair< TER, bool > applyBid(ApplyContext &ctx, Sandbox &sb, AccountID const &account, beast::Journal j)
TER redeemIOU(ApplyView &view, AccountID const &account, STAmount const &amount, Issue const &issue, beast::Journal j)
constexpr std::uint16_t kAuctionSlotTimeIntervals
bool isTesSuccess(TER x) noexcept
TERSubset< CanCvtToTER > TER
std::optional< std::uint8_t > ammAuctionTimeSlot(std::uint64_t current, STObject const &auctionSlot)
Get time slot of the auction slot.
constexpr std::uint16_t kAuctionSlotMaxAuthAccounts
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.
T time_since_epoch(T... args)