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>
25#include <xrpl/beast/utility/WrappedSink.h>
26#include <xrpl/protocol/Feature.h>
27#include <xrpl/protocol/Quality.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.";
270 auto const trustLine =
280 bool const deepFrozen =
294 if (
offer.fully_consumed())
302 return (amount <= beast::zero);
315 have_direct || have_bridge,
316 "ripple::CreateOffer::select_path : valid inputs");
322 Quality
const bridged_quality(
329 Quality
const direct_quality(direct.
tip().
quality());
331 if (bridged_quality < direct_quality)
343 auto const crossings =
348 return crossings >= 850;
361 !
isXRP(takerAmount.in) && !
isXRP(takerAmount.out),
362 "ripple::CreateOffer::bridged_cross : neither is XRP");
364 if (
isXRP(takerAmount.in) ||
isXRP(takerAmount.out))
365 Throw<std::logic_error>(
"Bridging with XRP and an endpoint.");
396 bool have_bridge = offers_leg1.
step() && offers_leg2.
step();
404 while (have_direct || have_bridge)
406 bool leg1_consumed =
false;
407 bool leg2_consumed =
false;
408 bool direct_consumed =
false;
411 have_direct, offers_direct, have_bridge, offers_leg1, offers_leg2);
415 if (taker.
reject(quality))
424 stream << count <<
" Direct:";
425 stream <<
" offer: " << offers_direct.
tip();
426 stream <<
" in: " << offers_direct.
tip().
amount().in;
427 stream <<
" out: " << offers_direct.
tip().
amount().out;
428 stream <<
" owner: " << offers_direct.
tip().
owner();
438 cross_result = taker.
cross(offers_direct.
tip());
444 direct_consumed =
true;
466 stream << count <<
" Bridge:";
467 stream <<
" offer1: " << offers_leg1.
tip();
468 stream <<
" in: " << offers_leg1.
tip().
amount().in;
469 stream <<
" out: " << offers_leg1.
tip().
amount().out;
470 stream <<
" owner: " << offers_leg1.
tip().
owner();
471 stream <<
" funds: " << owner1_funds_before;
472 stream <<
" offer2: " << offers_leg2.
tip();
473 stream <<
" in: " << offers_leg2.
tip().
amount().in;
474 stream <<
" out: " << offers_leg2.
tip().
amount().out;
475 stream <<
" owner: " << offers_leg2.
tip().
owner();
476 stream <<
" funds: " << owner2_funds_before;
479 cross_result = taker.
cross(offers_leg1.
tip(), offers_leg2.
tip());
489 have_bridge &= offers_leg1.
step();
493 have_bridge &= offers_leg2.
step();
501 leg1_consumed =
true;
502 have_bridge = (have_bridge && offers_leg1.
step());
506 leg2_consumed =
true;
507 have_bridge = (have_bridge && offers_leg2.
step());
520 JLOG(
j_.
debug()) <<
"The taker reports he's done during crossing!";
526 JLOG(
j_.
debug()) <<
"The offer crossing limit has been exceeded!";
533 direct_consumed || leg1_consumed || leg2_consumed,
534 "ripple::CreateOffer::bridged_cross : consumed an offer");
536 if (!direct_consumed && !leg1_consumed && !leg2_consumed)
537 Throw<std::logic_error>(
538 "bridged crossing: nothing was fully consumed.");
568 bool direct_consumed =
false;
579 stream << count <<
" Direct:";
580 stream <<
" offer: " <<
offer;
581 stream <<
" in: " <<
offer.amount().in;
582 stream <<
" out: " <<
offer.amount().out;
583 stream <<
"quality: " <<
offer.quality();
584 stream <<
" owner: " <<
offer.owner();
600 direct_consumed =
true;
612 JLOG(
j_.
debug()) <<
"The taker reports he's done during crossing!";
618 JLOG(
j_.
debug()) <<
"The offer crossing limit has been exceeded!";
626 "ripple::CreateOffer::direct_cross : consumed an offer");
628 if (!direct_consumed)
629 Throw<std::logic_error>(
630 "direct crossing: nothing was fully consumed.");
642 while (stream.step())
644 auto const&
offer = stream.tip();
666 Amounts
const& takerAmount)
689 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
702 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
711 Amounts
const& takerAmount)
723 if (inStartBalance <= beast::zero)
726 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
733 Rate gatewayXferRate{QUALITY_ONE};
738 if (gatewayXferRate.value != QUALITY_ONE)
743 takerAmount.in.issue(),
750 Quality threshold{takerAmount.out, sendMax};
759 if (sendMax > inStartBalance)
760 sendMax = inStartBalance;
767 if (!takerAmount.in.native() && !takerAmount.out.native())
790 takerAmount.out.
issue(),
796 auto const result =
flow(
811 for (
auto const& toRemove : result.removableOffers)
820 auto afterCross = takerAmount;
826 if (takerInBalance <= beast::zero)
830 afterCross.in.clear();
831 afterCross.out.clear();
836 Quality{takerAmount.out, takerAmount.in}.rate()};
848 STAmount nonGatewayAmountIn = result.actualAmountIn;
849 if (gatewayXferRate.value != QUALITY_ONE)
851 result.actualAmountIn,
853 takerAmount.in.issue(),
856 afterCross.in -= nonGatewayAmountIn;
860 if (afterCross.in < beast::zero)
863 afterCross.in.
clear();
865 afterCross.out = [&]() {
875 takerAmount.out.issue(),
879 afterCross.in,
rate, takerAmount.out.issue(),
true);
887 afterCross.out -= result.actualAmountOut;
889 afterCross.out >= beast::zero,
890 "ripple::CreateOffer::flowCross : minimum offer");
891 if (afterCross.out < beast::zero)
892 afterCross.out.clear();
894 afterCross.out,
rate, takerAmount.in.issue(),
true);
904 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
916 auto const ret =
flowCross(psbFlow, psbCancelFlow, takerAmount);
918 psbCancelFlow.apply(sbCancel);
923 Sandbox sbCancelTaker{&sbCancel};
924 auto const ret =
takerCross(sbTaker, sbCancelTaker, takerAmount);
926 sbCancelTaker.apply(sbCancel);
945 if (pays_xrp && !gets_xrp)
947 else if (gets_xrp && !pays_xrp)
960 bool const bPassive(uTxFlags &
tfPassive);
963 bool const bSell(uTxFlags &
tfSell);
965 auto saTakerPays =
ctx_.
tx[sfTakerPays];
966 auto saTakerGets =
ctx_.
tx[sfTakerGets];
968 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
977 auto uRate =
getRate(saTakerGets, saTakerPays);
986 auto const sleCancel =
994 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
1014 bool const bOpenLedger = sb.
open();
1015 bool crossed =
false;
1020 auto const& uPaysIssuerID = saTakerPays.getIssuer();
1021 auto const& uGetsIssuerID = saTakerGets.getIssuer();
1024 if (!
isXRP(uPaysIssuerID))
1027 if (sle && sle->isFieldPresent(sfTickSize))
1028 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
1030 if (!
isXRP(uGetsIssuerID))
1033 if (sle && sle->isFieldPresent(sfTickSize))
1034 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
1036 if (uTickSize < Quality::maxTickSize)
1039 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
1047 saTakerPays =
multiply(saTakerGets,
rate, saTakerPays.issue());
1052 saTakerGets =
divide(saTakerPays,
rate, saTakerGets.issue());
1054 if (!saTakerGets || !saTakerPays)
1056 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
1057 return {result,
true};
1060 uRate =
getRate(saTakerGets, saTakerPays);
1064 Amounts
const takerAmount(saTakerGets, saTakerPays);
1069 Amounts place_offer;
1071 JLOG(
j_.
debug()) <<
"Attempting cross: "
1072 <<
to_string(takerAmount.in.issue()) <<
" -> "
1077 stream <<
" mode: " << (bPassive ?
"passive " :
"")
1078 << (bSell ?
"sell" :
"buy");
1083 std::tie(result, place_offer) =
cross(sb, sbCancel, takerAmount);
1089 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
1094 stream <<
"Cross result: " <<
transToken(result);
1105 return {result,
true};
1109 saTakerGets.issue() == place_offer.in.issue(),
1110 "ripple::CreateOffer::applyGuts : taker gets issue match");
1112 saTakerPays.issue() == place_offer.out.issue(),
1113 "ripple::CreateOffer::applyGuts : taker pays issue match");
1115 if (takerAmount != place_offer)
1120 if (place_offer.in < zero || place_offer.out < zero)
1122 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
1128 if (place_offer.in == zero || place_offer.out == zero)
1130 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
1131 return {result,
true};
1137 saTakerPays = place_offer.out;
1138 saTakerGets = place_offer.in;
1142 saTakerPays > zero && saTakerGets > zero,
1143 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
1148 return {result,
true};
1153 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
1154 stream <<
" Pays: " << saTakerPays.getFullText();
1155 stream <<
" Gets: " << saTakerGets.getFullText();
1162 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
1170 if (bImmediateOrCancel)
1172 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
1173 if (!crossed && sb.
rules().
enabled(featureImmediateOfferKilled))
1203 return {result,
true};
1217 <<
"final result: failed to add offer to owner's directory";
1225 <<
" : " <<
to_string(saTakerGets.issue());
1227 Book const book{saTakerPays.issue(), saTakerGets.issue()};
1232 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
1235 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.issue().currency);
1236 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.issue().account);
1237 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.issue().currency);
1238 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.issue().account);
1239 sle->setFieldU64(sfExchangeRate, uRate);
1244 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
1248 auto sleOffer = std::make_shared<SLE>(offer_index);
1249 sleOffer->setAccountID(sfAccount,
account_);
1250 sleOffer->setFieldU32(sfSequence, offerSequence);
1251 sleOffer->setFieldH256(sfBookDirectory, dir.key);
1252 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
1253 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
1254 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
1255 sleOffer->setFieldU64(sfBookNode, *bookNode);
1257 sleOffer->setFieldU32(sfExpiration, *
expiration);
1267 JLOG(
j_.
debug()) <<
"final result: success";
1284 auto const result =
applyGuts(sb, sbCancel);
1289 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.
static int const cMaxOffset
Currency const & getCurrency() const
static std::uint64_t const cMaxValue
std::string getText() const override
AccountID const & getIssuer() const
Issue const & issue() const
static std::uint64_t const cMaxNative
bool native() const noexcept
STAmount const & getFieldAmount(SField const &field) const
std::uint32_t getFlags() const
std::uint32_t getSeqValue() const
Returns the first non-zero value of (Sequence, TicketSequence).
Discardable, editable view to a ledger.
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.
Set Paths, SendMax on a JTx.
Set the expected result code for a JTx The test will fail if the code doesn't match.
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.
owner_count< ltOFFER > offers
Match the number of offers in the account's owner directory.
Json::Value rate(Account const &account, double multiplier)
Set a transfer rate.
Json::Value offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
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.
bool isTesSuccess(TER x) noexcept
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 isTecClaim(TER x) noexcept
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.