xrpld
Loading...
Searching...
No Matches
BookStep.cpp
1#include <xrpl/basics/Log.h>
2#include <xrpl/basics/base_uint.h>
3#include <xrpl/basics/contract.h>
4#include <xrpl/beast/utility/Journal.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/ledger/ApplyView.h>
8#include <xrpl/ledger/PaymentSandbox.h>
9#include <xrpl/ledger/Sandbox.h>
10#include <xrpl/ledger/helpers/AMMHelpers.h>
11#include <xrpl/ledger/helpers/AccountRootHelpers.h>
12#include <xrpl/ledger/helpers/MPTokenHelpers.h>
13#include <xrpl/ledger/helpers/TokenHelpers.h>
14#include <xrpl/protocol/AccountID.h>
15#include <xrpl/protocol/Asset.h>
16#include <xrpl/protocol/Book.h>
17#include <xrpl/protocol/Concepts.h>
18#include <xrpl/protocol/Feature.h>
19#include <xrpl/protocol/IOUAmount.h>
20#include <xrpl/protocol/Indexes.h>
21#include <xrpl/protocol/Issue.h>
22#include <xrpl/protocol/LedgerFormats.h>
23#include <xrpl/protocol/MPTAmount.h>
24#include <xrpl/protocol/MPTIssue.h>
25#include <xrpl/protocol/Quality.h>
26#include <xrpl/protocol/Rate.h>
27#include <xrpl/protocol/SField.h>
28#include <xrpl/protocol/STAmount.h>
29#include <xrpl/protocol/TER.h>
30#include <xrpl/protocol/XRPAmount.h>
31#include <xrpl/tx/paths/AMMLiquidity.h>
32#include <xrpl/tx/paths/AMMOffer.h>
33#include <xrpl/tx/paths/BookTip.h>
34#include <xrpl/tx/paths/OfferStream.h>
35#include <xrpl/tx/paths/detail/EitherAmount.h>
36#include <xrpl/tx/paths/detail/FlatSets.h>
37#include <xrpl/tx/paths/detail/Steps.h>
38
39#include <boost/container/flat_set.hpp>
40
41#include <cstdint>
42#include <memory>
43#include <numeric>
44#include <optional>
45#include <sstream>
46#include <stdexcept>
47#include <string>
48#include <string_view>
49#include <type_traits>
50#include <utility>
51#include <variant>
52
53namespace xrpl {
54
55template <class TIn, class TOut, class TDerived>
56class BookStep : public StepImp<TIn, TOut, BookStep<TIn, TOut, TDerived>>
57{
58protected:
59 enum class OfferType { Amm, Clob };
60
61 static constexpr uint32_t kMaxOffersToConsume{1000};
65 // Charge transfer fees when the prev step redeems
66 Step const* const prevStep_ = nullptr;
68 // Mark as inactive (dry) if too many offers are consumed
69 bool inactive_ = false;
79 // If set, AMM liquidity might be available
80 // if AMM offer quality is better than CLOB offer
81 // quality or there is no CLOB offer.
85 // MaximumAmount of book_.in if it is an MPT. Taking an MPT offer has the
86 // issuer send TakerPays to the owner, and a send above the cap is rejected
87 // (isMPTOverflow). forEachOffer limits the offer's input to the cap so it
88 // fills partially instead of failing the strand.
90
91 struct Cache
92 {
93 TIn in;
94 TOut out;
95
96 Cache(TIn const& in, TOut const& out) : in(in), out(out)
97 {
98 }
99 };
100
102
103private:
104 BookStep(StrandContext const& ctx, Asset const& in, Asset const& out)
105 : book_(in, out, ctx.domainID)
106 , strandSrc_(ctx.strandSrc)
107 , strandDst_(ctx.strandDst)
108 , prevStep_(ctx.prevStep)
109 , ownerPaysTransferFee_(ctx.ownerPaysTransferFee)
110 , j_(ctx.j)
111 , strandDeliver_(ctx.strandDeliver)
112 {
113 if constexpr (std::is_same_v<TIn, MPTAmount>)
114 {
115 if (auto const max = maxMPTAmount(ctx.view, in.get<MPTIssue>().getMptID()))
116 maxIn_.emplace(*max);
117 }
118
119 if (auto const ammSle = ctx.view.read(keylet::amm(in, out));
120 ammSle && ammSle->getFieldAmount(sfLPTokenBalance) != beast::kZero)
121 {
122 ammLiquidity_.emplace(
123 ctx.view,
124 (*ammSle)[sfAccount],
125 getTradingFee(ctx.view, *ammSle, ctx.ammContext.account()),
126 in,
127 out,
128 ctx.ammContext,
129 ctx.j);
130 }
131 }
132
133public:
134 [[nodiscard]] Book const&
135 book() const
136 {
137 return book_;
138 }
139
140 [[nodiscard]] std::optional<EitherAmount>
141 cachedIn() const override
142 {
143 if (!cache_)
144 return std::nullopt;
145 return EitherAmount(cache_->in);
146 }
147
148 [[nodiscard]] std::optional<EitherAmount>
149 cachedOut() const override
150 {
151 if (!cache_)
152 return std::nullopt;
153 return EitherAmount(cache_->out);
154 }
155
156 [[nodiscard]] DebtDirection
161
162 [[nodiscard]] std::optional<Book>
163 bookStepBook() const override
164 {
165 return book_;
166 }
167
169 qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const override;
170
172 getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const override;
173
174 [[nodiscard]] std::uint32_t
175 offersUsed() const override;
176
179 PaymentSandbox& sb,
180 ApplyView& afView,
181 boost::container::flat_set<UInt256>& ofrsToRm,
182 TOut const& out);
183
186 PaymentSandbox& sb,
187 ApplyView& afView,
188 boost::container::flat_set<UInt256>& ofrsToRm,
189 TIn const& in);
190
192 validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override;
193
194 // Check for errors frozen constraints.
195 [[nodiscard]] TER
196 check(StrandContext const& ctx) const;
197
198 [[nodiscard]] bool
199 inactive() const override
200 {
201 return inactive_;
202 }
203
204protected:
206 logStringImpl(char const* name) const
207 {
209 ostr << name << ": "
210 << "\ninIss: " << book_.in.getIssuer() << "\noutIss: " << book_.out.getIssuer()
211 << "\ninCur: " << to_string(book_.in) << "\noutCur: " << to_string(book_.out);
212 return ostr.str();
213 }
214
215 [[nodiscard]] Rate
216 rate(ReadView const& view, Asset const& asset, AccountID const& dstAccount) const;
217
218private:
219 friend bool
220 operator==(BookStep const& lhs, BookStep const& rhs)
221 {
222 return lhs.book_ == rhs.book_;
223 }
224
225 friend bool
226 operator!=(BookStep const& lhs, BookStep const& rhs)
227 {
228 return !(lhs == rhs);
229 }
230
231 [[nodiscard]] bool
232 equal(Step const& rhs) const override;
233
234 // Iterate through the offers at the best quality in a book.
235 // Unfunded offers and bad offers are skipped (and returned).
236 // callback is called with the offer SLE, taker pays, taker gets.
237 // If callback returns false, don't process any more offers.
238 // Return the unfunded, bad offers and the number of offers consumed.
239 template <class Callback>
242 PaymentSandbox& sb,
243 ApplyView& afView,
244 DebtDirection prevStepDebtDir,
245 Callback& callback) const;
246
247 // Offer is either TOffer or AMMOffer
248 template <template <typename, typename> typename Offer>
249 void
251 PaymentSandbox& sb,
252 Offer<TIn, TOut>& offer,
253 TAmounts<TIn, TOut> const& ofrAmt,
254 TAmounts<TIn, TOut> const& stepAmt,
255 TOut const& ownerGives) const;
256
257 template <template <typename, typename> typename Offer>
258 void
260 PaymentSandbox& sb,
261 Offer<TIn, TOut>& offer,
262 TAmounts<TIn, TOut> const& ofrAmt,
263 TAmounts<TIn, TOut> const& stepAmt,
264 TOut const& ownerGives) const;
265
266 // If clobQuality is available and has a better quality then return nullopt,
267 // otherwise if amm liquidity is available return AMM offer adjusted based
268 // on clobQuality.
270 getAMMOffer(ReadView const& view, std::optional<Quality> const& clobQuality) const;
271
272 // If seated then it is either order book tip quality or AMMOffer,
273 // whichever is a better quality.
275 tip(ReadView const& view) const;
276 // If seated then it is either AMM or CLOB quality,
277 // whichever is a better quality. OfferType is AMM
278 // if AMM quality is better.
280 tipOfferQuality(ReadView const& view) const;
281 // If seated then it is either AMM or CLOB quality function,
282 // whichever is a better quality.
284 tipOfferQualityF(ReadView const& view) const;
285
286 // Check that takerPays/takerGets can be transferred/traded.
287 // Applies to MPT assets.
288 [[nodiscard]] bool
289 checkMPTDEX(ReadView const& view, AccountID const& owner) const;
290
291 friend TDerived;
292};
293
294//------------------------------------------------------------------------------
295
296// Flow is used in two different circumstances for transferring funds:
297// o Payments, and
298// o Offer crossing.
299// The rules for handling funds in these two cases are almost, but not
300// quite, the same.
301
302// Payment BookStep template class (not offer crossing).
303template <class TIn, class TOut>
304class BookPaymentStep : public BookStep<TIn, TOut, BookPaymentStep<TIn, TOut>>
305{
306public:
307 explicit BookPaymentStep() = default;
308
309 BookPaymentStep(StrandContext const& ctx, Asset const& in, Asset const& out)
310 : BookStep<TIn, TOut, BookPaymentStep<TIn, TOut>>(ctx, in, out)
311 {
312 }
313
316
317 // Never limit self cross quality on a payment.
318 template <template <typename, typename> typename Offer>
319 bool
321 AccountID const&,
322 AccountID const&,
323 Offer<TIn, TOut> const& offer,
326 bool) const
327 {
328 return false;
329 }
330
331 // A payment can look at offers of any quality
332 [[nodiscard]] bool
333 checkQualityThreshold(Quality const& quality) const
334 {
335 return true;
336 }
337
338 // A payment doesn't use quality threshold (limitQuality)
339 // since the strand's quality doesn't directly relate to the step's quality.
340 [[nodiscard]] std::optional<Quality>
341 qualityThreshold(Quality const& lobQuality) const
342 {
343 return lobQuality;
344 }
345
346 // For a payment ofrInRate is always the same as trIn.
348 getOfrInRate(Step const*, AccountID const&, std::uint32_t trIn) const
349 {
350 return trIn;
351 }
352
353 // For a payment ofrOutRate is always the same as trOut.
355 getOfrOutRate(Step const*, AccountID const&, AccountID const&, std::uint32_t trOut) const
356 {
357 return trOut;
358 }
359
360 [[nodiscard]] Quality
362 ReadView const& v,
363 Quality const& ofrQ,
364 DebtDirection prevStepDir,
365 WaiveTransferFee waiveFee,
366 OfferType) const
367 {
368 // Charge the offer owner, not the sender
369 // Charge a fee even if the owner is the same as the issuer
370 // (the old code does not charge a fee)
371 // Calculate amount that goes to the taker and the amount charged the
372 // offer owner
373 auto const trIn =
374 redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kParityRate;
375 // Always charge the transfer fee, even if the owner is the issuer,
376 // unless the fee is waived
377 auto const trOut = (this->ownerPaysTransferFee_ && waiveFee == WaiveTransferFee::No)
378 ? this->rate(v, this->book_.out, this->strandDst_)
379 : kParityRate;
380
381 Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))};
382 return composedQuality(q1, ofrQ);
383 }
384
385 [[nodiscard]] std::string
386 logString() const override
387 {
388 return this->logStringImpl("BookPaymentStep");
389 }
390};
391
392// Offer crossing BookStep template class (not a payment).
393template <class TIn, class TOut>
394class BookOfferCrossingStep : public BookStep<TIn, TOut, BookOfferCrossingStep<TIn, TOut>>
395{
398
399private:
400 // Helper function that throws if the optional passed to the constructor
401 // is none.
402 static Quality
404 {
405 // It's really a programming error if the quality is missing.
406 XRPL_ASSERT(limitQuality, "xrpl::BookOfferCrossingStep::getQuality : nonzero quality");
407 if (!limitQuality)
408 Throw<FlowException>(tefINTERNAL, "Offer requires quality.");
409 return *limitQuality;
410 }
411
412public:
413 BookOfferCrossingStep(StrandContext const& ctx, Asset const& in, Asset const& out)
414 : BookStep<TIn, TOut, BookOfferCrossingStep<TIn, TOut>>(ctx, in, out)
416 , qualityThreshold_(getQuality(ctx.limitQuality))
417 {
418 }
419
420 template <template <typename, typename> typename Offer>
421 bool
423 AccountID const& strandSrc,
424 AccountID const& strandDst,
425 Offer<TIn, TOut> const& offer,
428 bool const offerAttempted) const
429 {
430 // This method supports some correct but slightly surprising
431 // behavior in offer crossing. The scenario:
432 //
433 // o alice has already created one or more offers.
434 // o alice creates another offer that can be directly crossed (not
435 // autobridged) by one or more of her previously created offer(s).
436 //
437 // What does the offer crossing do?
438 //
439 // o The offer crossing could go ahead and cross the offers leaving
440 // either one reduced offer (partial crossing) or zero offers
441 // (exact crossing) in the ledger. We don't do this. And, really,
442 // the offer creator probably didn't want us to.
443 //
444 // o We could skip over the self offer in the book and only cross
445 // offers that are not our own. This would make a lot of sense,
446 // but we don't do it. Part of the rationale is that we can only
447 // operate on the tip of the order book. We can't leave an offer
448 // behind -- it would sit on the tip and block access to other
449 // offers.
450 //
451 // o We could delete the self-crossable offer(s) off the tip of the
452 // book and continue with offer crossing. That's what we do.
453 //
454 // To support this scenario offer crossing has a special rule. If:
455 // a. We're offer crossing using default path (no autobridging), and
456 // b. The offer's quality is at least as good as our quality, and
457 // c. We're about to cross one of our own offers, then
458 // d. Delete the old offer from the ledger.
459 if (defaultPath_ && offer.quality() >= qualityThreshold_ && strandSrc == offer.owner() &&
460 strandDst == offer.owner())
461 {
462 // Remove this offer even if no crossing occurs.
463 if (auto const key = offer.key())
464 offers.permRmOffer(*key);
465
466 // If no offers have been attempted yet then it's okay to move to
467 // a different quality.
468 if (!offerAttempted)
469 ofrQ = std::nullopt;
470
471 // Return true so the current offer will be deleted.
472 return true;
473 }
474 return false;
475 }
476
477 // Offer crossing can prune the offers it needs to look at with a
478 // quality threshold.
479 [[nodiscard]] bool
480 checkQualityThreshold(Quality const& quality) const
481 {
482 return !defaultPath_ || quality >= qualityThreshold_;
483 }
484
485 // Return quality threshold or nullopt to use when generating AMM offer.
486 // AMM synthetic offer is generated to match LOB offer quality.
487 // If LOB tip offer quality is less than qualityThreshold
488 // then generated AMM offer quality is also less than qualityThreshold and
489 // the offer is not crossed even though AMM might generate a better quality
490 // offer. To address this, if qualityThreshold is greater than lobQuality
491 // then don't use quality to generate the AMM offer. The limit out value
492 // generates the maximum AMM offer in this case, which matches
493 // the quality threshold. This only applies to single path scenario.
494 // Multi-path AMM offers work the same as LOB offers.
495 [[nodiscard]] std::optional<Quality>
496 qualityThreshold(Quality const& lobQuality) const
497 {
498 if (this->ammLiquidity_ && !this->ammLiquidity_->multiPath() &&
499 qualityThreshold_ > lobQuality)
500 return std::nullopt;
501 return lobQuality;
502 }
503
504 // For offer crossing don't pay the transfer fee if alice is paying alice.
505 // A regular (non-offer-crossing) payment does not apply this rule.
507 getOfrInRate(Step const* prevStep, AccountID const& owner, std::uint32_t trIn) const
508 {
509 auto const srcAcct = (prevStep != nullptr) ? prevStep->directStepSrcAcct() : std::nullopt;
510
511 return owner == srcAcct // If offer crossing && prevStep is DirectI
512 ? QUALITY_ONE // or MPTEndpoint && src is offer owner
513 : trIn; // then rate = QUALITY_ONE
514 }
515
516 // See comment on getOfrInRate().
519 Step const* prevStep,
520 AccountID const& owner,
521 AccountID const& strandDst,
522 std::uint32_t trOut) const
523 {
524 return // If offer crossing
525 (prevStep != nullptr) && prevStep->bookStepBook() && // && prevStep is BookStep
526 owner == strandDst // && dest is offer owner
527 ? QUALITY_ONE
528 : trOut; // then rate = QUALITY_ONE
529 }
530
531 [[nodiscard]] Quality
533 ReadView const& v,
534 Quality const& ofrQ,
535 DebtDirection prevStepDir,
536 WaiveTransferFee waiveFee,
537 OfferType offerType) const
538 {
539 // Offer x-ing does not charge a transfer fee when the offer's owner
540 // is the same as the strand dst. It is important that
541 // `qualityUpperBound` is an upper bound on the quality (it is used to
542 // ignore strands whose quality cannot meet a minimum threshold). When
543 // calculating quality assume no fee is charged, or the estimate will no
544 // longer be an upper bound.
545
546 // Single path AMM offer has to factor in the transfer in rate
547 // when calculating the upper bound quality and the quality function
548 // because single path AMM's offer quality is not constant.
549 if (offerType == OfferType::Clob ||
550 (this->ammLiquidity_ && this->ammLiquidity_->multiPath()))
551 {
552 return ofrQ;
553 }
554
555 auto const trIn =
556 redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : kParityRate;
557 // AMM doesn't pay the transfer fee on the out amount
558 auto const trOut = kParityRate;
559
560 Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))};
561 return composedQuality(q1, ofrQ);
562 }
563
564 [[nodiscard]] std::string
565 logString() const override
566 {
567 return this->logStringImpl("BookOfferCrossingStep");
568 }
569
570private:
571 bool const defaultPath_;
573};
574
575//------------------------------------------------------------------------------
576
577template <class TIn, class TOut, class TDerived>
578bool
580{
581 if (auto bs = dynamic_cast<BookStep<TIn, TOut, TDerived> const*>(&rhs))
582 return book_ == bs->book_;
583 return false;
584}
585
586template <class TIn, class TOut, class TDerived>
589{
590 auto const dir = this->debtDirection(v, StrandDirection::Forward);
591
593 if (!res)
594 return {std::nullopt, dir};
595
596 auto const waiveFee = (std::get<OfferType>(*res) == OfferType::Amm) ? WaiveTransferFee::Yes
598
599 Quality const q = static_cast<TDerived const*>(this)->adjustQualityWithFees(
600 v, std::get<Quality>(*res), prevStepDir, waiveFee, std::get<OfferType>(*res));
601 return {q, dir};
602}
603
604template <class TIn, class TOut, class TDerived>
607{
608 auto const dir = this->debtDirection(v, StrandDirection::Forward);
609
611 if (!res)
612 return {std::nullopt, dir};
613
614 // AMM
615 if (!res->isConst())
616 {
617 auto static const kQOne = Quality{STAmount::kURateOne};
618 auto const q = static_cast<TDerived const*>(this)->adjustQualityWithFees(
619 v, kQOne, prevStepDir, WaiveTransferFee::Yes, OfferType::Amm);
620 if (q == kQOne)
621 return {res, dir};
623 qf.combine(*res);
624 return {qf, dir};
625 }
626
627 // CLOB
628 Quality const q = static_cast<TDerived const*>(this)->adjustQualityWithFees(
629 v,
630 *res->quality(), // NOLINT(bugprone-unchecked-optional-access) CLOB QualityFunction
631 // always has quality set
632 prevStepDir,
636}
637
638template <class TIn, class TOut, class TDerived>
644
645// Limit the offer to the given input (net of the taker's transfer fee), and
646// the step output and owner's charge with it. The caller sets stpAmt.in.
647template <class TIn, class TOut, class Offer>
648static void
650 Offer const& offer,
651 TAmounts<TIn, TOut>& ofrAmt,
652 TAmounts<TIn, TOut>& stpAmt,
653 TOut& ownerGives,
654 std::uint32_t transferRateOut,
655 TIn const& inLmt)
656{
657 // It turns out we can prevent order book blocking by (strictly)
658 // rounding down the ceil_in() result. By rounding down we guarantee
659 // that the quality of an offer left in the ledger is as good or
660 // better than the quality of the containing order book page.
661 //
662 // This adjustment changes transaction outcomes, so it must be made
663 // under an amendment.
664 ofrAmt = offer.limitIn(ofrAmt, inLmt, /* roundUp */ false);
665 stpAmt.out = ofrAmt.out;
666 // Round up for MPT output so the offer owner pays the full
667 // ceil(amount × rate) fee, matching direct Payment semantics. IOU uses
668 // floating-point arithmetic so the floor/ceil distinction is sub-epsilon
669 // there; preserve the historical false to avoid changing IOU behavior.
670 ownerGives = mulRatio(
671 ofrAmt.out,
672 transferRateOut,
673 QUALITY_ONE,
675}
676
677// Adjust the offer amount and step amount subject to the given input limit
678template <class TIn, class TOut, class Offer>
679static void
681 Offer const& offer,
682 TAmounts<TIn, TOut>& ofrAmt,
683 TAmounts<TIn, TOut>& stpAmt,
684 TOut& ownerGives,
685 std::uint32_t transferRateIn,
686 std::uint32_t transferRateOut,
687 TIn const& limit)
688{
689 if (limit < stpAmt.in)
690 {
691 stpAmt.in = limit;
692 auto const inLmt = mulRatio(stpAmt.in, QUALITY_ONE, transferRateIn, /*roundUp*/ false);
693 limitOfferIn(offer, ofrAmt, stpAmt, ownerGives, transferRateOut, inLmt);
694 }
695}
696
697// Adjust the offer amount and step amount subject to the given output limit
698template <class TIn, class TOut, class Offer>
699static void
701 Offer const& offer,
702 TAmounts<TIn, TOut>& ofrAmt,
703 TAmounts<TIn, TOut>& stpAmt,
704 TOut& ownerGives,
705 std::uint32_t transferRateIn,
706 std::uint32_t transferRateOut,
707 TOut const& limit)
708{
709 if (limit < stpAmt.out)
710 {
711 stpAmt.out = limit;
712 ownerGives = mulRatio(
713 stpAmt.out,
714 transferRateOut,
715 QUALITY_ONE,
717 ofrAmt = offer.limitOut(
718 ofrAmt,
719 stpAmt.out,
720 /*roundUp*/ true);
721 stpAmt.in = mulRatio(ofrAmt.in, transferRateIn, QUALITY_ONE, /*roundUp*/ true);
722 }
723}
724
725template <class TIn, class TOut, class TDerived>
726template <class Callback>
729 PaymentSandbox& sb,
730 ApplyView& afView,
731 DebtDirection prevStepDir,
732 Callback& callback) const
733{
734 // Charge the offer owner, not the sender
735 // Charge a fee even if the owner is the same as the issuer
736 // (the old code does not charge a fee)
737 // Calculate amount that goes to the taker and the amount charged the offer
738 // owner
739 std::uint32_t const trIn =
740 redeems(prevStepDir) ? rate(sb, book_.in, this->strandDst_).value : QUALITY_ONE;
741 // Always charge the transfer fee, even if the owner is the issuer
742 std::uint32_t const trOut =
743 ownerPaysTransferFee_ ? rate(sb, book_.out, this->strandDst_).value : QUALITY_ONE;
744
746
747 FlowOfferStream<TIn, TOut> offers(sb, afView, book_, sb.parentCloseTime(), counter, j_);
748
749 bool offerAttempted = false;
751 auto execOffer = [&](auto& offer) {
752 // Note that offer.quality() returns a (non-optional) Quality. So
753 // ofrQ is always safe to use below this point in the lambda.
754 if (!ofrQ)
755 {
756 ofrQ = offer.quality();
757 }
758 else if (*ofrQ != offer.quality())
759 {
760 return false;
761 }
762
763 if (static_cast<TDerived const*>(this)->limitSelfCrossQuality(
764 strandSrc_, strandDst_, offer, ofrQ, offers, offerAttempted))
765 return true;
766
767 Asset const& assetIn = offer.assetIn();
768 bool const isAssetInMPT = assetIn.holds<MPTIssue>();
769 auto const& owner = offer.owner();
770
771 auto const removeOffer = [&](std::string_view logMessage = {}) {
772 auto const key = offer.key();
773 if (!logMessage.empty())
774 {
775 JLOG(j_.trace()) << logMessage << (key ? " " + to_string(*key) : "");
776 }
777 if (key)
778 offers.permRmOffer(*key);
779 if (!offerAttempted)
780 {
781 // Change quality only if no previous offers were tried.
782 ofrQ = std::nullopt;
783 }
784 };
785
786 // It shouldn't matter from auth point of view whether it's sb
787 // or afView. Amendment guard this change just in case.
788 auto const& applyView = sb.rules().enabled(featureMPTokensV2) ? sb : afView;
789 // Make sure offer owner has authorization to own Assets from issuer
790 // and MPT assets can be traded/transferred.
791 // An account can always own XRP or their own Assets.
792 // Missing MPTokens are allowed during offer discovery; they are
793 // created later if the offer is actually consumed.
794 auto const authType = isAssetInMPT ? AuthType::WeakAuth : AuthType::Legacy;
795 if (!isTesSuccess(requireAuth(applyView, assetIn, owner, authType)) ||
796 !checkMPTDEX(sb, owner))
797 {
798 // Offer owner not authorized to hold IOU/MPT from issuer.
799 // Remove this offer even if no crossing occurs.
800 removeOffer();
801 // Returning true causes offers.step() to delete the offer.
802 return true;
803 }
804
805 if (!static_cast<TDerived const*>(this)->checkQualityThreshold(offer.quality()))
806 return false;
807
808 auto const [ofrInRate, ofrOutRate] = offer.adjustRates(
809 static_cast<TDerived const*>(this)->getOfrInRate(prevStep_, owner, trIn),
810 static_cast<TDerived const*>(this)->getOfrOutRate(prevStep_, owner, strandDst_, trOut));
811
812 auto ofrAmt = offer.amount();
813 TAmounts stpAmt{ofrAmt.in, ofrAmt.out};
814 auto ownerGives = ofrAmt.out;
815 // A bid above MaximumAmount is limited to it below (see maxIn_). Gross
816 // up no more than the cap: the whole bid may not fit once grossed up
817 // even though a fill at the cap does.
818 bool const capInMPT = prevStep_ && maxIn_ && offer.owner() != assetIn.getIssuer();
819 auto const amtIn = [&](TIn const& in) { return capInMPT && *maxIn_ < in ? *maxIn_ : in; };
820 try
821 {
822 // A crafted MPTokensV2 offer can overflow while transfer rates or
823 // crossing limits are applied, here or in the callback's
824 // limitStepIn()/limitStepOut(); remove that unusable offer instead
825 // of letting it persist as a tecINTERNAL source. Overflows while
826 // consuming the offer are handled by tryConsumeOffer().
827 stpAmt.in = mulRatio(amtIn(ofrAmt.in), ofrInRate, QUALITY_ONE, /*roundUp*/ true);
828
829 // owner pays the transfer fee. An MPT gross-up that doesn't fit in
830 // an MPT amount exceeds any owner's funds (an MPT issuer's funds
831 // are what it can still issue), so a large, partially funded offer
832 // is limited to its funds below instead of removed as an overflow.
833 std::optional<TOut> grossOut;
835 {
836 grossOut = tryMulRatio(ofrAmt.out, ofrOutRate, QUALITY_ONE, /*roundUp*/ true);
837 }
838 else
839 {
840 grossOut = mulRatio(ofrAmt.out, ofrOutRate, QUALITY_ONE, /*roundUp*/ false);
841 }
842 if (grossOut)
843 ownerGives = *grossOut;
844
845 auto const funds = offer.isFunded()
846 ? ownerGives // Offer owner is IOU issuer; they have unlimited funds
847 : offers.ownerFunds();
848
849 // Only a CLOB offer: an AMM offer is funded and its output rate is
850 // parity, so its gross-up always fits.
851 if (!grossOut || funds < ownerGives)
852 {
853 // The owner isn't an IOU issuer (those are funded). An MPT
854 // issuer can be here: its funds are what it can still issue.
855 ownerGives = funds;
856 stpAmt.out = mulRatio(ownerGives, QUALITY_ONE, ofrOutRate, /*roundUp*/ false);
857
858 // It turns out we can prevent order book blocking by (strictly)
859 // rounding down the ceil_out() result. This adjustment changes
860 // transaction outcomes, so it must be made under an amendment.
861 ofrAmt = offer.limitOut(ofrAmt, stpAmt.out, /*roundUp*/ false);
862
863 stpAmt.in = mulRatio(amtIn(ofrAmt.in), ofrInRate, QUALITY_ONE, /*roundUp*/ true);
864
865 // Fee clip can floor in or out to 0. OfferStream is
866 // fee-blind, so it misses both: out==0 blocks the book;
867 // in==0 / out>0 consumes ownerGives for free. MPT at
868 // ordinary sizes; IOU only at the smallest out — V2
869 // because that IOU outcome changes.
870 if (sb.rules().enabled(featureMPTokensV2) &&
871 (stpAmt.out <= beast::kZero || ofrAmt.in <= beast::kZero))
872 {
873 removeOffer(
874 "Removing offer whose fee-clipped amount rounds to "
875 "zero");
876 return true;
877 }
878
879 // out = floor(funds / rate), so out × rate <= funds and
880 // ceil(out × rate) <= funds since funds is an integer. Charge
881 // that instead of funds; charging all of funds would burn the
882 // fraction that can't be delivered. IOU keeps funds; the
883 // difference is sub-epsilon there.
885 {
886 ownerGives = mulRatio(stpAmt.out, ofrOutRate, QUALITY_ONE, /*roundUp*/ true);
887 }
888 }
889
890 // Limit offer's input if MPT and the offer is not owned by the
891 // issuer (an issuer's send to itself is a no-op).
892 bool inLimited = false;
893 std::optional<TIn> limitIn;
894 auto const& issuer = assetIn.getIssuer();
895 if (isAssetInMPT && offer.owner() != issuer)
896 {
897 if (!prevStep_)
898 {
899 // BookStep is the first step (an issuer is making a
900 // cross-currency payment). Limit to the funds available to
901 // issue, otherwise OutstandingAmount may overflow. This
902 // limits the taker, not the offer: its remainder is still
903 // funded by the owner, so the callback keeps it. With
904 // nothing left to issue there is nothing to consume, so
905 // stop before touching the offer.
906 auto const available = toAmount<TIn>(accountFunds(
907 sb,
908 issuer,
909 assetIn, // STAmount{0}, but the default is not used
912 j_));
913 if (available <= beast::kZero)
914 return false;
915 if (stpAmt.in > available)
916 {
917 inLimited = true;
918 limitIn = available;
919 }
920 }
921 else if (maxIn_ && ofrAmt.in > *maxIn_)
922 {
923 // Limit to MaximumAmount (see maxIn_). The remainder is
924 // still funded, so the callback keeps the offer instead of
925 // consuming it. stpAmt.in is already the grossed-up cap.
926 inLimited = true;
927 limitOfferIn(offer, ofrAmt, stpAmt, ownerGives, ofrOutRate, *maxIn_);
928 }
929 }
930 if (limitIn)
931 limitStepIn(offer, ofrAmt, stpAmt, ownerGives, ofrInRate, ofrOutRate, *limitIn);
932
933 // amtIn() grossed up no more than the cap, so the offer must have
934 // been limited to it above or the taker pays for less than is
935 // consumed.
936 XRPL_ASSERT(
937 !capInMPT || ofrAmt.in <= *maxIn_,
938 "xrpl::BookStep::forEachOffer : capped offer input is limited");
939
940 offerAttempted = true;
941 return callback(offer, ofrAmt, stpAmt, ownerGives, ofrInRate, ofrOutRate, inLimited);
942 }
943 catch (std::overflow_error const&)
944 {
945 if (sb.rules().enabled(featureMPTokensV2))
946 {
947 SOMETIMES(
948 true,
949 "BookStep::forEachOffer removed MPT offer after "
950 "overflow during crossing");
951 removeOffer("Removing offer with overflowing amount calculation");
952 return true;
953 }
954 // Legacy behavior: the exception escapes flow() and the
955 // transaction fails with tecINTERNAL.
956 throw;
957 }
958 };
959
960 // At any payment engine iteration, AMM offer can only be consumed once.
961 auto const tryAMM = [&](std::optional<Quality> const& lobQuality) -> bool {
962 // amm doesn't support domain yet
963 if (book_.domain)
964 return true;
965
966 // If offer crossing then use either LOB quality or nullopt
967 // to prevent AMM being blocked by a lower quality LOB.
968 auto const qualityThreshold = [&] -> std::optional<Quality> {
969 if (lobQuality)
970 return static_cast<TDerived const*>(this)->qualityThreshold(*lobQuality);
971 return lobQuality;
972 }();
973 auto ammOffer = getAMMOffer(sb, qualityThreshold);
974 return !ammOffer || execOffer(*ammOffer);
975 };
976
977 if (offers.step())
978 {
979 if (tryAMM(offers.tip().quality()))
980 {
981 do
982 {
983 if (!execOffer(offers.tip()))
984 break;
985 } while (offers.step());
986 }
987 }
988 else
989 {
990 // Might have AMM offer if there are no LOB offers.
991 tryAMM(std::nullopt);
992 }
993
994 return {offers.permToRemove(), counter.count()};
995}
996
997template <class TIn, class TOut, class TDerived>
998template <template <typename, typename> typename Offer>
999void
1001 PaymentSandbox& sb,
1002 Offer<TIn, TOut>& offer,
1003 TAmounts<TIn, TOut> const& ofrAmt,
1004 TAmounts<TIn, TOut> const& stepAmt,
1005 TOut const& ownerGives) const
1006{
1007 try
1008 {
1009 // Under MPTokensV2, an overflow while consuming the offer fails the
1010 // strand instead of being handled by forEachOffer().
1011 consumeOffer(sb, offer, ofrAmt, stepAmt, ownerGives);
1012 }
1013 catch (std::overflow_error const&)
1014 {
1015 if (sb.rules().enabled(featureMPTokensV2))
1016 {
1017 Throw<FlowException>(tecINTERNAL, "Overflow while consuming offer");
1018 }
1019 throw;
1020 }
1021}
1022
1023template <class TIn, class TOut, class TDerived>
1024template <template <typename, typename> typename Offer>
1025void
1027 PaymentSandbox& sb,
1028 Offer<TIn, TOut>& offer,
1029 TAmounts<TIn, TOut> const& ofrAmt,
1030 TAmounts<TIn, TOut> const& stepAmt,
1031 TOut const& ownerGives) const
1032{
1033 if (!offer.checkInvariant(ofrAmt, j_))
1034 {
1035 // LCOV_EXCL_START
1036 Throw<FlowException>(tecINVARIANT_FAILED, "AMM pool product invariant failed.");
1037 // LCOV_EXCL_STOP
1038 }
1039
1040 // The offer owner gets the ofrAmt. The difference between ofrAmt and
1041 // stepAmt is a transfer fee that goes to book_.in.account
1042 {
1043 if constexpr (std::is_same_v<TIn, MPTAmount>)
1044 {
1045 // If the offer's TakerPays asset is an MPT, the offer owner must
1046 // hold an MPToken to receive it. Create one here if it doesn't
1047 // already exist.
1048 if (auto const err = checkCreateMPT(sb, book_.in.get<MPTIssue>(), offer.owner(), j_);
1049 !isTesSuccess(err))
1050 {
1051 // checkCreateMPT only fails on tecDIR_FULL (its source line is
1052 // itself LCOV-excluded) or a missing offer-owner account, which
1053 // cannot happen since that account owns the offer being
1054 // consumed. Defensive and unreachable in practice.
1055 Throw<FlowException>(err); // LCOV_EXCL_LINE
1056 }
1057 }
1058
1059 auto const dr = offer.send(
1060 sb, book_.in.getIssuer(), offer.owner(), toSTAmount(ofrAmt.in, book_.in), j_);
1061 if (!isTesSuccess(dr))
1063 }
1064
1065 // The offer owner pays `ownerGives`. The difference between ownerGives and
1066 // stepAmt is a transfer fee that goes to book_.out.account
1067 {
1068 auto const& issuer = book_.out.getIssuer();
1069 auto const cr =
1070 offer.send(sb, offer.owner(), issuer, toSTAmount(ownerGives, book_.out), j_);
1071 if (!isTesSuccess(cr))
1073 if constexpr (std::is_same_v<TOut, MPTAmount>)
1074 {
1075 if (offer.owner() == issuer)
1076 issuerSelfDebitHookMPT(sb, book_.out.get<MPTIssue>(), ofrAmt.out.value());
1077 }
1078 }
1079
1080 offer.consume(sb, ofrAmt);
1081}
1082
1083template <class TIn, class TOut, class TDerived>
1086 ReadView const& view,
1087 std::optional<Quality> const& clobQuality) const
1088{
1089 // AMM doesn't support domain books. When fixCleanup3_3_0 is enabled, exclude
1090 // AMM liquidity so quality estimation matches actual crossing (tryAMM skips
1091 // AMM for domain books).
1092 if (book_.domain && view.rules().enabled(fixCleanup3_3_0))
1093 return std::nullopt;
1094 if (ammLiquidity_)
1095 return ammLiquidity_->getOffer(view, clobQuality);
1096 return std::nullopt;
1097}
1098
1099template <class TIn, class TOut, class TDerived>
1102{
1103 // This can be simplified (and sped up) if directories are never empty.
1104 Sandbox sb(&view, TapNone);
1105 BookTip bt(sb, book_);
1106 auto const lobQuality = bt.step(j_) ? std::optional<Quality>(bt.quality()) : std::nullopt;
1107 // Multi-path offer generates an offer with the quality
1108 // calculated from the offer size and the quality is constant in this case.
1109 // Single path offer quality changes with the offer size. Spot price quality
1110 // (SPQ) can't be used in this case as the upper bound quality because
1111 // even if SPQ quality is better than LOB quality, it might not be possible
1112 // to generate AMM offer at or better quality than LOB quality. Another
1113 // factor to consider is limit quality on offer crossing. If LOB quality
1114 // is greater than limit quality then use LOB quality when generating AMM
1115 // offer, otherwise don't use quality threshold when generating AMM offer.
1116 // AMM or LOB offer, whether multi-path or single path then can be selected
1117 // based on the best offer quality. Using the quality to generate AMM offer
1118 // in this case also prevents the payment engine from going into multiple
1119 // iterations to cross a LOB offer. This happens when AMM changes
1120 // the out amount at the start of iteration to match the limitQuality
1121 // on offer crossing but AMM can't generate the offer at this quality,
1122 // as the result a LOB offer is partially crossed, and it might take a few
1123 // iterations to fully cross the offer.
1124 auto const qualityThreshold = [&] -> std::optional<Quality> {
1125 if (lobQuality)
1126 return static_cast<TDerived const*>(this)->qualityThreshold(*lobQuality);
1127 return std::nullopt;
1128 }();
1129 // AMM quality is better or no LOB offer
1130 if (auto const ammOffer = getAMMOffer(view, qualityThreshold);
1131 ammOffer && ((lobQuality && ammOffer->quality() > lobQuality) || !lobQuality))
1132 return ammOffer;
1133 // LOB quality is better or nullopt
1134 return lobQuality;
1135}
1136
1137template <class TIn, class TOut, class TDerived>
1138auto
1141{
1142 auto const res = tip(view);
1143 if (!res)
1144 {
1145 return std::nullopt;
1146 }
1147 if (auto const q = std::get_if<Quality>(&(*res)))
1148 {
1149 return std::make_pair(*q, OfferType::Clob);
1150 }
1151
1152 return std::make_pair(std::get<AMMOffer<TIn, TOut>>(*res).quality(), OfferType::Amm);
1153}
1154
1155template <class TIn, class TOut, class TDerived>
1158{
1159 auto const res = tip(view);
1160 if (!res)
1161 {
1162 return std::nullopt;
1163 }
1164 if (auto const q = std::get_if<Quality>(&(*res)))
1165 {
1167 }
1168
1169 return std::get<AMMOffer<TIn, TOut>>(*res).getQualityFunc();
1170}
1171
1172template <class TCollection>
1173static auto
1174sum(TCollection const& col)
1175{
1176 using TResult = std::decay_t<decltype(*col.begin())>;
1177 if (col.empty())
1178 return TResult{beast::kZero};
1179 return std::accumulate(
1180 col.begin() + 1, col.end(), *col.begin(), [](TResult const& a, TResult const& b) {
1181 return checkedStepAdd(a, b);
1182 });
1183};
1184
1185template <class TIn, class TOut, class TDerived>
1188 PaymentSandbox& sb,
1189 ApplyView& afView,
1190 boost::container::flat_set<UInt256>& ofrsToRm,
1191 TOut const& out)
1192{
1193 cache_.reset();
1194
1196
1197 auto remainingOut = out;
1198
1199 boost::container::flat_multiset<TIn> savedIns;
1200 savedIns.reserve(64);
1201 boost::container::flat_multiset<TOut> savedOuts;
1202 savedOuts.reserve(64);
1203
1204 /* amt fed will be adjusted by owner funds (and may differ from the offer's
1205 amounts - tho always <=)
1206 Return true to continue to receive offers, false to stop receiving offers.
1207 */
1208 auto eachOffer = [&](auto& offer,
1209 TAmounts<TIn, TOut> const& ofrAmt,
1210 TAmounts<TIn, TOut> const& stpAmt,
1211 TOut const& ownerGives,
1212 std::uint32_t transferRateIn,
1213 std::uint32_t transferRateOut,
1214 bool inLimited) mutable -> bool {
1215 if (remainingOut <= beast::kZero)
1216 return false;
1217
1218 if (stpAmt.out <= remainingOut)
1219 {
1220 savedIns.insert(stpAmt.in);
1221 savedOuts.insert(stpAmt.out);
1222 result = TAmounts<TIn, TOut>(sum(savedIns), sum(savedOuts));
1223 remainingOut = out - result.out;
1224 this->tryConsumeOffer(sb, offer, ofrAmt, stpAmt, ownerGives);
1225 // return true b/c even if the payment is satisfied,
1226 // we need to consume the offer. An offer limited by what the
1227 // issuer can issue is not consumed, though: its remainder is still
1228 // funded, and no more of that MPT can flow through this step
1229 // anyway.
1230 return !inLimited;
1231 }
1232
1233 auto ofrAdjAmt = ofrAmt;
1234 auto stpAdjAmt = stpAmt;
1235 auto ownerGivesAdj = ownerGives;
1236 // This reduction can overflow via the transfer-rate mulRatio() on a
1237 // 63-bit MPT amount (IOU rescales instead of throwing, and XRP stays
1238 // under the int64 limit, so only MPT reaches it today), but
1239 // savedIns/savedOuts are not updated until after it succeeds. The outer
1240 // execOffer() catch can therefore remove the offer under
1241 // featureMPTokensV2 (legacy propagate-the-exception behavior otherwise)
1242 // without rolling back local state.
1244 offer,
1245 ofrAdjAmt,
1246 stpAdjAmt,
1247 ownerGivesAdj,
1248 transferRateIn,
1249 transferRateOut,
1250 remainingOut);
1251 remainingOut = beast::kZero;
1252 savedIns.insert(stpAdjAmt.in);
1253 savedOuts.insert(remainingOut);
1254 result.in = sum(savedIns);
1255 result.out = out;
1256 this->tryConsumeOffer(sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj);
1257
1258 // Explicitly check whether the offer is funded. Given that we have
1259 // (stpAmt.out > remainingOut), it's natural to assume the offer
1260 // will still be funded after consuming remainingOut but that is
1261 // not always the case. If the mantissas of two IOU amounts differ
1262 // by less than ten, then subtracting them leaves a zero.
1263 return offer.fullyConsumed();
1264 };
1265
1266 {
1267 auto const prevStepDebtDir = [&] {
1268 if (prevStep_)
1269 return prevStep_->debtDirection(sb, StrandDirection::Reverse);
1270 return DebtDirection::Issues;
1271 }();
1272 auto const r = forEachOffer(sb, afView, prevStepDebtDir, eachOffer);
1273 boost::container::flat_set<UInt256> const toRm = std::move(std::get<0>(r));
1274 std::uint32_t const offersConsumed = std::get<1>(r);
1275 offersUsed_ = offersConsumed;
1276 setUnion(ofrsToRm, toRm);
1277
1278 // Too many iterations, mark this strand as inactive
1279 if (offersConsumed >= kMaxOffersToConsume)
1280 {
1281 inactive_ = true;
1282 }
1283 }
1284
1285 switch (remainingOut.signum())
1286 {
1287 case -1: {
1288 // something went very wrong
1289 // LCOV_EXCL_START
1290 JLOG(j_.error()) << "BookStep remainingOut < 0 " << to_string(remainingOut);
1291 UNREACHABLE("xrpl::BookStep::revImp : remaining less than zero");
1293 return {beast::kZero, beast::kZero};
1294 // LCOV_EXCL_STOP
1295 }
1296 case 0: {
1297 // due to normalization, remainingOut can be zero without
1298 // result.out == out. Force result.out == out for this case
1299 result.out = out;
1300 }
1301 }
1302
1303 cache_.emplace(result.in, result.out);
1304 return {result.in, result.out};
1305}
1306
1307template <class TIn, class TOut, class TDerived>
1310 PaymentSandbox& sb,
1311 ApplyView& afView,
1312 boost::container::flat_set<UInt256>& ofrsToRm,
1313 TIn const& in)
1314{
1315 XRPL_ASSERT(cache_, "xrpl::BookStep::fwdImp : cache is set");
1316
1318
1319 auto remainingIn = in;
1320
1321 boost::container::flat_multiset<TIn> savedIns;
1322 savedIns.reserve(64);
1323 boost::container::flat_multiset<TOut> savedOuts;
1324 savedOuts.reserve(64);
1325
1326 // amt fed will be adjusted by owner funds (and may differ from the offer's
1327 // amounts - tho always <=)
1328 auto eachOffer = [&](auto& offer,
1329 TAmounts<TIn, TOut> const& ofrAmt,
1330 TAmounts<TIn, TOut> const& stpAmt,
1331 TOut const& ownerGives,
1332 std::uint32_t transferRateIn,
1333 std::uint32_t transferRateOut,
1334 bool inLimited) mutable -> bool {
1335 XRPL_ASSERT(cache_, "xrpl::BookStep::fwdImp::eachOffer : cache is set");
1336
1337 if (remainingIn <= beast::kZero)
1338 return false;
1339
1340 bool processMore = true;
1341 auto ofrAdjAmt = ofrAmt;
1342 auto stpAdjAmt = stpAmt;
1343 auto ownerGivesAdj = ownerGives;
1344
1345 // limitStepIn()/limitStepOut() can throw std::overflow_error from the
1346 // transfer-rate mulRatio() on a 63-bit MPT amount. (IOUAmount::mulRatio
1347 // rescales rather than throwing, and XRP amounts/rates stay under the
1348 // int64 limit, so in practice only MPT reaches this today.) execOffer()
1349 // catches it: under featureMPTokensV2 the offending offer is removed;
1350 // otherwise the legacy behavior (propagate the exception) is preserved.
1351 // Keep candidate accumulator changes local until those calls succeed so
1352 // the catch path does not observe partially updated state. Re-sum the
1353 // staged sets to preserve historical flat_multiset summing behavior.
1354 auto savedInsAdj = savedIns;
1355 auto savedOutsAdj = savedOuts;
1356 auto resultAdj = result;
1357 typename boost::container::flat_multiset<TOut>::const_iterator lastOut;
1358
1359 if (stpAmt.in <= remainingIn)
1360 {
1361 savedInsAdj.insert(stpAmt.in);
1362 lastOut = savedOutsAdj.insert(stpAmt.out);
1363 resultAdj = TAmounts<TIn, TOut>(sum(savedInsAdj), sum(savedOutsAdj));
1364 // consume the offer even if stepAmt.in == remainingIn, unless it
1365 // was limited by what the issuer can issue: its remainder is
1366 // still funded and must stay on the book.
1367 processMore = !inLimited;
1368 }
1369 else
1370 {
1372 offer,
1373 ofrAdjAmt,
1374 stpAdjAmt,
1375 ownerGivesAdj,
1376 transferRateIn,
1377 transferRateOut,
1378 remainingIn);
1379 savedInsAdj.insert(remainingIn);
1380 lastOut = savedOutsAdj.insert(stpAdjAmt.out);
1381 resultAdj.out = sum(savedOutsAdj);
1382 resultAdj.in = in;
1383
1384 processMore = false;
1385 }
1386
1387 if (resultAdj.out > cache_->out && resultAdj.in <= cache_->in)
1388 {
1389 // The step produced more output in the forward pass than the
1390 // reverse pass while consuming the same input (or less). If we
1391 // compute the input required to produce the cached output
1392 // (produced in the reverse step) and the input is equal to
1393 // the input consumed in the forward step, then consume the
1394 // input provided in the forward step and produce the output
1395 // requested from the reverse step.
1396 auto const lastOutAmt = *lastOut;
1397 savedOutsAdj.erase(lastOut);
1398 auto const remainingOut = cache_->out - sum(savedOutsAdj);
1399 auto ofrAdjAmtRev = ofrAmt;
1400 auto stpAdjAmtRev = stpAmt;
1401 auto ownerGivesAdjRev = ownerGives;
1403 offer,
1404 ofrAdjAmtRev,
1405 stpAdjAmtRev,
1406 ownerGivesAdjRev,
1407 transferRateIn,
1408 transferRateOut,
1409 remainingOut);
1410
1411 if (stpAdjAmtRev.in == remainingIn)
1412 {
1413 resultAdj.in = in;
1414 resultAdj.out = cache_->out;
1415
1416 savedInsAdj.clear();
1417 savedInsAdj.insert(resultAdj.in);
1418 savedOutsAdj.clear();
1419 savedOutsAdj.insert(resultAdj.out);
1420
1421 ofrAdjAmt = ofrAdjAmtRev;
1422 stpAdjAmt.in = remainingIn;
1423 stpAdjAmt.out = remainingOut;
1424 ownerGivesAdj = ownerGivesAdjRev;
1425 }
1426 else
1427 {
1428 // This is (likely) a problem case, and will be caught
1429 // with later checks
1430 savedOutsAdj.insert(lastOutAmt);
1431 }
1432 }
1433
1434 // Commit the staged accounting only after limitStepIn()/limitStepOut()
1435 // have succeeded.
1436 savedIns = std::move(savedInsAdj);
1437 savedOuts = std::move(savedOutsAdj);
1438 result = resultAdj;
1439 remainingIn = in - result.in;
1440 this->tryConsumeOffer(sb, offer, ofrAdjAmt, stpAdjAmt, ownerGivesAdj);
1441
1442 // When the mantissas of two iou amounts differ by less than ten, then
1443 // subtracting them leaves a result of zero. This can cause the check
1444 // for (stpAmt.in > remainingIn) to incorrectly think an offer will be
1445 // funded after subtracting remainingIn.
1446 return processMore || offer.fullyConsumed();
1447 };
1448
1449 {
1450 auto const prevStepDebtDir = [&] {
1451 if (prevStep_)
1452 return prevStep_->debtDirection(sb, StrandDirection::Forward);
1453 return DebtDirection::Issues;
1454 }();
1455 auto const r = forEachOffer(sb, afView, prevStepDebtDir, eachOffer);
1456 boost::container::flat_set<UInt256> const toRm = std::move(std::get<0>(r));
1457 std::uint32_t const offersConsumed = std::get<1>(r);
1458 offersUsed_ = offersConsumed;
1459 setUnion(ofrsToRm, toRm);
1460
1461 // Too many iterations, mark this strand as inactive (dry)
1462 if (offersConsumed >= kMaxOffersToConsume)
1463 {
1464 inactive_ = true;
1465 }
1466 }
1467
1468 switch (remainingIn.signum())
1469 {
1470 case -1: {
1471 // LCOV_EXCL_START
1472 // something went very wrong
1473 JLOG(j_.error()) << "BookStep remainingIn < 0 " << to_string(remainingIn);
1474 UNREACHABLE("xrpl::BookStep::fwdImp : remaining less than zero");
1476 return {beast::kZero, beast::kZero};
1477 // LCOV_EXCL_STOP
1478 }
1479 case 0: {
1480 // due to normalization, remainingIn can be zero without
1481 // result.in == in. Force result.in == in for this case
1482 result.in = in;
1483 }
1484 }
1485
1486 cache_.emplace(result.in, result.out);
1487 return {result.in, result.out};
1488}
1489
1490template <class TIn, class TOut, class TDerived>
1493 PaymentSandbox& sb,
1494 ApplyView& afView,
1495 EitherAmount const& in)
1496{
1497 if (!cache_)
1498 {
1499 JLOG(j_.trace()) << "Expected valid cache in validFwd";
1500 return {false, EitherAmount(TOut(beast::kZero))};
1501 }
1502
1503 auto const savCache = *cache_;
1504
1505 try
1506 {
1507 boost::container::flat_set<UInt256> dummy;
1508 fwdImp(sb, afView, dummy, get<TIn>(in)); // changes cache
1509 }
1510 catch (FlowException const&)
1511 {
1512 return {false, EitherAmount(TOut(beast::kZero))};
1513 }
1514
1515 // NOLINTBEGIN(bugprone-unchecked-optional-access) fwdImp sets cache_ on success
1516 if (!(checkNear(savCache.in, cache_->in) && checkNear(savCache.out, cache_->out)))
1517 {
1518 JLOG(j_.warn()) << "Strand re-execute check failed."
1519 << " ExpectedIn: " << to_string(savCache.in)
1520 << " CachedIn: " << to_string(cache_->in)
1521 << " ExpectedOut: " << to_string(savCache.out)
1522 << " CachedOut: " << to_string(cache_->out);
1523 return {false, EitherAmount(cache_->out)};
1524 }
1525 return {true, EitherAmount(cache_->out)};
1526 // NOLINTEND(bugprone-unchecked-optional-access)
1527}
1528
1529template <class TIn, class TOut, class TDerived>
1530TER
1532{
1533 if (book_.in == book_.out)
1534 {
1535 JLOG(j_.debug()) << "BookStep: Book with same in and out issuer " << *this;
1536 return temBAD_PATH;
1537 }
1538 if (!isConsistent(book_.in) || !isConsistent(book_.out))
1539 {
1540 JLOG(j_.debug()) << "Book: currency is inconsistent with issuer." << *this;
1541 return temBAD_PATH;
1542 }
1543
1544 // An issuer paying with its own MPT issues it into the first book. A
1545 // holder-sourced strand records the MPT in the first MPTEndpointStep and
1546 // so rejects a later book that outputs it again; do the same here. The
1547 // step after such a book issues the MPT a second time and the payment
1548 // engine cannot keep the two within MaximumAmount once StrandFlow
1549 // rebuilds the sandbox on a limiting step.
1550 if (ctx.isFirst && book_.in.holds<MPTIssue>() && book_.in.getIssuer() == ctx.strandSrc &&
1551 ctx.view.rules().enabled(featureMPTokensV2))
1552 {
1553 ctx.seenDirectAssets[0].insert(book_.in);
1554 }
1555
1556 // Do not allow two books to output the same issue. This may cause offers on
1557 // one step to unfund offers in another step.
1558 if (!ctx.seenBookOuts.insert(book_.out).second ||
1559 (ctx.seenDirectAssets[0].count(book_.out) != 0u))
1560 {
1561 JLOG(j_.debug()) << "BookStep: loop detected: " << *this;
1562 return temBAD_PATH_LOOP;
1563 }
1564
1565 if (ctx.seenDirectAssets[1].count(book_.out) != 0u)
1566 {
1567 JLOG(j_.debug()) << "BookStep: loop detected: " << *this;
1568 return temBAD_PATH_LOOP;
1569 }
1570
1571 auto const issuerExists = [](ReadView const& view, Asset const& iss) -> bool {
1572 return isXRP(iss.getIssuer()) || view.exists(keylet::account(iss.getIssuer()));
1573 };
1574
1575 if (!issuerExists(ctx.view, book_.in) || !issuerExists(ctx.view, book_.out))
1576 {
1577 JLOG(j_.debug()) << "BookStep: deleted issuer detected: " << *this;
1578 return tecNO_ISSUER;
1579 }
1580
1581 if (ctx.prevStep != nullptr)
1582 {
1583 if (auto const prev = ctx.prevStep->directStepSrcAcct())
1584 {
1585 auto const& view = ctx.view;
1586 auto const& cur = book_.in.getIssuer();
1587
1588 auto const err = book_.in.visit(
1589 [&](Issue const& issue) -> std::optional<TER> {
1590 auto const sle = view.read(keylet::trustLine(*prev, cur, issue.currency));
1591 if (!sle)
1592 return terNO_LINE;
1593 if (sle->isFlag((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple))
1594 return terNO_RIPPLE;
1595 return std::nullopt;
1596 },
1597 [&](MPTIssue const& issue) -> std::optional<TER> { return std::nullopt; });
1598 if (err)
1599 return *err;
1600 }
1601 }
1602
1603 // Check if the offer can be traded on DEX.
1604 if (auto const ter = canTrade(ctx.view, book_.in); !isTesSuccess(ter))
1605 return ter;
1606 if (auto const ter = canTrade(ctx.view, book_.out); !isTesSuccess(ter))
1607 return ter;
1608
1609 return tesSUCCESS;
1610}
1611
1612template <class TIn, class TOut, class TDerived>
1613Rate
1615 ReadView const& view,
1616 Asset const& asset,
1617 AccountID const& dstAccount) const
1618{
1619 return asset.visit(
1620 [&](Issue const& issue) -> Rate {
1621 if (isXRP(issue.account) || issue.account == dstAccount)
1622 return kParityRate;
1623 return transferRate(view, issue.account);
1624 },
1625 [&](MPTIssue const& mptIssue) -> Rate {
1626 // For MPT, parity applies only when this asset is the final strand
1627 // delivery AND the destination is the MPT issuer (holder → issuer,
1628 // which is fee-free). Using strandDst_ alone is wrong because it
1629 // incorrectly suppresses the fee when MPT is an intermediate or
1630 // the in-side of a book that precedes the issuer's XRP receipt.
1631 if (asset == strandDeliver_ && mptIssue.getIssuer() == dstAccount)
1632 return kParityRate;
1633 return transferRate(view, mptIssue.getMptID());
1634 });
1635};
1636
1637template <class TIn, class TOut, class TDerived>
1638bool
1640{
1641 // Offer-owner locks on book_.in and book_.out are handled by the
1642 // liquidity sources before an offer reaches this point. OfferStream
1643 // filters CLOB offers through the assetIn deep-freeze check and the
1644 // assetOut owner-funds check using FreezeHandling::ZeroIfFrozen, while
1645 // AMMLiquidity gets pool balances through ammAccountHolds(), which zeroes
1646 // locked holdings. This method only enforces MPT trade and transfer
1647 // permissions.
1648 if (!isTesSuccess(canTrade(view, book_.in)) || !isTesSuccess(canTrade(view, book_.out)))
1649 return false;
1650
1651 if (book_.in.holds<MPTIssue>())
1652 {
1653 auto const ret = [&] {
1654 auto const& asset = book_.in;
1655 // Strand's source is an issuer
1656 if (!prevStep_)
1657 return true;
1658 // Offer's owner is an issuer
1659 if (asset.getIssuer() == owner)
1660 return true;
1661 // Previous BookStep already enforced transferability for the asset
1662 // it sends to this offer.
1663 if (prevStep_->bookStepBook())
1664 return true;
1665 // Previous step is MPTEndpointStep and offer's owner is not an
1666 // issuer
1667 return isTesSuccess(canTransfer(view, asset, owner, owner));
1668 }();
1669 if (!ret)
1670 return false;
1671 }
1672
1673 if (book_.out.holds<MPTIssue>())
1674 {
1675 auto const& asset = book_.out;
1676 // Last step if the strand's destination is an issuer
1677 if (strandDeliver_ == asset && strandDst_ == asset.getIssuer())
1678 return true;
1679 // Offer's owner is an issuer
1680 if (asset.getIssuer() == owner)
1681 return true;
1682
1683 // Next step is BookStep and offer's owner is not an issuer.
1684 return isTesSuccess(canTransfer(view, asset, owner, owner));
1685 }
1686
1687 return true;
1688}
1689
1690//------------------------------------------------------------------------------
1691
1692namespace test {
1693// Needed for testing
1694
1695template <class TIn, class TOut, class TDerived>
1696static bool
1697equalHelper(Step const& step, xrpl::Book const& book)
1698{
1699 if (auto bs = dynamic_cast<BookStep<TIn, TOut, TDerived> const*>(&step))
1700 return book == bs->book();
1701 return false;
1702}
1703
1704bool
1705bookStepEqual(Step const& step, xrpl::Book const& book)
1706{
1707 return std::visit(
1708 [&]<typename TIn, typename TOut>(TIn const&, TOut const&) {
1709 using TInAmount = TIn::Amount;
1710 using TOutAmount = TOut::Amount;
1711
1713 {
1715 step, book);
1716 }
1717 else
1718 {
1719 // LCOV_EXCL_START
1720 UNREACHABLE("xrpl::bookStepEqual : invalid book step");
1721 return false;
1722 // LCOV_EXCL_STOP
1723 }
1724 },
1725 book.in.getAmountType(),
1726 book.out.getAmountType());
1727}
1728} // namespace test
1729
1730//------------------------------------------------------------------------------
1731
1732template <class TIn, class TOut>
1734makeBookStepHelper(StrandContext const& ctx, Asset const& in, Asset const& out)
1735{
1736 TER ter = tefINTERNAL;
1739 {
1740 auto offerCrossingStep = std::make_unique<BookOfferCrossingStep<TIn, TOut>>(ctx, in, out);
1741 ter = offerCrossingStep->check(ctx);
1742 r = std::move(offerCrossingStep);
1743 }
1744 else // payment
1745 {
1746 auto paymentStep = std::make_unique<BookPaymentStep<TIn, TOut>>(ctx, in, out);
1747 ter = paymentStep->check(ctx);
1748 r = std::move(paymentStep);
1749 }
1750 if (!isTesSuccess(ter))
1751 return {ter, nullptr};
1752
1753 return {tesSUCCESS, std::move(r)};
1754}
1755
1757makeBookStepIi(StrandContext const& ctx, Issue const& in, Issue const& out)
1758{
1759 return makeBookStepHelper<IOUAmount, IOUAmount>(ctx, in, out);
1760}
1761
1763makeBookStepIx(StrandContext const& ctx, Issue const& in)
1764{
1766}
1767
1769makeBookStepXi(StrandContext const& ctx, Issue const& out)
1770{
1772}
1773
1774// MPT's
1776makeBookStepMm(StrandContext const& ctx, MPTIssue const& in, MPTIssue const& out)
1777{
1778 return makeBookStepHelper<MPTAmount, MPTAmount>(ctx, in, out);
1779}
1780
1782makeBookStepMi(StrandContext const& ctx, MPTIssue const& in, Issue const& out)
1783{
1784 return makeBookStepHelper<MPTAmount, IOUAmount>(ctx, in, out);
1785}
1786
1788makeBookStepIm(StrandContext const& ctx, Issue const& in, MPTIssue const& out)
1789{
1790 return makeBookStepHelper<IOUAmount, MPTAmount>(ctx, in, out);
1791}
1792
1795{
1797}
1798
1801{
1803}
1804
1805} // namespace xrpl
T accumulate(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Represents synthetic AMM offer in BookStep.
Definition AMMOffer.h:30
Quality quality() const noexcept
Definition AMMOffer.h:59
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
Definition Asset.h:117
constexpr TIss const & get() const
AccountID const & getIssuer() const
Definition Asset.cpp:21
constexpr bool holds() const
Definition Asset.h:177
std::uint32_t getOfrInRate(Step const *prevStep, AccountID const &owner, std::uint32_t trIn) const
Definition BookStep.cpp:507
std::string logString() const override
Definition BookStep.cpp:565
Quality adjustQualityWithFees(ReadView const &v, Quality const &ofrQ, DebtDirection prevStepDir, WaiveTransferFee waiveFee, OfferType offerType) const
Definition BookStep.cpp:532
bool checkQualityThreshold(Quality const &quality) const
Definition BookStep.cpp:480
BookOfferCrossingStep(StrandContext const &ctx, Asset const &in, Asset const &out)
Definition BookStep.cpp:413
bool limitSelfCrossQuality(AccountID const &strandSrc, AccountID const &strandDst, Offer< TIn, TOut > const &offer, std::optional< Quality > &ofrQ, FlowOfferStream< TIn, TOut > &offers, bool const offerAttempted) const
Definition BookStep.cpp:422
static Quality getQuality(std::optional< Quality > const &limitQuality)
Definition BookStep.cpp:403
std::optional< Quality > qualityThreshold(Quality const &lobQuality) const
Definition BookStep.cpp:496
Quality const qualityThreshold_
Definition BookStep.cpp:572
std::uint32_t getOfrOutRate(Step const *prevStep, AccountID const &owner, AccountID const &strandDst, std::uint32_t trOut) const
Definition BookStep.cpp:518
BookPaymentStep(StrandContext const &ctx, Asset const &in, Asset const &out)
Definition BookStep.cpp:309
std::optional< Quality > qualityThreshold(Quality const &lobQuality) const
Definition BookStep.cpp:341
bool limitSelfCrossQuality(AccountID const &, AccountID const &, Offer< TIn, TOut > const &offer, std::optional< Quality > &, FlowOfferStream< TIn, TOut > &, bool) const
Definition BookStep.cpp:320
Quality adjustQualityWithFees(ReadView const &v, Quality const &ofrQ, DebtDirection prevStepDir, WaiveTransferFee waiveFee, OfferType) const
Definition BookStep.cpp:361
std::uint32_t getOfrInRate(Step const *, AccountID const &, std::uint32_t trIn) const
Definition BookStep.cpp:348
std::uint32_t getOfrOutRate(Step const *, AccountID const &, AccountID const &, std::uint32_t trOut) const
Definition BookStep.cpp:355
std::string logString() const override
Definition BookStep.cpp:386
bool checkQualityThreshold(Quality const &quality) const
Definition BookStep.cpp:333
TER check(StrandContext const &ctx) const
AccountID strandSrc_
Definition BookStep.cpp:63
Step const *const prevStep_
Definition BookStep.cpp:66
friend bool operator==(BookStep const &lhs, BookStep const &rhs)
Definition BookStep.cpp:220
std::optional< Book > bookStepBook() const override
Definition BookStep.cpp:163
beast::Journal const j_
Definition BookStep.cpp:83
std::optional< std::variant< Quality, AMMOffer< TIn, TOut > > > tip(ReadView const &view) const
void tryConsumeOffer(PaymentSandbox &sb, Offer< TIn, TOut > &offer, TAmounts< TIn, TOut > const &ofrAmt, TAmounts< TIn, TOut > const &stepAmt, TOut const &ownerGives) const
std::optional< QualityFunction > tipOfferQualityF(ReadView const &view) const
Asset const strandDeliver_
Definition BookStep.cpp:84
std::optional< EitherAmount > cachedIn() const override
Definition BookStep.cpp:141
std::optional< AMMOffer< TIn, TOut > > getAMMOffer(ReadView const &view, std::optional< Quality > const &clobQuality) const
bool const ownerPaysTransferFee_
Definition BookStep.cpp:67
DebtDirection debtDirection(ReadView const &sb, StrandDirection dir) const override
Definition BookStep.cpp:157
BookStep(StrandContext const &ctx, Asset const &in, Asset const &out)
Definition BookStep.cpp:104
void consumeOffer(PaymentSandbox &sb, Offer< TIn, TOut > &offer, TAmounts< TIn, TOut > const &ofrAmt, TAmounts< TIn, TOut > const &stepAmt, TOut const &ownerGives) const
bool equal(Step const &rhs) const override
Definition BookStep.cpp:579
std::optional< TIn > maxIn_
Definition BookStep.cpp:89
std::optional< Cache > cache_
Definition BookStep.cpp:101
std::uint32_t offersUsed_
Number of offers consumed or partially consumed the last time the step ran, including expired and unf...
Definition BookStep.cpp:78
std::pair< boost::container::flat_set< UInt256 >, std::uint32_t > forEachOffer(PaymentSandbox &sb, ApplyView &afView, DebtDirection prevStepDebtDir, Callback &callback) const
Definition BookStep.cpp:728
std::optional< EitherAmount > cachedOut() const override
Definition BookStep.cpp:149
std::pair< std::optional< Quality >, DebtDirection > qualityUpperBound(ReadView const &v, DebtDirection prevStepDir) const override
Definition BookStep.cpp:588
bool inactive() const override
Definition BookStep.cpp:199
friend bool operator!=(BookStep const &lhs, BookStep const &rhs)
Definition BookStep.cpp:226
std::uint32_t offersUsed() const override
Definition BookStep.cpp:640
std::pair< std::optional< QualityFunction >, DebtDirection > getQualityFunc(ReadView const &v, DebtDirection prevStepDir) const override
Definition BookStep.cpp:606
std::pair< TIn, TOut > fwdImp(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, TIn const &in)
std::optional< AMMLiquidity< TIn, TOut > > ammLiquidity_
Definition BookStep.cpp:82
Rate rate(ReadView const &view, Asset const &asset, AccountID const &dstAccount) const
std::pair< TIn, TOut > revImp(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, TOut const &out)
Book const & book() const
Definition BookStep.cpp:135
static constexpr uint32_t kMaxOffersToConsume
Definition BookStep.cpp:61
std::optional< std::pair< Quality, OfferType > > tipOfferQuality(ReadView const &view) const
AccountID strandDst_
Definition BookStep.cpp:64
std::string logStringImpl(char const *name) const
Definition BookStep.cpp:206
bool checkMPTDEX(ReadView const &view, AccountID const &owner) const
std::pair< bool, EitherAmount > validFwd(PaymentSandbox &sb, ApplyView &afView, EitherAmount const &in) override
Iterates and consumes raw offers in an order book.
Definition BookTip.h:20
bool step(beast::Journal j)
Erases the current offer and advance to the next offer.
Definition BookTip.cpp:19
Quality const & quality() const noexcept
Definition BookTip.h:50
Specifies an order book.
Definition Book.h:28
Presents and consumes the offers in an order book.
boost::container::flat_set< UInt256 > const & permToRemove() const
void permRmOffer(UInt256 const &offerIndex) override
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
AccountID account
Definition Issue.h:21
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
A wrapper which makes credits unavailable to balances.
Average quality of a path as a function of out: q(out) = m * out + b, where m = -1 / poolGets,...
void combine(QualityFunction const &qf)
Combines QF with the next step QF.
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
NetClock::time_point parentCloseTime() const
Returns the close time of the previous ledger.
Definition ReadView.h:106
virtual bool exists(Keylet const &k) const =0
Determine if a state item exists.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
static std::uint64_t const kURateOne
Definition STAmount.h:78
Discardable, editable view to a ledger.
Definition Sandbox.h:18
A step in a payment path.
Definition Steps.h:83
virtual std::optional< AccountID > directStepSrcAcct() const
If this step is DirectStepI (IOU->IOU direct step), return the src account.
Definition Steps.h:142
virtual std::optional< Book > bookStepBook() const
If this step is a BookStep, return the book.
Definition Steps.h:220
TOffer< TIn, TOut > & tip() const
Returns the offer at the tip of the order book.
Definition OfferStream.h:94
TOut ownerFunds() const
bool step()
Advance to the next valid offer.
Rules const & rules() const override
Returns the tx processing rules.
T empty(T... args)
T get_if(T... args)
T is_same_v
T make_pair(T... args)
T make_unique(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
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
bool bookStepEqual(Step const &step, xrpl::Book const &book)
static bool equalHelper(Step const &step, xrpl::Book const &book)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static void limitOfferIn(Offer const &offer, TAmounts< TIn, TOut > &ofrAmt, TAmounts< TIn, TOut > &stpAmt, TOut &ownerGives, std::uint32_t transferRateOut, TIn const &inLmt)
Definition BookStep.cpp:649
@ terNO_LINE
Definition TER.h:221
@ terNO_RIPPLE
Definition TER.h:226
std::int64_t maxMPTAmount(SLE const &sleIssuance)
MaximumAmount doesn't exceed 2**63-1.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
static auto sum(TCollection const &col)
std::pair< TER, std::unique_ptr< Step > > makeBookStepIi(StrandContext const &ctx, Issue const &in, Issue const &out)
TER checkCreateMPT(xrpl::ApplyView &view, xrpl::MPTIssue const &mptIssue, xrpl::AccountID const &holder, SLE::Ref sponsorSle, std::uint32_t flags, beast::Journal j)
bool isXRP(AccountID const &c)
Definition AccountID.h:84
static void limitStepOut(Offer const &offer, TAmounts< TIn, TOut > &ofrAmt, TAmounts< TIn, TOut > &stpAmt, TOut &ownerGives, std::uint32_t transferRateIn, std::uint32_t transferRateOut, TOut const &limit)
Definition BookStep.cpp:700
T get(Section const &section, std::string const &name, T const &defaultValue=T{})
Retrieve a key/value pair from a section.
std::pair< TER, std::unique_ptr< Step > > makeBookStepMx(StrandContext const &ctx, MPTIssue const &in)
void setUnion(boost::container::flat_set< T > &dst, boost::container::flat_set< T > const &src)
Given two flat sets dst and src, compute dst = dst union src.
Definition FlatSets.h:16
@ tefINTERNAL
Definition TER.h:167
WaiveTransferFee
std::pair< TER, std::unique_ptr< Step > > makeBookStepMi(StrandContext const &ctx, MPTIssue const &in, Issue const &out)
static void limitStepIn(Offer const &offer, TAmounts< TIn, TOut > &ofrAmt, TAmounts< TIn, TOut > &stpAmt, TOut &ownerGives, std::uint32_t transferRateIn, std::uint32_t transferRateOut, TIn const &limit)
Definition BookStep.cpp:680
TER canTransfer(ReadView const &view, MPTIssue const &mptIssue, AccountID const &from, AccountID const &to, WaiveMPTCanTransfer waive=WaiveMPTCanTransfer::No, std::uint8_t depth=0)
Check whether to may receive the given MPT from from.
DebtDirection
Definition Steps.h:38
std::pair< TER, std::unique_ptr< Step > > makeBookStepIx(StrandContext const &ctx, Issue const &in)
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
TER canTrade(ReadView const &view, Asset const &asset, std::uint8_t depth=0)
Check whether asset may be traded on the DEX.
T toAmount(STAmount const &amt)=delete
StrandDirection
Definition Steps.h:40
std::optional< MPTAmount > tryMulRatio(MPTAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Definition MPTAmount.h:179
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
static bool isDefaultPath(STPath const &path)
std::pair< TER, std::unique_ptr< Step > > makeBookStepXm(StrandContext const &ctx, MPTIssue const &out)
IOUAmount mulRatio(IOUAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
Rate const kParityRate
A transfer rate signifying a 1:1 exchange.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
std::pair< TER, std::unique_ptr< Step > > makeBookStepXi(StrandContext const &ctx, Issue const &out)
bool checkNear(IOUAmount const &expected, IOUAmount const &actual)
Definition PaySteps.cpp:36
@ TapNone
Definition ApplyView.h:28
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
std::pair< TER, std::unique_ptr< Step > > makeBookStepIm(StrandContext const &ctx, Issue const &in, MPTIssue const &out)
@ temBAD_PATH
Definition TER.h:84
@ temBAD_PATH_LOOP
Definition TER.h:85
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
bool isConsistent(Asset const &asset)
Definition Asset.h:323
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.
@ tecINTERNAL
Definition TER.h:321
@ tecINVARIANT_FAILED
Definition TER.h:324
@ tecNO_ISSUER
Definition TER.h:310
void issuerSelfDebitHookMPT(ApplyView &view, MPTIssue const &issue, std::uint64_t amount)
Facilitate tracking of MPT sold by an issuer owning MPT sell offer.
bool redeems(DebtDirection dir)
Definition Steps.h:44
static std::pair< TER, std::unique_ptr< Step > > makeBookStepHelper(StrandContext const &ctx, Asset const &in, Asset const &out)
std::pair< TER, std::unique_ptr< Step > > makeBookStepMm(StrandContext const &ctx, MPTIssue const &in, MPTIssue const &out)
Quality composedQuality(Quality const &lhs, Quality const &rhs)
Calculate the quality of a two-hop path given the two hops.
Definition Quality.cpp:151
@ tesSUCCESS
Definition TER.h:253
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
STAmount toSTAmount(IOUAmount const &iou, Asset const &asset)
T str(T... args)
Cache(TIn const &in, TOut const &out)
Definition BookStep.cpp:96
UInt256 key
Definition Keylet.h:21
Represents a transfer rate.
Definition Rate.h:21
Context needed to build Strand Steps and for error checking.
Definition Steps.h:568
ReadView const & view
Current ReadView.
Definition Steps.h:569
bool const isFirst
true if Step is first in Strand
Definition Steps.h:574
std::array< boost::container::flat_set< Asset >, 2 > & seenDirectAssets
A strand may not include the same account node more than once in the same currency.
Definition Steps.h:591
AccountID const strandSrc
Strand source account.
Definition Steps.h:570
boost::container::flat_set< Asset > & seenBookOuts
A strand may not include an offer that output the same issue more than once.
Definition Steps.h:596
Step const *const prevStep
The previous step in the strand.
Definition Steps.h:584
OfferCrossing const offerCrossing
Yes/Sell if offer crossing, not payment.
Definition Steps.h:577
Represents a pair of input and output currencies.
Definition Quality.h:29
T visit(T... args)