xrpld
Loading...
Searching...
No Matches
AMMBid.cpp
1#include <xrpl/tx/transactors/dex/AMMBid.h>
2
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>
25
26#include <algorithm>
27#include <chrono>
28#include <cstdint>
29#include <expected>
30#include <optional>
31#include <set>
32#include <utility>
33
34namespace xrpl {
35
36bool
38{
39 return ctx.rules.enabled(featureMPTokensV2) ||
40 (!ctx.tx[sfAsset].holds<MPTIssue>() && !ctx.tx[sfAsset2].holds<MPTIssue>());
41}
42
45{
46 if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2]))
47 {
48 JLOG(ctx.j.debug()) << "AMM Bid: Invalid asset pair.";
49 return res;
50 }
51
52 if (auto const bidMin = ctx.tx[~sfBidMin])
53 {
54 if (auto const res = invalidAMMAmount(*bidMin))
55 {
56 JLOG(ctx.j.debug()) << "AMM Bid: invalid min slot price.";
57 return res;
58 }
59 }
60
61 if (auto const bidMax = ctx.tx[~sfBidMax])
62 {
63 if (auto const res = invalidAMMAmount(*bidMax))
64 {
65 JLOG(ctx.j.debug()) << "AMM Bid: invalid max slot price.";
66 return res;
67 }
68 }
69
70 if (ctx.tx.isFieldPresent(sfAuthAccounts))
71 {
72 auto const authAccounts = ctx.tx.getFieldArray(sfAuthAccounts);
73 if (authAccounts.size() > kAuctionSlotMaxAuthAccounts)
74 {
75 JLOG(ctx.j.debug()) << "AMM Bid: Invalid number of AuthAccounts.";
76 return temMALFORMED;
77 }
78 if (ctx.rules.enabled(fixAMMv1_3))
79 {
80 AccountID const account = ctx.tx[sfAccount];
82 for (auto const& obj : authAccounts)
83 {
84 auto const authAccount = obj[sfAccount];
85 if (authAccount == account || unique.contains(authAccount))
86 {
87 JLOG(ctx.j.debug()) << "AMM Bid: Invalid auth.account.";
88 return temMALFORMED;
89 }
90 unique.insert(authAccount);
91 }
92 }
93 }
94
95 return tesSUCCESS;
96}
97
98TER
100{
101 auto const ammSle = ctx.view.read(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2]));
102 if (!ammSle)
103 {
104 JLOG(ctx.j.debug()) << "AMM Bid: Invalid asset pair.";
105 return terNO_AMM;
106 }
107
108 auto const lpTokensBalance = (*ammSle)[sfLPTokenBalance];
109 if (lpTokensBalance == beast::kZero)
110 return tecAMM_EMPTY;
111
112 if (ctx.tx.isFieldPresent(sfAuthAccounts))
113 {
114 for (auto const& account : ctx.tx.getFieldArray(sfAuthAccounts))
115 {
116 if (!ctx.view.read(keylet::account(account[sfAccount])))
117 {
118 JLOG(ctx.j.debug()) << "AMM Bid: Invalid Account.";
119 return terNO_ACCOUNT;
120 }
121 }
122 }
123
124 auto const lpTokens = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j);
125 // Not LP
126 if (lpTokens == beast::kZero)
127 {
128 JLOG(ctx.j.debug()) << "AMM Bid: account is not LP.";
130 }
131
132 auto const bidMin = ctx.tx[~sfBidMin];
133
134 if (bidMin)
135 {
136 if (bidMin->asset() != lpTokens.asset())
137 {
138 JLOG(ctx.j.debug()) << "AMM Bid: Invalid LPToken.";
139 return temBAD_AMM_TOKENS;
140 }
141 if (*bidMin > lpTokens || *bidMin >= lpTokensBalance)
142 {
143 JLOG(ctx.j.debug()) << "AMM Bid: Invalid Tokens.";
145 }
146 }
147
148 auto const bidMax = ctx.tx[~sfBidMax];
149 if (bidMax)
150 {
151 if (bidMax->asset() != lpTokens.asset())
152 {
153 JLOG(ctx.j.debug()) << "AMM Bid: Invalid LPToken.";
154 return temBAD_AMM_TOKENS;
155 }
156 if (*bidMax > lpTokens || *bidMax >= lpTokensBalance)
157 {
158 JLOG(ctx.j.debug()) << "AMM Bid: Invalid Tokens.";
160 }
161 }
162
163 if (bidMin && bidMax && bidMin > bidMax)
164 {
165 JLOG(ctx.j.debug()) << "AMM Bid: Invalid Max/MinSlotPrice.";
167 }
168
169 return tesSUCCESS;
170}
171
174{
175 using namespace std::chrono;
176 auto const ammSle = sb.peek(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2]));
177 if (!ammSle)
178 return {tecINTERNAL, false};
179 STAmount const lptAMMBalance = (*ammSle)[sfLPTokenBalance];
180 auto const lpTokens = ammLPHolds(sb, *ammSle, account, ctx.journal);
181
182 XRPL_ASSERT(ammSle->isFieldPresent(sfAuctionSlot), "xrpl::applyBid : has auction slot");
183 if (!ammSle->isFieldPresent(sfAuctionSlot))
184 return {tecINTERNAL, false};
185
186 auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot);
187 auto const current =
189 // Auction slot discounted fee
190 auto const ammTradingFee = (*ammSle)[sfTradingFee];
191 auto const discountedFee = ammTradingFee / kAuctionSlotDiscountedFeeFraction;
192 // Min price
193 auto const minSlotPrice = ammAuctionMinSlotPrice(lptAMMBalance, ammTradingFee);
194
195 static constexpr std::uint32_t kTailingSlot = kAuctionSlotTimeIntervals - 1;
196
197 // If seated then it is the current slot-holder time slot, otherwise
198 // the auction slot is not owned. Slot range is in {0-19}
199 auto const timeSlot = ammAuctionTimeSlot(current, auctionSlot);
200
201 // Account must exist and the slot not expired.
202 auto const validOwner = [&](AccountID const& account) {
203 // Valid range is 0-19 but the tailing slot pays MinSlotPrice
204 // and doesn't refund so the check is < instead of <= to optimize.
205 return timeSlot && *timeSlot < kTailingSlot && sb.read(keylet::account(account));
206 };
207
208 auto const updateSlot =
209 [&](std::uint32_t fee, Number const& minPrice, Number const& burn) -> TER {
210 auctionSlot.setAccountID(sfAccount, account);
211 auctionSlot.setFieldU32(sfExpiration, current + kTotalTimeSlotSecs);
212 if (fee != 0)
213 {
214 auctionSlot.setFieldU16(sfDiscountedFee, fee);
215 }
216 else if (auctionSlot.isFieldPresent(sfDiscountedFee))
217 {
218 auctionSlot.makeFieldAbsent(sfDiscountedFee);
219 }
220 auctionSlot.setFieldAmount(sfPrice, toSTAmount(lpTokens.asset(), minPrice));
221 if (ctx.tx.isFieldPresent(sfAuthAccounts))
222 {
223 auctionSlot.setFieldArray(sfAuthAccounts, ctx.tx.getFieldArray(sfAuthAccounts));
224 }
225 else
226 {
227 auctionSlot.makeFieldAbsent(sfAuthAccounts);
228 }
229 // Burn the remaining bid amount
230 auto const saBurn =
231 adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.asset(), burn), IsDeposit::No);
232 if (saBurn >= lptAMMBalance)
233 {
234 // This error case should never occur.
235 // LCOV_EXCL_START
236 JLOG(ctx.journal.fatal())
237 << "AMM Bid: LP Token burn exceeds AMM balance " << burn << " " << lptAMMBalance;
238 return tecINTERNAL;
239 // LCOV_EXCL_STOP
240 }
241 auto res = redeemIOU(sb, account, saBurn, lpTokens.get<Issue>(), ctx.journal);
242 if (!isTesSuccess(res))
243 {
244 JLOG(ctx.journal.debug()) << "AMM Bid: failed to redeem.";
245 return res;
246 }
247 ammSle->setFieldAmount(sfLPTokenBalance, lptAMMBalance - saBurn);
248 sb.update(ammSle);
249 return tesSUCCESS;
250 };
251
252 TER res = tesSUCCESS;
253
254 auto const bidMin = ctx.tx[~sfBidMin];
255 auto const bidMax = ctx.tx[~sfBidMax];
256
257 auto const getPayPrice = [&](Number const& computedPrice) -> std::expected<Number, TER> {
258 auto effectivePrice = computedPrice;
259 if (ctx.view().rules().enabled(fixCleanup3_4_0) && ammTradingFee == 0)
260 {
261 // Prevent zero-fee pools from granting auction slots at zero or dust prices.
262 effectivePrice = std::max(effectivePrice, ammAuctionMinSlotPrice(lptAMMBalance, 1));
263 }
264 auto const payPrice = [&] -> std::optional<Number> {
265 // Both min/max bid price are defined
266 if (bidMin && bidMax)
267 {
268 if (effectivePrice <= *bidMax)
269 return std::max(effectivePrice, Number(*bidMin));
270 JLOG(ctx.journal.debug()) << "AMM Bid: not in range " << effectivePrice << " "
271 << *bidMin << " " << *bidMax;
272 return std::nullopt;
273 }
274 // Bidder pays max(bidPrice, effectivePrice)
275 if (bidMin)
276 {
277 return std::max(effectivePrice, Number(*bidMin));
278 }
279 if (bidMax)
280 {
281 if (effectivePrice <= *bidMax)
282 return effectivePrice;
283 JLOG(ctx.journal.debug())
284 << "AMM Bid: not in range " << effectivePrice << " " << *bidMax;
285 return std::nullopt;
286 }
287
288 return effectivePrice;
289 }();
290 if (!payPrice)
291 {
293 }
294 if (payPrice > lpTokens)
295 {
297 }
298 return *payPrice;
299 };
300
301 // No one owns the slot or expired slot.
302 if (auto const acct = auctionSlot[~sfAccount]; !acct || !validOwner(*acct))
303 {
304 auto const payPrice = getPayPrice(minSlotPrice);
305 if (!payPrice)
306 {
307 return {payPrice.error(), false};
308 }
309
310 res = updateSlot(discountedFee, *payPrice, *payPrice);
311 }
312 else
313 {
314 // Price the slot was purchased at.
315 STAmount const pricePurchased = auctionSlot[sfPrice];
316 XRPL_ASSERT(timeSlot, "xrpl::applyBid : timeSlot is set");
317 // NOLINTBEGIN(bugprone-unchecked-optional-access)
318 auto const fractionUsed = (Number(*timeSlot) + 1) / kAuctionSlotTimeIntervals;
319 auto const fractionRemaining = Number(1) - fractionUsed;
320 auto const computedPrice = [&] -> Number {
321 auto const p105 = Number(105, -2);
322 // First interval slot price
323 if (*timeSlot == 0)
324 return pricePurchased * p105 + minSlotPrice;
325 // Other intervals slot price
326 return pricePurchased * p105 * (1 - power(fractionUsed, 60)) + minSlotPrice;
327 }();
328 // NOLINTEND(bugprone-unchecked-optional-access)
329
330 auto const payPrice = getPayPrice(computedPrice);
331
332 if (!payPrice)
333 return {payPrice.error(), false};
334
335 // Refund the previous owner. If the time slot is 0 then
336 // the owner is refunded 95% of the amount.
337 auto const refund = fractionRemaining * pricePurchased;
338 if (refund > *payPrice)
339 {
340 // This error case should never occur.
341 JLOG(ctx.journal.fatal())
342 << "AMM Bid: refund exceeds payPrice " << refund << " " << *payPrice;
343 return {tecINTERNAL, false};
344 }
345 res = accountSend(
346 sb, account, auctionSlot[sfAccount], toSTAmount(lpTokens.asset(), refund), ctx.journal);
347 if (!isTesSuccess(res))
348 {
349 JLOG(ctx.journal.debug()) << "AMM Bid: failed to refund.";
350 return {res, false};
351 }
352
353 auto const burn = *payPrice - refund;
354 res = updateSlot(discountedFee, *payPrice, burn);
355 }
356
357 return {res, isTesSuccess(res)};
358}
359
360TER
362{
363 // This is the ledger view that we work against. Transactions are applied
364 // as we go on processing transactions.
365 Sandbox sb(&ctx_.view());
366
367 auto const result = applyBid(ctx_, sb, accountID_, j_);
368 if (result.second)
369 sb.apply(ctx_.rawView());
370
371 return result.first;
372}
373
374void
376{
377 // No transaction-specific invariants yet (future work).
378}
379
380bool
382{
383 // No transaction-specific invariants yet (future work).
384 return true;
385}
386
387} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream debug() const
Definition Journal.h:344
TER doApply() override
Definition AMMBid.cpp:361
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.
Definition AMMBid.cpp:381
static NotTEC preflight(PreflightContext const &ctx)
Definition AMMBid.cpp:44
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Definition AMMBid.cpp:375
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition AMMBid.cpp:37
static TER preclaim(PreclaimContext const &ctx)
Definition AMMBid.cpp:99
State information when applying a tx.
STTx const & tx
beast::Journal const journal
ApplyView & view()
A currency issued by an account.
Definition Issue.h:18
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
A view into a ledger.
Definition ReadView.h:41
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.
Definition Rules.cpp:182
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry const > const & ConstRef
STArray const & getFieldArray(SField const &field) const
Definition STObject.cpp:688
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
beast::Journal const j_
Definition Transactor.h:164
AccountID const accountID_
Definition Transactor.h:166
ApplyContext & ctx_
Definition Transactor.h:162
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)
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
Definition AMMCore.cpp:96
@ terNO_AMM
Definition TER.h:229
@ terNO_ACCOUNT
Definition TER.h:219
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
Definition AMMCore.h:19
constexpr std::uint32_t kAuctionSlotDiscountedFeeFraction
Definition AMMCore.h:23
Number ammAuctionMinSlotPrice(Number const &lptAMMBalance, std::uint16_t tradingFee)
Minimum auction slot price: LPTokens * TradingFee / kAuctionSlotMinFeeFraction.
Definition AMMCore.h:94
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
Definition AMMCore.cpp:81
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
Definition TER.h:617
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.
Definition AccountID.h:34
static std::pair< TER, bool > applyBid(ApplyContext &ctx, Sandbox &sb, AccountID const &account, beast::Journal j)
Definition AMMBid.cpp:173
TER redeemIOU(ApplyView &view, AccountID const &account, STAmount const &amount, Issue const &issue, beast::Journal j)
constexpr std::uint16_t kAuctionSlotTimeIntervals
Definition AMMCore.h:20
@ temBAD_AMM_TOKENS
Definition TER.h:117
@ temMALFORMED
Definition TER.h:75
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
std::optional< std::uint8_t > ammAuctionTimeSlot(std::uint64_t current, STObject const &auctionSlot)
Get time slot of the auction slot.
Definition AMMCore.cpp:109
@ tecAMM_EMPTY
Definition TER.h:343
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecAMM_FAILED
Definition TER.h:341
@ tecINTERNAL
Definition TER.h:321
constexpr std::uint16_t kAuctionSlotMaxAuthAccounts
Definition AMMCore.h:21
@ tesSUCCESS
Definition TER.h:253
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
NetClock::time_point parentCloseTime
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46
T time_since_epoch(T... args)
T unexpected(T... args)