xrpld
Loading...
Searching...
No Matches
Steps.h
1#pragma once
2
3#include <xrpl/basics/MathUtilities.h>
4#include <xrpl/basics/base_uint.h>
5#include <xrpl/basics/contract.h>
6#include <xrpl/beast/utility/Journal.h>
7#include <xrpl/beast/utility/Zero.h>
8#include <xrpl/protocol/AccountID.h>
9#include <xrpl/protocol/Book.h>
10#include <xrpl/protocol/Concepts.h>
11#include <xrpl/protocol/Quality.h>
12#include <xrpl/protocol/QualityFunction.h>
13#include <xrpl/protocol/STPathSet.h>
14#include <xrpl/protocol/TER.h>
15#include <xrpl/protocol/UintTypes.h>
16#include <xrpl/tx/paths/detail/EitherAmount.h>
17
18#include <boost/container/flat_set.hpp>
19
20#include <array>
21#include <cstddef>
22#include <cstdint>
23#include <memory>
24#include <optional>
25#include <ostream>
26#include <stdexcept>
27#include <string>
28#include <type_traits>
29#include <utility>
30#include <vector>
31
32namespace xrpl {
33class PaymentSandbox;
34class ReadView;
35class ApplyView;
36class AMMContext;
37
39enum class QualityDirection { In, Out };
41enum class OfferCrossing { No = 0, Yes = 1, Sell = 2 };
42
43inline bool
45{
46 return dir == DebtDirection::Redeems;
47}
48
49inline bool
51{
52 return dir == DebtDirection::Issues;
53}
54
82class Step
83{
84public:
85 virtual ~Step() = default;
86
101 ApplyView& afView,
102 boost::container::flat_set<UInt256>& ofrsToRm,
103 EitherAmount const& out) = 0;
104
119 ApplyView& afView,
120 boost::container::flat_set<UInt256>& ofrsToRm,
121 EitherAmount const& in) = 0;
122
127 [[nodiscard]] virtual std::optional<EitherAmount>
128 cachedIn() const = 0;
129
134 [[nodiscard]] virtual std::optional<EitherAmount>
135 cachedOut() const = 0;
136
141 [[nodiscard]] virtual std::optional<AccountID>
143 {
144 return std::nullopt;
145 }
146
147 // for debugging. Return the src and dst accounts for a direct step
148 // For XRP endpoints, one of src or dst will be the root account
151 {
152 return std::nullopt;
153 }
154
163 [[nodiscard]] virtual DebtDirection
164 debtDirection(ReadView const& sb, StrandDirection dir) const = 0;
165
169 [[nodiscard]] virtual std::uint32_t
171 {
172 return QUALITY_ONE;
173 }
174
188 [[nodiscard]] virtual std::pair<std::optional<Quality>, DebtDirection>
189 qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const = 0;
190
200 getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const;
201
210 [[nodiscard]] virtual std::uint32_t
212 {
213 return 0;
214 }
215
219 [[nodiscard]] virtual std::optional<Book>
221 {
222 return std::nullopt;
223 }
224
228 [[nodiscard]] virtual bool
229 isZero(EitherAmount const& out) const = 0;
230
236 [[nodiscard]] virtual bool
237 inactive() const
238 {
239 return false;
240 }
241
245 [[nodiscard]] virtual bool
246 equalOut(EitherAmount const& lhs, EitherAmount const& rhs) const = 0;
247
251 [[nodiscard]] virtual bool
252 equalIn(EitherAmount const& lhs, EitherAmount const& rhs) const = 0;
253
265 validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) = 0;
266
274 friend bool
275 operator==(Step const& lhs, Step const& rhs)
276 {
277 return lhs.equal(rhs);
278 }
279
284 operator<<(std::ostream& stream, Step const& step)
285 {
286 stream << step.logString();
287 return stream;
288 }
289
290private:
291 [[nodiscard]] virtual std::string
292 logString() const = 0;
293
294 [[nodiscard]] virtual bool
295 equal(Step const& rhs) const = 0;
296};
297
299Step::getQualityFunc(ReadView const& v, DebtDirection prevStepDir) const
300{
301 auto const res = qualityUpperBound(v, prevStepDir);
302 if (res.first)
303 return {QualityFunction{*res.first, QualityFunction::CLOBLikeTag{}}, res.second};
304 return {std::nullopt, res.second};
305}
306
309
310inline std::uint32_t
311offersUsed(Strand const& strand)
312{
313 std::uint32_t r = 0;
314 for (auto const& step : strand)
315 {
316 if (step)
317 r += step->offersUsed();
318 }
319 return r;
320}
322
324inline bool
325operator==(Strand const& lhs, Strand const& rhs)
326{
327 if (lhs.size() != rhs.size())
328 return false;
329 for (size_t i = 0, e = lhs.size(); i != e; ++i)
330 {
331 if (*lhs[i] != *rhs[i])
332 return false;
333 }
334 return true;
335}
337
351std::pair<TER, STPath>
353 AccountID const& src,
354 AccountID const& dst,
355 Asset const& deliver,
356 std::optional<Asset> const& sendMaxAsset,
357 STPath const& path);
358
385 ReadView const& sb,
386 AccountID const& src,
387 AccountID const& dst,
388 Asset const& deliver,
389 std::optional<Quality> const& limitQuality,
390 std::optional<Asset> const& sendMaxAsset,
391 STPath const& path,
392 bool ownerPaysTransferFee,
393 OfferCrossing offerCrossing,
394 AMMContext& ammContext,
395 std::optional<UInt256> const& domainID,
397
426 ReadView const& sb,
427 AccountID const& src,
428 AccountID const& dst,
429 Asset const& deliver,
430 std::optional<Quality> const& limitQuality,
431 std::optional<Asset> const& sendMax,
432 STPathSet const& paths,
433 bool addDefaultPath,
434 bool ownerPaysTransferFee,
435 OfferCrossing offerCrossing,
436 AMMContext& ammContext,
437 std::optional<UInt256> const& domainID,
439
441template <StepAmount TIn, StepAmount TOut, class TDerived>
442struct StepImp : public Step
443{
444private:
445 explicit StepImp() = default;
446
447public:
449 rev(PaymentSandbox& sb,
450 ApplyView& afView,
451 boost::container::flat_set<UInt256>& ofrsToRm,
452 EitherAmount const& out) override
453 {
454 auto const r = static_cast<TDerived*>(this)->revImp(sb, afView, ofrsToRm, get<TOut>(out));
455 return {EitherAmount(r.first), EitherAmount(r.second)};
456 }
457
458 // Given the requested amount to consume, compute the amount produced.
459 // Return the consumed/produced
460 std::pair<EitherAmount, EitherAmount>
461 fwd(PaymentSandbox& sb,
462 ApplyView& afView,
463 boost::container::flat_set<UInt256>& ofrsToRm,
464 EitherAmount const& in) override
465 {
466 auto const r = static_cast<TDerived*>(this)->fwdImp(sb, afView, ofrsToRm, get<TIn>(in));
467 return {EitherAmount(r.first), EitherAmount(r.second)};
468 }
469
470 [[nodiscard]] bool
471 isZero(EitherAmount const& out) const override
472 {
473 return get<TOut>(out) == beast::kZero;
474 }
475
476 [[nodiscard]] bool
477 equalOut(EitherAmount const& lhs, EitherAmount const& rhs) const override
478 {
479 return get<TOut>(lhs) == get<TOut>(rhs);
480 }
481
482 [[nodiscard]] bool
483 equalIn(EitherAmount const& lhs, EitherAmount const& rhs) const override
484 {
485 return get<TIn>(lhs) == get<TIn>(rhs);
486 }
487 friend TDerived;
488};
490
492// Thrown when unexpected errors occur
493class FlowException : public std::runtime_error
494{
495public:
496 TER ter;
497
498 FlowException(TER t, std::string const& msg) : std::runtime_error(msg), ter(t)
499 {
500 }
501
502 explicit FlowException(TER t) : std::runtime_error(transHuman(t)), ter(t)
503 {
504 }
505};
507
509template <class T>
510[[nodiscard]] std::optional<T>
511checkedStepAddOpt(T const& lhs, T const& rhs)
512{
513 if constexpr (std::is_same_v<T, XRPAmount>)
514 {
515 if (auto const r = checkedAdd(lhs.drops(), rhs.drops()))
516 return XRPAmount{*r};
517 return std::nullopt;
518 }
519 else if constexpr (std::is_same_v<T, MPTAmount>)
520 {
521 if (auto const r = checkedAdd(lhs.value(), rhs.value()))
522 return MPTAmount{*r};
523 return std::nullopt;
524 }
525 else if constexpr (std::is_same_v<T, IOUAmount>)
526 {
527 // IOUAmount is Number-backed and throws on overflow.
528 return lhs + rhs;
529 }
530 else
531 {
532 // A new amount type must decide explicitly how to add; do not fall back
533 // to an unchecked add.
534 static_assert(sizeof(T) == 0, "checkedStepAddOpt: unsupported amount type");
535 }
536}
537
538template <class T>
539[[nodiscard]] T
540checkedStepAdd(T const& lhs, T const& rhs)
541{
542 if (auto const r = checkedStepAddOpt(lhs, rhs))
543 return *r;
545}
547
549// Check equal with tolerance
550bool
551checkNear(IOUAmount const& expected, IOUAmount const& actual);
552inline bool
553checkNear(MPTAmount const& expected, MPTAmount const& actual)
554{
555 return expected == actual;
556}
557inline bool
558checkNear(XRPAmount const& expected, XRPAmount const& actual)
559{
560 return expected == actual;
561}
563
568{
569 ReadView const& view;
574 bool const isFirst;
575 bool const isLast = false;
578 bool const isDefaultPath;
579 size_t const strandSize;
584 Step const* const prevStep = nullptr;
596 boost::container::flat_set<Asset>& seenBookOuts;
598 std::optional<UInt256> domainID; // the domain the order book will use
600
605 ReadView const& view,
606 std::vector<std::unique_ptr<Step>> const& strand,
607 // A strand may not include an inner node that
608 // replicates the source or destination.
609 AccountID const& strandSrc,
610 AccountID const& strandDst,
611 Asset const& strandDeliver,
613 bool isLast,
616 bool isDefaultPath,
617 std::array<boost::container::flat_set<Asset>, 2>&
619 boost::container::flat_set<Asset>& seenBookOuts,
623};
624
626namespace test {
627// Needed for testing
628bool
630 Step const& step,
631 AccountID const& src,
632 AccountID const& dst,
633 Currency const& currency);
634
635bool
637 Step const& step,
638 AccountID const& src,
639 AccountID const& dst,
640 MPTID const& mptid);
641
642bool
643xrpEndpointStepEqual(Step const& step, AccountID const& acc);
644
645bool
646bookStepEqual(Step const& step, xrpl::Book const& book);
647} // namespace test
648
651 StrandContext const& ctx,
652 AccountID const& src,
653 AccountID const& dst,
654 Currency const& c);
655
658 StrandContext const& ctx,
659 AccountID const& src,
660 AccountID const& dst,
661 MPTID const& a);
662
664makeBookStepIi(StrandContext const& ctx, Issue const& in, Issue const& out);
665
667makeBookStepIx(StrandContext const& ctx, Issue const& in);
668
670makeBookStepXi(StrandContext const& ctx, Issue const& out);
671
673makeXrpEndpointStep(StrandContext const& ctx, AccountID const& acc);
674
676makeBookStepMm(StrandContext const& ctx, MPTIssue const& in, MPTIssue const& out);
677
679makeBookStepMx(StrandContext const& ctx, MPTIssue const& in);
680
682makeBookStepXm(StrandContext const& ctx, MPTIssue const& out);
683
685makeBookStepMi(StrandContext const& ctx, MPTIssue const& in, Issue const& out);
686
688makeBookStepIm(StrandContext const& ctx, Issue const& in, MPTIssue const& out);
689
690template <StepAmount InAmt, StepAmount OutAmt>
691bool
692isDirectXrpToXrp(Strand const& strand)
693{
695 {
696 return strand.size() == 2;
697 }
698 else
699 {
700 return false;
701 }
702}
704
705} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Maintains AMM info per overall payment engine execution and individual iteration.
Definition AMMContext.h:17
Writeable view to a ledger, for applying a transaction.
Definition ApplyView.h:141
Specifies an order book.
Definition Book.h:28
Floating point representation of amounts with high dynamic range.
Definition IOUAmount.h:26
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,...
A view into a ledger.
Definition ReadView.h:41
A step in a payment path.
Definition Steps.h:83
virtual std::optional< EitherAmount > cachedIn() const =0
Amount of currency computed coming into the Step the last time the step ran in reverse.
virtual std::pair< std::optional< Quality >, DebtDirection > qualityUpperBound(ReadView const &v, DebtDirection prevStepDir) const =0
Find an upper bound of quality for the step.
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::string logString() const =0
virtual std::optional< std::pair< AccountID, AccountID > > directStepAccts() const
Definition Steps.h:150
virtual std::pair< EitherAmount, EitherAmount > rev(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, EitherAmount const &out)=0
Find the amount we need to put into the step to get the requested out subject to liquidity limits.
virtual std::uint32_t offersUsed() const
Return the number of offers consumed or partially consumed the last time the step ran,...
Definition Steps.h:211
virtual std::pair< std::optional< QualityFunction >, DebtDirection > getQualityFunc(ReadView const &v, DebtDirection prevStepDir) const
Get QualityFunction.
Definition Steps.h:299
virtual bool inactive() const
Return true if the step should be considered inactive.
Definition Steps.h:237
virtual std::pair< EitherAmount, EitherAmount > fwd(PaymentSandbox &sb, ApplyView &afView, boost::container::flat_set< UInt256 > &ofrsToRm, EitherAmount const &in)=0
Find the amount we get out of the step given the input subject to liquidity limits.
friend bool operator==(Step const &lhs, Step const &rhs)
Return true if lhs == rhs.
Definition Steps.h:275
virtual std::pair< bool, EitherAmount > validFwd(PaymentSandbox &sb, ApplyView &afView, EitherAmount const &in)=0
Check that the step can correctly execute in the forward direction.
virtual bool equalOut(EitherAmount const &lhs, EitherAmount const &rhs) const =0
Return true if Out of lhs == Out of rhs.
virtual std::optional< Book > bookStepBook() const
If this step is a BookStep, return the book.
Definition Steps.h:220
virtual DebtDirection debtDirection(ReadView const &sb, StrandDirection dir) const =0
If this step is a DirectStepI and the src redeems to the dst, return true, otherwise return false.
friend std::ostream & operator<<(std::ostream &stream, Step const &step)
Streaming operator for a Step.
Definition Steps.h:284
virtual std::uint32_t lineQualityIn(ReadView const &) const
If this step is a DirectStepI, return the quality in of the dst account.
Definition Steps.h:170
virtual bool equalIn(EitherAmount const &lhs, EitherAmount const &rhs) const =0
Return true if In of lhs == In of rhs.
virtual bool equal(Step const &rhs) const =0
virtual ~Step()=default
virtual std::optional< EitherAmount > cachedOut() const =0
Amount of currency computed coming out of the Step the last time the step ran in reverse.
virtual bool isZero(EitherAmount const &out) const =0
Check if amount is zero.
T is_same_v
constexpr Zero kZero
Definition Zero.h:30
bool bookStepEqual(Step const &step, xrpl::Book const &book)
bool xrpEndpointStepEqual(Step const &step, AccountID const &acc)
bool mptEndpointStepEqual(Step const &step, AccountID const &src, AccountID const &dst, MPTID const &mptid)
bool directStepEqual(Step const &step, AccountID const &src, AccountID const &dst, Currency const &currency)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
std::pair< TER, std::unique_ptr< Step > > makeXrpEndpointStep(StrandContext const &ctx, AccountID const &acc)
constexpr std::optional< std::int64_t > checkedAdd(std::int64_t a, std::int64_t b) noexcept
Add two signed 64-bit integers, returning std::nullopt when the exact mathematical sum is not represe...
constexpr bool operator==(BaseUInt< Bits, Tag > const &lhs, BaseUInt< Bits, Tag > const &rhs)
Definition base_uint.h:613
std::pair< TER, std::unique_ptr< Step > > makeDirectStepI(StrandContext const &ctx, AccountID const &src, AccountID const &dst, Currency const &c)
std::pair< TER, std::unique_ptr< Step > > makeBookStepIi(StrandContext const &ctx, Issue const &in, Issue const &out)
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)
bool issues(DebtDirection dir)
Definition Steps.h:50
std::pair< TER, std::unique_ptr< Step > > makeMptEndpointStep(StrandContext const &ctx, AccountID const &src, AccountID const &dst, MPTID const &mpt)
BaseUInt< 160, detail::CurrencyTag > Currency
Currency is a hash representing a specific currency.
Definition UintTypes.h:42
std::string transHuman(TER code)
Definition TER.cpp:268
std::pair< TER, std::unique_ptr< Step > > makeBookStepMi(StrandContext const &ctx, MPTIssue const &in, Issue const &out)
std::pair< TER, STPath > normalizePath(AccountID const &src, AccountID const &dst, Asset const &deliver, std::optional< Asset > const &sendMaxAsset, STPath const &path)
Normalize a path by inserting implied accounts and offers.
DebtDirection
Definition Steps.h:38
std::pair< TER, std::unique_ptr< Step > > makeBookStepIx(StrandContext const &ctx, Issue const &in)
StrandDirection
Definition Steps.h:40
@ Yes
We have consensus along with the network.
@ No
We do not have consensus.
QualityDirection
Definition Steps.h:39
std::pair< TER, std::unique_ptr< Step > > makeBookStepXm(StrandContext const &ctx, MPTIssue const &out)
std::pair< TER, std::vector< Strand > > toStrands(ReadView const &sb, AccountID const &src, AccountID const &dst, Asset const &deliver, std::optional< Quality > const &limitQuality, std::optional< Asset > const &sendMax, STPathSet const &paths, bool addDefaultPath, bool ownerPaysTransferFee, OfferCrossing offerCrossing, AMMContext &ammContext, std::optional< UInt256 > const &domainID, beast::Journal j)
Create a Strand for each specified path (including the default path, if indicated).
Definition PaySteps.cpp:574
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
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
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)
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecPATH_DRY
Definition TER.h:305
bool redeems(DebtDirection dir)
Definition Steps.h:44
OfferCrossing
Definition Steps.h:41
std::pair< TER, Strand > toStrand(ReadView const &sb, AccountID const &src, AccountID const &dst, Asset const &deliver, std::optional< Quality > const &limitQuality, std::optional< Asset > const &sendMaxAsset, STPath const &path, bool ownerPaysTransferFee, OfferCrossing offerCrossing, AMMContext &ammContext, std::optional< UInt256 > const &domainID, beast::Journal j)
Create a Strand for the specified path.
Definition PaySteps.cpp:170
std::pair< TER, std::unique_ptr< Step > > makeBookStepMm(StrandContext const &ctx, MPTIssue const &in, MPTIssue const &out)
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
beast::Journal const j
Definition Steps.h:599
Asset const strandDeliver
Asset strand delivers.
Definition Steps.h:572
AMMContext & ammContext
Definition Steps.h:597
std::optional< Quality > const limitQuality
Worst accepted quality.
Definition Steps.h:573
size_t const strandSize
Length of Strand.
Definition Steps.h:579
StrandContext(ReadView const &view, std::vector< std::unique_ptr< Step > > const &strand, AccountID const &strandSrc, AccountID const &strandDst, Asset const &strandDeliver, std::optional< Quality > const &limitQuality, bool isLast, bool ownerPaysTransferFee, OfferCrossing offerCrossing, bool isDefaultPath, std::array< boost::container::flat_set< Asset >, 2 > &seenDirectAssets, boost::container::flat_set< Asset > &seenBookOuts, AMMContext &ammContext, std::optional< UInt256 > const &domainID, beast::Journal j)
StrandContext constructor.
Definition PaySteps.cpp:686
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
bool const ownerPaysTransferFee
true if owner, not sender, pays fee
Definition Steps.h:576
bool const isLast
true if Step is last in Strand
Definition Steps.h:575
bool const isDefaultPath
true if Strand is default path
Definition Steps.h:578
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
AccountID const strandDst
Strand destination account.
Definition Steps.h:571
Step const *const prevStep
The previous step in the strand.
Definition Steps.h:584
std::optional< UInt256 > domainID
Definition Steps.h:598
OfferCrossing const offerCrossing
Yes/Sell if offer crossing, not payment.
Definition Steps.h:577