xrpld
Loading...
Searching...
No Matches
StrandFlow.h
1#pragma once
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/beast/utility/Journal.h>
7#include <xrpl/beast/utility/Zero.h>
8#include <xrpl/beast/utility/instrumentation.h>
9#include <xrpl/ledger/PaymentSandbox.h>
10#include <xrpl/ledger/helpers/AMMHelpers.h>
11#include <xrpl/ledger/helpers/OfferHelpers.h>
12#include <xrpl/protocol/Concepts.h>
13#include <xrpl/protocol/Feature.h>
14#include <xrpl/protocol/IOUAmount.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/MPTAmount.h>
17#include <xrpl/protocol/Quality.h>
18#include <xrpl/protocol/QualityFunction.h>
19#include <xrpl/protocol/STAmount.h>
20#include <xrpl/protocol/TER.h>
21#include <xrpl/protocol/XRPAmount.h>
22#include <xrpl/tx/paths/detail/FlatSets.h>
23#include <xrpl/tx/paths/detail/Steps.h>
24#include <xrpl/tx/transactors/dex/AMMContext.h>
25
26#include <boost/container/flat_set.hpp>
27
28#include <algorithm>
29#include <cstddef>
30#include <cstdint>
31#include <iterator>
32#include <memory>
33#include <optional>
34#include <tuple>
35#include <type_traits>
36#include <utility>
37#include <vector>
38
39namespace xrpl {
40
44template <class TInAmt, class TOutAmt>
46{
47 bool success = false;
48 TInAmt in = beast::kZero;
49 TOutAmt out = beast::kZero;
51 boost::container::flat_set<UInt256> ofrsToRm;
52 // Num offers consumed or partially consumed (includes expired and unfunded
53 // offers)
55 // strand can be inactive if there is no more liquidity or too many offers
56 // have been consumed
57 bool inactive = false;
59
63 StrandResult() = default;
64
66 Strand const& strand,
67 TInAmt const& in,
68 TOutAmt const& out,
70 boost::container::flat_set<UInt256> ofrsToRemoveMember,
71 bool inactive)
72 : success(true)
73 , in(in)
74 , out(out)
75 , sandbox(std::move(sandbox))
76 , ofrsToRm(std::move(ofrsToRemoveMember))
77 , ofrsUsed(offersUsed(strand))
79 {
80 }
81
82 StrandResult(Strand const& strand, boost::container::flat_set<UInt256> ofrsToRemoveMember)
83 : ofrsToRm(std::move(ofrsToRemoveMember)), ofrsUsed(offersUsed(strand))
84 {
85 }
86};
87
99template <class TInAmt, class TOutAmt>
100StrandResult<TInAmt, TOutAmt>
102 PaymentSandbox const& baseView,
103 Strand const& strand,
104 std::optional<TInAmt> const& maxIn,
105 TOutAmt const& out,
107{
109 if (strand.empty())
110 {
111 JLOG(j.warn()) << "Empty strand passed to Liquidity";
112 return {};
113 }
114
115 boost::container::flat_set<UInt256> ofrsToRm;
116
117 if (isDirectXrpToXrp<TInAmt, TOutAmt>(strand))
118 {
119 return Result{strand, std::move(ofrsToRm)};
120 }
121
122 try
123 {
124 std::size_t const s = strand.size();
125
126 std::size_t limitingStep = strand.size();
127 std::optional<PaymentSandbox> sb(&baseView);
128 // The "all funds" view determines if an offer becomes unfunded or is
129 // found unfunded
130 // These are the account balances before the strand executes
131 std::optional<PaymentSandbox> afView(&baseView);
133 {
134 EitherAmount stepOut(out);
135 for (auto i = s; i--;)
136 {
137 auto r = strand[i]->rev(*sb, *afView, ofrsToRm, stepOut);
138 if (strand[i]->isZero(r.second))
139 {
140 JLOG(j.trace()) << "Strand found dry in rev";
141 return Result{strand, std::move(ofrsToRm)};
142 }
143
144 if (i == 0 && maxIn && *maxIn < get<TInAmt>(r.first))
145 {
146 // limiting - exceeded maxIn
147 // Throw out previous results
148 sb.emplace(&baseView);
149 limitingStep = i;
150
151 // re-execute the limiting step
152 r = strand[i]->fwd(*sb, *afView, ofrsToRm, EitherAmount(*maxIn));
153 limitStepOut = r.second;
154
155 if (strand[i]->isZero(r.second))
156 {
157 JLOG(j.trace()) << "First step found dry";
158 return Result{strand, std::move(ofrsToRm)};
159 }
160 if (get<TInAmt>(r.first) != *maxIn)
161 {
162 // Something is very wrong
163 // throwing out the sandbox can only increase liquidity
164 // yet the limiting is still limiting
165 // LCOV_EXCL_START
166 JLOG(j.fatal())
167 << "Re-executed limiting step failed. r.first: "
168 << to_string(get<TInAmt>(r.first)) << " maxIn: " << to_string(*maxIn);
169 UNREACHABLE(
170 "xrpl::flow : first step re-executing the "
171 "limiting step failed");
172 return Result{strand, std::move(ofrsToRm)};
173 // LCOV_EXCL_STOP
174 }
175 }
176 else if (!strand[i]->equalOut(r.second, stepOut))
177 {
178 // limiting
179 // Throw out previous results
180 sb.emplace(&baseView);
181 afView.emplace(&baseView);
182 limitingStep = i;
183
184 // re-execute the limiting step
185 stepOut = r.second;
186 r = strand[i]->rev(*sb, *afView, ofrsToRm, stepOut);
187 limitStepOut = r.second;
188
189 if (strand[i]->isZero(r.second))
190 {
191 // A tiny input amount can cause this step to output
192 // zero. I.e. 10^-80 IOU into an IOU -> XRP offer.
193 JLOG(j.trace()) << "Limiting step found dry";
194 return Result{strand, std::move(ofrsToRm)};
195 }
196 if (!strand[i]->equalOut(r.second, stepOut))
197 {
198 // Something is very wrong
199 // throwing out the sandbox can only increase liquidity
200 // yet the limiting is still limiting
201 // LCOV_EXCL_START
202#ifndef NDEBUG
203 JLOG(j.fatal())
204 << "Re-executed limiting step failed. r.second: " << r.second
205 << " stepOut: " << stepOut;
206#else
207 JLOG(j.fatal()) << "Re-executed limiting step failed";
208#endif
209 UNREACHABLE(
210 "xrpl::flow : limiting step re-executing the "
211 "limiting step failed");
212 return Result{strand, std::move(ofrsToRm)};
213 // LCOV_EXCL_STOP
214 }
215 }
216
217 // prev node needs to produce what this node wants to consume
218 stepOut = r.first;
219 }
220 }
221
222 {
224 for (auto i = limitingStep + 1; i < s; ++i)
225 {
226 auto const r = strand[i]->fwd(*sb, *afView, ofrsToRm, stepIn);
227 if (strand[i]->isZero(r.second))
228 {
229 // A tiny input amount can cause this step to output zero.
230 // I.e. 10^-80 IOU into an IOU -> XRP offer.
231 JLOG(j.trace()) << "Non-limiting step found dry";
232 return Result{strand, std::move(ofrsToRm)};
233 }
234 if (!strand[i]->equalIn(r.first, stepIn))
235 {
236 // The limits should already have been found, so executing a
237 // strand forward from the limiting step should not find a
238 // new limit
239 // LCOV_EXCL_START
240#ifndef NDEBUG
241 JLOG(j.fatal()) << "Re-executed forward pass failed. r.first: " << r.first
242 << " stepIn: " << stepIn;
243#else
244 JLOG(j.fatal()) << "Re-executed forward pass failed";
245#endif
246 UNREACHABLE(
247 "xrpl::flow : non-limiting step re-executing the "
248 "forward pass failed");
249 return Result{strand, std::move(ofrsToRm)};
250 // LCOV_EXCL_STOP
251 }
252 stepIn = r.second;
253 }
254 }
255
256 // NOLINTBEGIN(bugprone-unchecked-optional-access) cachedIn/Out set after strand is stepped
257 // above
258 auto const strandIn = *strand.front()->cachedIn();
259 auto const strandOut = *strand.back()->cachedOut();
260 // NOLINTEND(bugprone-unchecked-optional-access)
261
262#ifndef NDEBUG
263 {
264 // Check that the strand will execute as intended
265 // Re-executing the strand will change the cached values
266 PaymentSandbox checkSB(&baseView);
267 PaymentSandbox checkAfView(&baseView);
268 EitherAmount stepIn(
269 *strand[0]->cachedIn()); // NOLINT(bugprone-unchecked-optional-access)
270 for (auto i = 0; i < s; ++i)
271 {
272 bool valid = false;
273 std::tie(valid, stepIn) = strand[i]->validFwd(checkSB, checkAfView, stepIn);
274 if (!valid)
275 {
276 JLOG(j.warn()) << "Strand re-execute check failed. Step: " << i;
277 break;
278 }
279 }
280 }
281#endif
282
283 bool const inactive =
284 std::any_of(strand.begin(), strand.end(), [](std::unique_ptr<Step> const& step) {
285 return step->inactive();
286 });
287
288 return Result(
289 strand,
290 get<TInAmt>(strandIn),
291 get<TOutAmt>(strandOut),
292 std::move(*sb),
293 std::move(ofrsToRm),
294 inactive);
295 }
296 catch (FlowException const&)
297 {
298 return Result{strand, std::move(ofrsToRm)};
299 }
300}
301
303template <class TInAmt, class TOutAmt>
304struct FlowResult
305{
306 TInAmt in = beast::kZero;
307 TOutAmt out = beast::kZero;
309 boost::container::flat_set<UInt256> removableOffers;
310 TER ter = temUNKNOWN;
311
312 FlowResult() = default;
313
314 FlowResult(
315 TInAmt const& in,
316 TOutAmt const& out,
317 PaymentSandbox&& sandbox,
318 boost::container::flat_set<UInt256> ofrsToRm)
319 : in(in)
320 , out(out)
321 , sandbox(std::move(sandbox))
322 , removableOffers(std::move(ofrsToRm))
323 , ter(tesSUCCESS)
324 {
325 }
326
327 FlowResult(TER ter, boost::container::flat_set<UInt256> ofrsToRm)
328 : removableOffers(std::move(ofrsToRm)), ter(ter)
329 {
330 }
331
332 FlowResult(
333 TER ter,
334 TInAmt const& in,
335 TOutAmt const& out,
336 boost::container::flat_set<UInt256> ofrsToRm)
337 : in(in), out(out), removableOffers(std::move(ofrsToRm)), ter(ter)
338 {
339 }
340};
342
344inline std::optional<Quality>
345qualityUpperBound(ReadView const& v, Strand const& strand)
346{
348 std::optional<Quality> stepQ;
350 for (auto const& step : strand)
351 {
352 if (std::tie(stepQ, dir) = step->qualityUpperBound(v, dir); stepQ)
353 {
354 q = composedQuality(q, *stepQ);
355 }
356 else
357 {
358 return std::nullopt;
359 }
360 }
361 return q;
362};
364
375template <StepAmount TOutAmt>
376inline TOutAmt
377limitOut(
378 ReadView const& v,
379 Strand const& strand,
380 TOutAmt const& remainingOut,
381 Quality const& limitQuality)
382{
383 std::optional<QualityFunction> stepQualityFunc;
384 std::optional<QualityFunction> qf;
386 for (auto const& step : strand)
387 {
388 if (std::tie(stepQualityFunc, dir) = step->getQualityFunc(v, dir); stepQualityFunc)
389 {
390 if (!qf)
391 {
392 qf = stepQualityFunc;
393 }
394 else
395 {
396 qf->combine(*stepQualityFunc);
397 }
398 }
399 else
400 {
401 return remainingOut;
402 }
403 }
404
405 // QualityFunction is constant
406 if (!qf || qf->isConst())
407 return remainingOut;
408
409 auto const out = [&] {
410 auto const out = qf->outFromAvgQ(limitQuality);
411 if (!out)
412 return remainingOut;
414 {
415 auto const roundedOut = TOutAmt{*out};
416 // Integral outputs that round above the continuous target can
417 // realize worse average quality than the requested limit. Keep the
418 // default rounded value when it still satisfies the limit, since it
419 // is the largest matching offer; otherwise round down.
420 if (v.rules().enabled(featureMPTokensV2) && roundedOut > *out &&
421 !qf->satisfiesAvgQ(limitQuality, roundedOut))
422 {
424 return TOutAmt{*out};
425 }
426 return roundedOut;
427 }
428 else if constexpr (std::is_same_v<TOutAmt, IOUAmount>)
429 {
430 return IOUAmount{*out};
431 }
432 else
433 {
434 static constexpr bool kAlwaysFalse = !std::is_same_v<TOutAmt, TOutAmt>;
435 static_assert(kAlwaysFalse, "Unhandled StepAmount type");
436 }
437 }();
438 // A tiny difference could be due to the round off
439 if (withinRelativeDistance(out, remainingOut, Number(1, -9)))
440 return remainingOut;
441 return std::min(out, remainingOut);
442};
444
446/* Track the non-dry strands
447
448 flow will search the non-dry strands (stored in `cur_`) for the best
449 available liquidity If flow doesn't use all the liquidity of a strand, that
450 strand is added to `next_`. The strands in `next_` are searched after the
451 current best liquidity is used.
452 */
453class ActiveStrands
454{
455private:
456 // Strands to be explored for liquidity
457 std::vector<Strand const*> cur_;
458 // Strands that may be explored for liquidity on the next iteration
459 std::vector<Strand const*> next_;
460
461public:
462 ActiveStrands(std::vector<Strand> const& strands)
463 {
464 cur_.reserve(strands.size());
465 next_.reserve(strands.size());
466 for (auto& strand : strands)
467 next_.push_back(&strand);
468 }
469
470 // Start a new iteration in the search for liquidity
471 // Set the current strands to the strands in `next_`
472 void
473 activateNext(ReadView const& v, std::optional<Quality> const& limitQuality)
474 {
475 // add the strands in `next_` to `cur_`, sorted by theoretical quality.
476 // Best quality first.
477 cur_.clear();
478 if (!next_.empty())
479 {
480 std::vector<std::pair<Quality, Strand const*>> strandQualities;
481 strandQualities.reserve(next_.size());
482 if (next_.size() > 1) // no need to sort one strand
483 {
484 for (Strand const* strand : next_)
485 {
486 if (strand == nullptr)
487 {
488 // should not happen
489 continue;
490 }
491 if (auto const qual = qualityUpperBound(v, *strand))
492 {
493 if (limitQuality && *qual < *limitQuality)
494 {
495 // If a strand's quality is ever over limitQuality
496 // it is no longer part of the candidate set. Note
497 // that when transfer fees are charged, and an
498 // account goes from redeeming to issuing then
499 // strand quality _can_ increase; However, this is
500 // an unusual corner case.
501 continue;
502 }
503 strandQualities.emplace_back(*qual, strand);
504 }
505 }
506 // must stable sort for deterministic order across different c++
507 // standard library implementations
509 strandQualities,
510
511 [](auto const& lhs, auto const& rhs) {
512 // higher qualities first
513 return std::get<Quality>(lhs) > std::get<Quality>(rhs);
514 });
515 next_.clear();
516 next_.reserve(strandQualities.size());
517 for (auto const& sq : strandQualities)
518 {
519 next_.push_back(std::get<Strand const*>(sq));
520 }
521 }
522 }
523 std::swap(cur_, next_);
524 }
525
526 [[nodiscard]] Strand const*
527 get(size_t i) const
528 {
529 if (i >= cur_.size())
530 {
531 // LCOV_EXCL_START
532 UNREACHABLE("xrpl::ActiveStrands::get : input out of range");
533 return nullptr;
534 // LCOV_EXCL_STOP
535 }
536 return cur_[i];
537 }
538
539 void
540 push(Strand const* s)
541 {
542 next_.push_back(s);
543 }
544
545 // Push the strands from index i to the end of cur_ to next_
546 void
547 pushRemainingCurToNext(size_t i)
548 {
549 if (i >= cur_.size())
550 return;
551 next_.insert(next_.end(), std::next(cur_.begin(), i), cur_.end());
552 }
553
554 [[nodiscard]] auto
555 size() const
556 {
557 return cur_.size();
558 }
559};
561
581template <StepAmount TInAmt, StepAmount TOutAmt>
582FlowResult<TInAmt, TOutAmt>
584 PaymentSandbox const& baseView,
585 std::vector<Strand> const& strands,
586 TOutAmt const& outReq,
587 bool partialPayment,
588 OfferCrossing offerCrossing,
589 std::optional<Quality> const& limitQuality,
590 std::optional<STAmount> const& sendMaxST,
592 AMMContext& ammContext)
593{
594 // Used to track the strand that offers the best quality (output/input
595 // ratio)
596 struct BestStrand
597 {
598 TInAmt in;
599 TOutAmt out;
601 Strand const& strand;
602 Quality quality;
603
604 BestStrand(
605 TInAmt const& in,
606 TOutAmt const& out,
607 PaymentSandbox&& sb,
608 Strand const& strand,
609 Quality const& quality)
610 : in(in), out(out), sb(std::move(sb)), strand(strand), quality(quality)
611 {
612 }
613 };
614
615 std::size_t const maxTries = 1000;
616 std::size_t curTry = 0;
617 std::uint32_t const maxOffersToConsider = 1500;
618 std::uint32_t offersConsidered = 0;
619
620 // There is a bug in gcc that incorrectly warns about using uninitialized
621 // values if `remainingIn` is initialized through a copy constructor. We can
622 // get similar warnings for `sendMax` if it is initialized in the most
623 // natural way. Using `make_optional`, allows us to work around this bug.
624 TInAmt const sendMaxInit = sendMaxST ? toAmount<TInAmt>(*sendMaxST) : TInAmt{beast::kZero};
625 std::optional<TInAmt> const sendMax =
626 (sendMaxST && sendMaxInit >= beast::kZero) ? std::make_optional(sendMaxInit) : std::nullopt;
627 std::optional<TInAmt> remainingIn = !!sendMax ? std::make_optional(sendMaxInit) : std::nullopt;
628 // std::optional<TInAmt> remainingIn{sendMax};
629
630 TOutAmt remainingOut(outReq);
631
632 PaymentSandbox sb(&baseView);
633
634 // non-dry strands
635 ActiveStrands activeStrands(strands);
636
637 // Keeping a running sum of the amount in the order they are processed
638 // will not give the best precision. Keep a collection so they may be summed
639 // from smallest to largest
640 boost::container::flat_multiset<TInAmt> savedIns;
641 savedIns.reserve(maxTries);
642 boost::container::flat_multiset<TOutAmt> savedOuts;
643 savedOuts.reserve(maxTries);
644
645 // Returns std::nullopt if the aggregate overflows; callers treat that as a
646 // dry path.
647 auto const sum = [](auto const& col) -> std::optional<std::decay_t<decltype(*col.begin())>> {
648 using TResult = std::decay_t<decltype(*col.begin())>;
649 if (col.empty())
650 return TResult{beast::kZero};
651 TResult total = *col.begin();
652 for (auto it = col.begin() + 1; it != col.end(); ++it)
653 {
654 auto const next = checkedStepAddOpt(total, *it);
655 if (!next)
656 return std::nullopt;
657 total = *next;
658 }
659 return total;
660 };
661
662 // These offers only need to be removed if the payment is not
663 // successful
664 boost::container::flat_set<UInt256> ofrsToRmOnFail;
665
666 while (remainingOut > beast::kZero && (!remainingIn || *remainingIn > beast::kZero))
667 {
668 ++curTry;
669 if (curTry >= maxTries)
670 {
671 return {telFAILED_PROCESSING, std::move(ofrsToRmOnFail)};
672 }
673
674 activeStrands.activateNext(sb, limitQuality);
675
676 ammContext.setMultiPath(activeStrands.size() > 1);
677
678 // Limit only if one strand and limitQuality
679 auto const limitRemainingOut = [&] {
680 if (activeStrands.size() == 1 && limitQuality)
681 {
682 if (auto const strand = activeStrands.get(0))
683 return limitOut(sb, *strand, remainingOut, *limitQuality);
684 }
685 return remainingOut;
686 }();
687 auto const adjustedRemOut = limitRemainingOut != remainingOut;
688
689 boost::container::flat_set<UInt256> ofrsToRm;
691 for (size_t strandIndex = 0, sie = activeStrands.size(); strandIndex != sie; ++strandIndex)
692 {
693 Strand const* strand = activeStrands.get(strandIndex);
694 if (!strand)
695 {
696 // should not happen
697 continue;
698 }
699 // Clear AMM liquidity used flag. The flag might still be set if
700 // the previous strand execution failed. It has to be reset
701 // since this strand might not have AMM liquidity.
702 ammContext.clear();
703 if (offerCrossing != OfferCrossing::No && limitQuality)
704 {
705 auto const strandQ = qualityUpperBound(sb, *strand);
706 if (!strandQ || *strandQ < *limitQuality)
707 continue;
708 }
709 auto f = flow<TInAmt, TOutAmt>(sb, *strand, remainingIn, limitRemainingOut, j);
710
711 // rm bad offers even if the strand fails
712 setUnion(ofrsToRm, f.ofrsToRm);
713
714 offersConsidered += f.ofrsUsed;
715
716 if (!f.success || f.out == beast::kZero)
717 continue;
718
719 XRPL_ASSERT(
720 f.out <= remainingOut && f.sandbox && (!remainingIn || f.in <= *remainingIn),
721 "xrpl::flow : remaining constraints");
722
723 Quality const q(f.out, f.in);
724
725 JLOG(j.trace()) << "New flow iter (iter, in, out): " << curTry - 1 << " "
726 << to_string(f.in) << " " << to_string(f.out);
727
728 // limitOut() finds output to generate exact requested
729 // limitQuality. But the actual limit quality might be slightly
730 // off due to the round off.
731 if (limitQuality && q < *limitQuality &&
732 (!adjustedRemOut || !withinRelativeDistance(q, *limitQuality, Number(1, -7))))
733 {
734 JLOG(j.trace()) << "Path rejected by limitQuality"
735 << " limit: " << *limitQuality << " path q: " << q;
736 continue;
737 }
738
739 XRPL_ASSERT(!best, "xrpl::flow : best is unset");
740 if (!f.inactive)
741 activeStrands.push(strand);
742 best.emplace(f.in, f.out, std::move(*f.sandbox), *strand, q);
743 activeStrands.pushRemainingCurToNext(strandIndex + 1);
744 break;
745 }
746
747 bool const shouldBreak = !best || offersConsidered >= maxOffersToConsider;
748
749 if (best)
750 {
751 savedIns.insert(best->in);
752 savedOuts.insert(best->out);
753 auto const sumOut = sum(savedOuts);
754 if (!sumOut)
755 return {tecPATH_DRY, std::move(ofrsToRmOnFail)};
756 remainingOut = outReq - *sumOut;
757 if (sendMax)
758 {
759 auto const sumIn = sum(savedIns);
760 if (!sumIn)
761 return {tecPATH_DRY, std::move(ofrsToRmOnFail)};
762 remainingIn = *sendMax - *sumIn;
763 }
764
765 JLOG(j.trace()) << "Best path: in: " << to_string(best->in)
766 << " out: " << to_string(best->out)
767 << " remainingOut: " << to_string(remainingOut);
768
769 best->sb.apply(sb);
770 ammContext.update();
771 }
772 else
773 {
774 JLOG(j.trace()) << "All strands dry.";
775 }
776
777 best.reset(); // view in best must be destroyed before modifying base view
778 if (!ofrsToRm.empty())
779 {
780 setUnion(ofrsToRmOnFail, ofrsToRm);
781 for (auto const& o : ofrsToRm)
782 {
783 if (auto const ok = sb.peek(keylet::offer(o)))
784 offerDelete(sb, ok, j);
785 }
786 }
787
788 if (shouldBreak)
789 break;
790 }
791
792 auto const actualOutOpt = sum(savedOuts);
793 auto const actualInOpt = sum(savedIns);
794 if (!actualOutOpt || !actualInOpt)
795 return {tecPATH_DRY, std::move(ofrsToRmOnFail)};
796 auto const actualOut = *actualOutOpt;
797 auto const actualIn = *actualInOpt;
798
799 JLOG(j.trace()) << "Total flow: in: " << to_string(actualIn)
800 << " out: " << to_string(actualOut);
801
802 /* flowCross doesn't handle offer crossing with tfFillOrKill flag correctly.
803 * 1. If tfFillOrKill is set then the owner must receive the full
804 * TakerPays. We reverse pays and gets because during crossing
805 * we are taking, therefore the owner must deliver the full TakerPays and
806 * the entire TakerGets doesn't have to be spent.
807 * 2. If tfSell is also set then the owner must spend the entire TakerGets
808 * even if it means obtaining more than TakerPays. Since the pays and gets
809 * are reversed, the owner must send the entire TakerGets.
810 */
811
812 if (actualOut != outReq)
813 {
814 if (actualOut > outReq)
815 {
816 // Rounding in the payment engine is causing this assert to sometimes fire with "dust"
817 // amounts. This is causing issues when running debug builds of xrpld.
818 // While this issue still needs to be resolved, the assert is causing more harm than
819 // good at this point.
820 // UNREACHABLE("xrpl::flow : rounding error");
821
822 return {tefEXCEPTION, std::move(ofrsToRmOnFail)};
823 }
824 if (!partialPayment)
825 {
826 // If partialPayment is false, the caller requires full outReq (payments, or FillOrKill
827 // offers).
828 if (offerCrossing != OfferCrossing::Sell)
829 {
830 return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)};
831 }
832 }
833 else if (actualOut == beast::kZero)
834 {
835 return {tecPATH_DRY, std::move(ofrsToRmOnFail)};
836 }
837 }
838 if (!partialPayment && offerCrossing == OfferCrossing::Sell)
839 {
840 // If we're offer crossing and partialPayment is *not* true, then
841 // we're handling a FillOrKill offer.
842 XRPL_ASSERT(remainingIn, "xrpl::flow : nonzero remainingIn");
843 if (remainingIn && *remainingIn != beast::kZero)
844 return {tecPATH_PARTIAL, actualIn, actualOut, std::move(ofrsToRmOnFail)};
845 }
846
847 return {actualIn, actualOut, std::move(sb), std::move(ofrsToRmOnFail)};
848}
849
850} // namespace xrpl
T any_of(T... args)
T begin(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream trace() const
Severity stream access functions.
Definition Journal.h:338
Stream warn() const
Definition Journal.h:356
Maintains AMM info per overall payment engine execution and individual iteration.
Definition AMMContext.h:17
void setMultiPath(bool fs)
Definition AMMContext.h:51
void clear()
Strand execution may fail.
Definition AMMContext.h:93
Floating point representation of amounts with high dynamic range.
Definition IOUAmount.h:26
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
A wrapper which makes credits unavailable to balances.
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
A view into a ledger.
Definition ReadView.h:41
static std::uint64_t const kURateOne
Definition STAmount.h:78
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
T clear(T... args)
T emplace_back(T... args)
T emplace(T... args)
T empty(T... args)
T end(T... args)
T is_same_v
T make_optional(T... args)
T min(T... args)
T move(T... args)
constexpr Zero kZero
Definition Zero.h:30
STL namespace.
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Keylet offer(AccountID const &id, SeqProxy const &seq) noexcept
An offer from an account.
Definition Indexes.cpp:310
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ telFAILED_PROCESSING
Definition TER.h:42
static auto sum(TCollection const &col)
TER offerDelete(ApplyView &view, SLE::Ref sle, beast::Journal j)
Delete an offer.
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.
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
@ tefEXCEPTION
Definition TER.h:166
DebtDirection
Definition Steps.h:38
boost::outcome_v2::result< T, std::error_code > Result
Definition b58_utils.h:19
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
T toAmount(STAmount const &amt)=delete
StrandResult< TInAmt, TOutAmt > flow(PaymentSandbox const &baseView, Strand const &strand, std::optional< TInAmt > const &maxIn, TOutAmt const &out, beast::Journal j)
Request out amount from a strand.
Definition StrandFlow.h:101
bool withinRelativeDistance(Quality const &calcQuality, Quality const &reqQuality, Number const &dist)
Check if the relative distance between the qualities is within the requested distance.
Definition AMMHelpers.h:133
@ tecPATH_PARTIAL
Definition TER.h:293
@ tecPATH_DRY
Definition TER.h:305
OfferCrossing
Definition Steps.h:41
Quality composedQuality(Quality const &lhs, Quality const &rhs)
Calculate the quality of a two-hop path given the two hops.
Definition Quality.cpp:151
T next(T... args)
T push_back(T... args)
T reserve(T... args)
T reset(T... args)
T size(T... args)
T stable_sort(T... args)
Result of flow() execution of a single Strand.
Definition StrandFlow.h:46
TOutAmt out
Currency amount out.
Definition StrandFlow.h:49
StrandResult(Strand const &strand, TInAmt const &in, TOutAmt const &out, PaymentSandbox &&sandbox, boost::container::flat_set< UInt256 > ofrsToRemoveMember, bool inactive)
Definition StrandFlow.h:65
std::optional< PaymentSandbox > sandbox
Resulting Sandbox state.
Definition StrandFlow.h:50
bool success
Strand succeeded.
Definition StrandFlow.h:47
std::uint32_t ofrsUsed
Definition StrandFlow.h:54
StrandResult()=default
Strand result constructor.
boost::container::flat_set< UInt256 > ofrsToRm
Offers to remove.
Definition StrandFlow.h:51
StrandResult(Strand const &strand, boost::container::flat_set< UInt256 > ofrsToRemoveMember)
Definition StrandFlow.h:82
TInAmt in
Currency amount in.
Definition StrandFlow.h:48
bool inactive
Strand should not considered as a further source of liquidity (dry).
Definition StrandFlow.h:57
T swap(T... args)
T tie(T... args)