20#include <xrpld/app/ledger/OrderBookDB.h>
21#include <xrpld/app/paths/Flow.h>
22#include <xrpld/app/tx/detail/CreateOffer.h>
23#include <xrpld/ledger/PaymentSandbox.h>
24#include <xrpl/beast/utility/WrappedSink.h>
25#include <xrpl/protocol/Feature.h>
26#include <xrpl/protocol/Quality.h>
27#include <xrpl/protocol/st.h>
35 auto const& amount{tx[sfTakerGets]};
36 return amount.native() ? amount.xrp() : beast::zero;
55 JLOG(j.debug()) <<
"Malformed transaction: Invalid flags set.";
62 if (bImmediateOrCancel && bFillOrKill)
64 JLOG(j.debug()) <<
"Malformed transaction: both IoC and FoK set.";
68 bool const bHaveExpiration(tx.isFieldPresent(sfExpiration));
70 if (bHaveExpiration && (tx.getFieldU32(sfExpiration) == 0))
72 JLOG(j.debug()) <<
"Malformed offer: bad expiration";
76 if (
auto const cancelSequence = tx[~sfOfferSequence];
77 cancelSequence && *cancelSequence == 0)
79 JLOG(j.debug()) <<
"Malformed offer: bad cancel sequence";
83 STAmount saTakerPays = tx[sfTakerPays];
84 STAmount saTakerGets = tx[sfTakerGets];
91 JLOG(j.debug()) <<
"Malformed offer: redundant (XRP for XRP)";
94 if (saTakerPays <= beast::zero || saTakerGets <= beast::zero)
96 JLOG(j.debug()) <<
"Malformed offer: bad amount";
100 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
101 auto const& uPaysCurrency = saTakerPays.
getCurrency();
103 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
104 auto const& uGetsCurrency = saTakerGets.
getCurrency();
106 if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID)
108 JLOG(j.debug()) <<
"Malformed offer: redundant (IOU for IOU)";
114 JLOG(j.debug()) <<
"Malformed offer: bad currency";
118 if (saTakerPays.
native() != !uPaysIssuerID ||
119 saTakerGets.
native() != !uGetsIssuerID)
121 JLOG(j.debug()) <<
"Malformed offer: bad issuer";
131 auto const id = ctx.
tx[sfAccount];
133 auto saTakerPays = ctx.
tx[sfTakerPays];
134 auto saTakerGets = ctx.
tx[sfTakerGets];
136 auto const& uPaysIssuerID = saTakerPays.getIssuer();
137 auto const& uPaysCurrency = saTakerPays.getCurrency();
139 auto const& uGetsIssuerID = saTakerGets.getIssuer();
141 auto const cancelSequence = ctx.
tx[~sfOfferSequence];
147 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
154 JLOG(ctx.
j.
debug()) <<
"Offer involves frozen asset";
162 <<
"delay: Offers must be at least partially funded.";
168 if (cancelSequence && (uAccountSequence <= *cancelSequence))
170 JLOG(ctx.
j.
debug()) <<
"uAccountSequenceNext=" << uAccountSequence
171 <<
" uOfferSequence=" << *cancelSequence;
189 if (!saTakerPays.native())
196 Issue(uPaysCurrency, uPaysIssuerID));
215 "ripple::CreateOffer::checkAcceptAsset : input is not XRP");
222 <<
"delay: can't receive IOUs from non-existent issuer: "
237 auto const trustLine =
248 bool const canonical_gt(
id > issue.
account);
250 bool const is_authorized(
256 <<
"delay: can't receive IOUs from issuer without auth.";
268 if (offer.fully_consumed())
276 return (amount <= beast::zero);
289 have_direct || have_bridge,
290 "ripple::CreateOffer::select_path : valid inputs");
296 Quality
const bridged_quality(
303 Quality
const direct_quality(direct.
tip().
quality());
305 if (bridged_quality < direct_quality)
317 auto const crossings =
322 return crossings >= 850;
335 !
isXRP(takerAmount.in) && !
isXRP(takerAmount.out),
336 "ripple::CreateOffer::bridged_cross : neither is XRP");
338 if (
isXRP(takerAmount.in) ||
isXRP(takerAmount.out))
339 Throw<std::logic_error>(
"Bridging with XRP and an endpoint.");
370 bool have_bridge = offers_leg1.
step() && offers_leg2.
step();
378 while (have_direct || have_bridge)
380 bool leg1_consumed =
false;
381 bool leg2_consumed =
false;
382 bool direct_consumed =
false;
385 have_direct, offers_direct, have_bridge, offers_leg1, offers_leg2);
389 if (taker.
reject(quality))
398 stream << count <<
" Direct:";
399 stream <<
" offer: " << offers_direct.
tip();
400 stream <<
" in: " << offers_direct.
tip().
amount().in;
401 stream <<
" out: " << offers_direct.
tip().
amount().out;
402 stream <<
" owner: " << offers_direct.
tip().
owner();
412 cross_result = taker.
cross(offers_direct.
tip());
418 direct_consumed =
true;
440 stream << count <<
" Bridge:";
441 stream <<
" offer1: " << offers_leg1.
tip();
442 stream <<
" in: " << offers_leg1.
tip().
amount().in;
443 stream <<
" out: " << offers_leg1.
tip().
amount().out;
444 stream <<
" owner: " << offers_leg1.
tip().
owner();
445 stream <<
" funds: " << owner1_funds_before;
446 stream <<
" offer2: " << offers_leg2.
tip();
447 stream <<
" in: " << offers_leg2.
tip().
amount().in;
448 stream <<
" out: " << offers_leg2.
tip().
amount().out;
449 stream <<
" owner: " << offers_leg2.
tip().
owner();
450 stream <<
" funds: " << owner2_funds_before;
453 cross_result = taker.
cross(offers_leg1.
tip(), offers_leg2.
tip());
463 have_bridge &= offers_leg1.
step();
467 have_bridge &= offers_leg2.
step();
475 leg1_consumed =
true;
476 have_bridge = (have_bridge && offers_leg1.
step());
480 leg2_consumed =
true;
481 have_bridge = (have_bridge && offers_leg2.
step());
494 JLOG(
j_.
debug()) <<
"The taker reports he's done during crossing!";
500 JLOG(
j_.
debug()) <<
"The offer crossing limit has been exceeded!";
507 direct_consumed || leg1_consumed || leg2_consumed,
508 "ripple::CreateOffer::bridged_cross : consumed an offer");
510 if (!direct_consumed && !leg1_consumed && !leg2_consumed)
511 Throw<std::logic_error>(
512 "bridged crossing: nothing was fully consumed.");
542 bool direct_consumed =
false;
543 auto& offer(offers.tip());
546 if (taker.
reject(offer.quality()))
553 stream << count <<
" Direct:";
554 stream <<
" offer: " << offer;
555 stream <<
" in: " << offer.amount().in;
556 stream <<
" out: " << offer.amount().out;
557 stream <<
"quality: " << offer.quality();
558 stream <<
" owner: " << offer.owner();
568 cross_result = taker.
cross(offer);
574 direct_consumed =
true;
586 JLOG(
j_.
debug()) <<
"The taker reports he's done during crossing!";
592 JLOG(
j_.
debug()) <<
"The offer crossing limit has been exceeded!";
600 "ripple::CreateOffer::direct_cross : consumed an offer");
602 if (!direct_consumed)
603 Throw<std::logic_error>(
604 "direct crossing: nothing was fully consumed.");
616 while (stream.step())
618 auto const& offer = stream.tip();
621 if (taker.
reject(offer.quality()))
625 if (offer.owner() != taker.
account())
640 Amounts
const& takerAmount)
663 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
676 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
685 Amounts
const& takerAmount)
697 if (inStartBalance <= beast::zero)
700 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
707 Rate gatewayXferRate{QUALITY_ONE};
712 if (gatewayXferRate.value != QUALITY_ONE)
717 takerAmount.in.issue(),
724 Quality threshold{takerAmount.out, sendMax};
733 if (sendMax > inStartBalance)
734 sendMax = inStartBalance;
741 if (!takerAmount.in.native() && !takerAmount.out.native())
744 path.emplace_back(std::nullopt,
xrpCurrency(), std::nullopt);
764 takerAmount.out.
issue(),
770 auto const result =
flow(
785 for (
auto const& toRemove : result.removableOffers)
794 auto afterCross = takerAmount;
800 if (takerInBalance <= beast::zero)
804 afterCross.in.clear();
805 afterCross.out.clear();
810 Quality{takerAmount.out, takerAmount.in}.rate()};
822 STAmount nonGatewayAmountIn = result.actualAmountIn;
823 if (gatewayXferRate.value != QUALITY_ONE)
825 result.actualAmountIn,
827 takerAmount.in.issue(),
830 afterCross.in -= nonGatewayAmountIn;
834 if (afterCross.in < beast::zero)
837 afterCross.in.
clear();
839 afterCross.out = [&]() {
849 takerAmount.out.issue(),
853 afterCross.in, rate, takerAmount.out.issue(),
true);
861 afterCross.out -= result.actualAmountOut;
863 afterCross.out >= beast::zero,
864 "ripple::CreateOffer::flowCross : minimum offer");
865 if (afterCross.out < beast::zero)
866 afterCross.out.clear();
868 afterCross.out, rate, takerAmount.in.issue(),
true);
878 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
890 auto const ret =
flowCross(psbFlow, psbCancelFlow, takerAmount);
892 psbCancelFlow.apply(sbCancel);
897 Sandbox sbCancelTaker{&sbCancel};
898 auto const ret =
takerCross(sbTaker, sbCancelTaker, takerAmount);
900 sbCancelTaker.apply(sbCancel);
919 if (pays_xrp && !gets_xrp)
921 else if (gets_xrp && !pays_xrp)
934 bool const bPassive(uTxFlags &
tfPassive);
937 bool const bSell(uTxFlags &
tfSell);
939 auto saTakerPays =
ctx_.
tx[sfTakerPays];
940 auto saTakerGets =
ctx_.
tx[sfTakerGets];
942 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
951 auto uRate =
getRate(saTakerGets, saTakerPays);
960 auto const sleCancel =
968 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
973 auto const expiration =
ctx_.
tx[~sfExpiration];
988 bool const bOpenLedger = sb.
open();
989 bool crossed =
false;
994 auto const& uPaysIssuerID = saTakerPays.getIssuer();
995 auto const& uGetsIssuerID = saTakerGets.getIssuer();
998 if (!
isXRP(uPaysIssuerID))
1001 if (sle && sle->isFieldPresent(sfTickSize))
1002 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
1004 if (!
isXRP(uGetsIssuerID))
1007 if (sle && sle->isFieldPresent(sfTickSize))
1008 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
1010 if (uTickSize < Quality::maxTickSize)
1013 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
1021 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.issue());
1026 saTakerGets =
divide(saTakerPays, rate, saTakerGets.issue());
1028 if (!saTakerGets || !saTakerPays)
1030 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
1031 return {result,
true};
1034 uRate =
getRate(saTakerGets, saTakerPays);
1038 Amounts
const takerAmount(saTakerGets, saTakerPays);
1043 Amounts place_offer;
1045 JLOG(
j_.
debug()) <<
"Attempting cross: "
1046 <<
to_string(takerAmount.in.issue()) <<
" -> "
1051 stream <<
" mode: " << (bPassive ?
"passive " :
"")
1052 << (bSell ?
"sell" :
"buy");
1057 std::tie(result, place_offer) =
cross(sb, sbCancel, takerAmount);
1063 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
1068 stream <<
"Cross result: " <<
transToken(result);
1079 return {result,
true};
1083 saTakerGets.issue() == place_offer.in.issue(),
1084 "ripple::CreateOffer::applyGuts : taker gets issue match");
1086 saTakerPays.issue() == place_offer.out.issue(),
1087 "ripple::CreateOffer::applyGuts : taker pays issue match");
1089 if (takerAmount != place_offer)
1094 if (place_offer.in < zero || place_offer.out < zero)
1096 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
1102 if (place_offer.in == zero || place_offer.out == zero)
1104 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
1105 return {result,
true};
1111 saTakerPays = place_offer.out;
1112 saTakerGets = place_offer.in;
1116 saTakerPays > zero && saTakerGets > zero,
1117 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
1122 return {result,
true};
1127 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
1128 stream <<
" Pays: " << saTakerPays.getFullText();
1129 stream <<
" Gets: " << saTakerGets.getFullText();
1136 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
1144 if (bImmediateOrCancel)
1146 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
1147 if (!crossed && sb.
rules().
enabled(featureImmediateOfferKilled))
1177 return {result,
true};
1191 <<
"final result: failed to add offer to owner's directory";
1199 <<
" : " <<
to_string(saTakerGets.issue());
1201 Book const book{saTakerPays.issue(), saTakerGets.issue()};
1206 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
1209 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.issue().currency);
1210 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.issue().account);
1211 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.issue().currency);
1212 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.issue().account);
1213 sle->setFieldU64(sfExchangeRate, uRate);
1218 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
1222 auto sleOffer = std::make_shared<SLE>(offer_index);
1223 sleOffer->setAccountID(sfAccount,
account_);
1224 sleOffer->setFieldU32(sfSequence, offerSequence);
1225 sleOffer->setFieldH256(sfBookDirectory, dir.key);
1226 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
1227 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
1228 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
1229 sleOffer->setFieldU64(sfBookNode, *bookNode);
1231 sleOffer->setFieldU32(sfExpiration, *expiration);
1241 JLOG(
j_.
debug()) <<
"final result: success";
1258 auto const result =
applyGuts(sb, sbCancel);
1263 return result.first;
A generic endpoint for log messages.
Stream trace() const
Severity stream access functions.
Wraps a Journal::Sink to prefix its output with a string.
virtual beast::Journal journal(std::string const &name)=0
virtual OrderBookDB & getOrderBookDB()=0
Writeable view to a ledger, for applying a transaction.
std::optional< std::uint64_t > dirAppend(Keylet const &directory, Keylet const &key, std::function< void(std::shared_ptr< SLE > const &)> const &describe)
Append an entry to a directory.
std::optional< std::uint64_t > dirInsert(Keylet const &directory, uint256 const &key, std::function< void(std::shared_ptr< SLE > const &)> const &describe)
Insert an entry to a directory.
bool done() const
Returns true if order crossing should not continue.
AccountID const & account() const noexcept
Returns the account identifier of the taker.
bool reject(Quality const &quality) const noexcept
Returns true if the quality does not meet the taker's requirements.
Issue const & issue_in() const
Returns the Issue associated with the input of the offer.
Amounts remaining_offer() const
Returns the amount remaining on the offer.
Amounts const & original_offer() const
Returns the amount that the offer was originally placed at.
Issue const & issue_out() const
Returns the Issue associated with the output of the offer.
bool unfunded() const
Returns true if the taker has run out of funds.
std::pair< TER, Amounts > bridged_cross(Taker &taker, ApplyView &view, ApplyView &view_cancel, NetClock::time_point const when)
OfferStream::StepCounter stepCounter_
std::pair< TER, Amounts > flowCross(PaymentSandbox &psb, PaymentSandbox &psbCancel, Amounts const &takerAmount)
static TER checkAcceptAsset(ReadView const &view, ApplyFlags const flags, AccountID const id, beast::Journal const j, Issue const &issue)
void preCompute() override
Gather information beyond what the Transactor base class gathers.
bool dry_offer(ApplyView &view, Offer const &offer)
static TER preclaim(PreclaimContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
static bool step_account(OfferStream &stream, Taker const &taker)
static std::string format_amount(STAmount const &amount)
bool reachedOfferCrossingLimit(Taker const &taker) const
std::pair< TER, Amounts > takerCross(Sandbox &sb, Sandbox &sbCancel, Amounts const &takerAmount)
std::pair< TER, Amounts > direct_cross(Taker &taker, ApplyView &view, ApplyView &view_cancel, NetClock::time_point const when)
static NotTEC preflight(PreflightContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
static TxConsequences makeTxConsequences(PreflightContext const &ctx)
TER doApply() override
Precondition: fee collection is likely.
std::pair< TER, bool > applyGuts(Sandbox &view, Sandbox &view_cancel)
static std::pair< bool, Quality > select_path(bool have_direct, OfferStream const &direct, bool have_bridge, OfferStream const &leg1, OfferStream const &leg2)
std::pair< TER, Amounts > cross(Sandbox &sb, Sandbox &sbCancel, Amounts const &takerAmount)
A currency issued by an account.
Presents and consumes the offers in an order book.
void addOrderBook(Book const &)
A wrapper which makes credits unavailable to balances.
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
NetClock::time_point parentCloseTime() const
Returns the close time of the previous ledger.
virtual Rules const & rules() const =0
Returns the tx processing rules.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Currency const & getCurrency() const
static const std::uint64_t cMaxNative
static const int cMaxOffset
std::string getText() const override
AccountID const & getIssuer() const
Issue const & issue() const
bool native() const noexcept
static const std::uint64_t cMaxValue
STAmount const & getFieldAmount(SField const &field) const
std::uint32_t getFlags() const
void emplace_back(Args &&... args)
SeqProxy getSeqProxy() const
Discardable, editable view to a ledger.
constexpr std::uint32_t value() const
bool step()
Advance to the next valid offer.
TOffer< TIn, TOut > & tip() const
Returns the offer at the tip of the order book.
Quality quality() const noexcept
Returns the quality of the offer.
AccountID const & owner() const
Returns the account id of the offer's owner.
TAmounts< TIn, TOut > const & amount() const
Returns the in and out amounts.
std::uint32_t get_bridge_crossings() const
std::uint32_t get_direct_crossings() const
TER cross(Offer &offer)
Perform a direct or bridged offer crossing as appropriate.
virtual void preCompute()
Class describing the consequences to the account of applying a transaction if the transaction consume...
Fees const & fees() const override
Returns the fees for the base ledger.
bool open() const override
Returns true if this reflects an open ledger.
void insert(std::shared_ptr< SLE > const &sle) override
Insert a new state SLE.
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
Rules const & rules() const override
Returns the tx processing rules.
std::shared_ptr< SLE > peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
Keylet quality(Keylet const &k, std::uint64_t q) noexcept
The initial directory page for a specific quality.
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Keylet offer(AccountID const &id, std::uint32_t seq) noexcept
An offer from an account.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
STAmount divide(STAmount const &amount, Rate const &rate)
Currency const & badCurrency()
We deliberately disallow the currency that looks like "XRP" because too many people were using it ins...
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
bool isXRP(AccountID const &c)
constexpr std::uint32_t tfOfferCreateMask
STAmount divRoundStrict(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
bool isLegalNet(STAmount const &value)
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
STAmount multiply(STAmount const &amount, Rate const &rate)
std::function< void(SLE::ref)> describeOwnerDir(AccountID const &account)
constexpr std::uint32_t tfFillOrKill
NotTEC preflight1(PreflightContext const &ctx)
Performs early sanity checks on the account and fee fields.
STAmount divideRound(STAmount const &amount, Rate const &rate, bool roundUp)
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.
constexpr std::uint32_t tfPassive
constexpr std::uint32_t tfImmediateOrCancel
TER offerDelete(ApplyView &view, std::shared_ptr< SLE > const &sle, beast::Journal j)
Delete an offer.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
Quality composed_quality(Quality const &lhs, Quality const &rhs)
static bool adjustOwnerCount(ApplyContext &ctx, int count)
std::string transToken(TER code)
NotTEC preflight2(PreflightContext const &ctx)
Checks whether the signature appears valid.
Currency const & xrpCurrency()
XRP currency.
STAmount divRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
std::string to_string(base_uint< Bits, Tag > const &a)
STAmount mulRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
STAmount multiplyRound(STAmount const &amount, Rate const &rate, bool roundUp)
constexpr std::uint32_t tfSell
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp)
Determines whether the given expiration time has passed.
bool isGlobalFrozen(ReadView const &view, AccountID const &issuer)
XRPAmount accountReserve(std::size_t ownerCount) const
Returns the account reserve given the owner count, in drops.
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.
Represents a transfer rate.