20#include <xrpld/app/ledger/OrderBookDB.h>
21#include <xrpld/app/misc/PermissionedDEXHelpers.h>
22#include <xrpld/app/paths/Flow.h>
23#include <xrpld/app/tx/detail/CreateOffer.h>
25#include <xrpl/basics/base_uint.h>
26#include <xrpl/beast/utility/WrappedSink.h>
27#include <xrpl/ledger/PaymentSandbox.h>
28#include <xrpl/protocol/Feature.h>
29#include <xrpl/protocol/STAmount.h>
30#include <xrpl/protocol/TER.h>
31#include <xrpl/protocol/TxFlags.h>
32#include <xrpl/protocol/st.h>
39 auto const& amount{tx[sfTakerGets]};
40 return amount.native() ? amount.xrp() : beast::zero;
76 if (tx.isFlag(
tfHybrid) && !tx.isFieldPresent(sfDomainID))
82 if (bImmediateOrCancel && bFillOrKill)
84 JLOG(j.debug()) <<
"Malformed transaction: both IoC and FoK set.";
88 bool const bHaveExpiration(tx.isFieldPresent(sfExpiration));
90 if (bHaveExpiration && (tx.getFieldU32(sfExpiration) == 0))
92 JLOG(j.debug()) <<
"Malformed offer: bad expiration";
96 if (
auto const cancelSequence = tx[~sfOfferSequence];
97 cancelSequence && *cancelSequence == 0)
99 JLOG(j.debug()) <<
"Malformed offer: bad cancel sequence";
103 STAmount saTakerPays = tx[sfTakerPays];
104 STAmount saTakerGets = tx[sfTakerGets];
111 JLOG(j.debug()) <<
"Malformed offer: redundant (XRP for XRP)";
114 if (saTakerPays <= beast::zero || saTakerGets <= beast::zero)
116 JLOG(j.debug()) <<
"Malformed offer: bad amount";
120 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
121 auto const& uPaysCurrency = saTakerPays.
getCurrency();
123 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
124 auto const& uGetsCurrency = saTakerGets.
getCurrency();
126 if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID)
128 JLOG(j.debug()) <<
"Malformed offer: redundant (IOU for IOU)";
134 JLOG(j.debug()) <<
"Malformed offer: bad currency";
138 if (saTakerPays.
native() != !uPaysIssuerID ||
139 saTakerGets.
native() != !uGetsIssuerID)
141 JLOG(j.debug()) <<
"Malformed offer: bad issuer";
151 auto const id = ctx.
tx[sfAccount];
153 auto saTakerPays = ctx.
tx[sfTakerPays];
154 auto saTakerGets = ctx.
tx[sfTakerGets];
156 auto const& uPaysIssuerID = saTakerPays.getIssuer();
157 auto const& uPaysCurrency = saTakerPays.getCurrency();
159 auto const& uGetsIssuerID = saTakerGets.getIssuer();
161 auto const cancelSequence = ctx.
tx[~sfOfferSequence];
167 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
174 JLOG(ctx.
j.
debug()) <<
"Offer involves frozen asset";
182 <<
"delay: Offers must be at least partially funded.";
188 if (cancelSequence && (uAccountSequence <= *cancelSequence))
190 JLOG(ctx.
j.
debug()) <<
"uAccountSequenceNext=" << uAccountSequence
191 <<
" uOfferSequence=" << *cancelSequence;
209 if (!saTakerPays.native())
216 Issue(uPaysCurrency, uPaysIssuerID));
226 ctx.
view,
id, ctx.
tx[sfDomainID]))
244 "ripple::CreateOffer::checkAcceptAsset : input is not XRP");
251 <<
"delay: can't receive IOUs from non-existent issuer: "
266 auto const trustLine =
277 bool const canonical_gt(
id > issue.
account);
279 bool const is_authorized(
285 <<
"delay: can't receive IOUs from issuer without auth.";
299 auto const trustLine =
309 bool const deepFrozen =
324 Amounts
const& takerAmount,
337 if (inStartBalance <= beast::zero)
340 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
347 Rate gatewayXferRate{QUALITY_ONE};
352 if (gatewayXferRate.value != QUALITY_ONE)
357 takerAmount.in.issue(),
364 Quality threshold{takerAmount.out, sendMax};
373 if (sendMax > inStartBalance)
374 sendMax = inStartBalance;
381 if (!takerAmount.in.native() && !takerAmount.out.native())
404 takerAmount.out.
issue(),
410 auto const result =
flow(
426 for (
auto const& toRemove : result.removableOffers)
435 auto afterCross = takerAmount;
441 if (takerInBalance <= beast::zero)
445 afterCross.in.clear();
446 afterCross.out.clear();
451 Quality{takerAmount.out, takerAmount.in}.rate()};
463 STAmount nonGatewayAmountIn = result.actualAmountIn;
464 if (gatewayXferRate.value != QUALITY_ONE)
466 result.actualAmountIn,
468 takerAmount.in.issue(),
471 afterCross.in -= nonGatewayAmountIn;
475 if (afterCross.in < beast::zero)
478 afterCross.in.
clear();
481 afterCross.in, rate, takerAmount.out.issue(),
false);
488 afterCross.out -= result.actualAmountOut;
490 afterCross.out >= beast::zero,
491 "ripple::CreateOffer::flowCross : minimum offer");
492 if (afterCross.out < beast::zero)
493 afterCross.out.clear();
495 afterCross.out, rate, takerAmount.in.issue(),
true);
505 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
528 if (!sleOffer->isFieldPresent(sfDomainID))
539 bool const bookExists = sb.
exists(dir);
550 <<
"final result: failed to add hybrid offer to open book";
554 STArray bookArr(sfAdditionalBooks, 1);
556 bookInfo.setFieldH256(sfBookDirectory, dir.key);
557 bookInfo.setFieldU64(sfBookNode, *bookNode);
563 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
574 bool const bPassive(uTxFlags &
tfPassive);
577 bool const bSell(uTxFlags &
tfSell);
578 bool const bHybrid(uTxFlags &
tfHybrid);
580 auto saTakerPays =
ctx_.
tx[sfTakerPays];
581 auto saTakerGets =
ctx_.
tx[sfTakerGets];
582 auto const domainID =
ctx_.
tx[~sfDomainID];
584 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
593 auto uRate =
getRate(saTakerGets, saTakerPays);
602 auto const sleCancel =
610 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
615 auto const expiration =
ctx_.
tx[~sfExpiration];
630 bool const bOpenLedger = sb.
open();
631 bool crossed =
false;
636 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
637 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
640 if (!
isXRP(uPaysIssuerID))
643 if (sle && sle->isFieldPresent(sfTickSize))
644 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
646 if (!
isXRP(uGetsIssuerID))
649 if (sle && sle->isFieldPresent(sfTickSize))
650 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
652 if (uTickSize < Quality::maxTickSize)
655 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
663 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
668 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
670 if (!saTakerGets || !saTakerPays)
672 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
673 return {result,
true};
676 uRate =
getRate(saTakerGets, saTakerPays);
680 Amounts
const takerAmount(saTakerGets, saTakerPays);
682 JLOG(
j_.
debug()) <<
"Attempting cross: "
683 <<
to_string(takerAmount.in.issue()) <<
" -> "
688 stream <<
" mode: " << (bPassive ?
"passive " :
"")
689 << (bSell ?
"sell" :
"buy");
702 flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
704 psbCancelFlow.apply(sbCancel);
710 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
715 stream <<
"Cross result: " <<
transToken(result);
726 return {result,
true};
730 saTakerGets.
issue() == place_offer.in.issue(),
731 "ripple::CreateOffer::applyGuts : taker gets issue match");
733 saTakerPays.
issue() == place_offer.out.issue(),
734 "ripple::CreateOffer::applyGuts : taker pays issue match");
736 if (takerAmount != place_offer)
741 if (place_offer.in < zero || place_offer.out < zero)
743 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
749 if (place_offer.in == zero || place_offer.out == zero)
751 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
752 return {result,
true};
758 saTakerPays = place_offer.out;
759 saTakerGets = place_offer.in;
763 saTakerPays > zero && saTakerGets > zero,
764 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
769 return {result,
true};
774 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
783 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
789 if (bImmediateOrCancel)
791 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
792 if (!crossed && sb.
rules().
enabled(featureImmediateOfferKilled))
822 return {result,
true};
837 <<
"final result: failed to add offer to owner's directory";
847 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
849 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
863 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
867 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
868 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
869 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
870 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
871 sle->setFieldU64(sfExchangeRate, uRate);
873 sle->setFieldH256(sfDomainID, *maybeDomain);
878 setBookDir(sle, domainID);
884 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
890 sleOffer->setAccountID(sfAccount,
account_);
891 sleOffer->setFieldU32(sfSequence, offerSequence);
892 sleOffer->setFieldH256(sfBookDirectory, dir.key);
893 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
894 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
895 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
896 sleOffer->setFieldU64(sfBookNode, *bookNode);
898 sleOffer->setFieldU32(sfExpiration, *expiration);
904 sleOffer->setFieldH256(sfDomainID, *domainID);
910 sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
920 JLOG(
j_.
debug()) <<
"final result: success";
937 auto const result =
applyGuts(sb, sbCancel);
A generic endpoint for log messages.
Stream trace() const
Severity stream access functions.
virtual beast::Journal journal(std::string const &name)=0
virtual OrderBookDB & getOrderBookDB()=0
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.
std::pair< TER, Amounts > flowCross(PaymentSandbox &psb, PaymentSandbox &psbCancel, Amounts const &takerAmount, std::optional< uint256 > const &domainID)
static TER checkAcceptAsset(ReadView const &view, ApplyFlags const flags, AccountID const id, beast::Journal const j, Issue const &issue)
static TER preclaim(PreclaimContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
static std::string format_amount(STAmount const &amount)
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
static NotTEC preflight(PreflightContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
static TxConsequences makeTxConsequences(PreflightContext const &ctx)
TER applyHybrid(Sandbox &sb, std::shared_ptr< STLedgerEntry > sleOffer, Keylet const &offer_index, STAmount const &saTakerPays, STAmount const &saTakerGets, std::function< void(SLE::ref, std::optional< uint256 >)> const &setDir)
TER doApply() override
Precondition: fee collection is likely.
static bool checkExtraFeatures(PreflightContext const &ctx)
std::pair< TER, bool > applyGuts(Sandbox &view, Sandbox &view_cancel)
A currency issued by an account.
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.
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
std::string getFullText() const override
bool native() const noexcept
void push_back(STObject const &object)
bool isFieldPresent(SField const &field) const
static STObject makeInnerObject(SField const &name)
std::uint32_t getFlags() const
void emplace_back(Args &&... args)
std::uint32_t getSeqValue() const
Returns the first non-zero value of (Sequence, TicketSequence).
Discardable, editable view to a ledger.
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.
bool exists(Keylet const &k) const override
Determine if a state item exists.
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.
bool accountInDomain(ReadView const &view, AccountID const &account, Domain const &domainID)
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
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)
void adjustOwnerCount(ApplyView &view, std::shared_ptr< SLE > const &sle, std::int32_t amount, beast::Journal j)
Adjust the owner count up or down.
constexpr std::uint32_t tfHybrid
STAmount multiply(STAmount const &amount, Rate const &rate)
std::function< void(SLE::ref)> describeOwnerDir(AccountID const &account)
constexpr std::uint32_t tfFillOrKill
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
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
std::string transToken(TER code)
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp)
Determines whether the given expiration time has passed.
Currency const & xrpCurrency()
XRP currency.
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
bool isTesSuccess(TER x) noexcept
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 isTecClaim(TER x) noexcept
TER offerDelete(ApplyView &view, std::shared_ptr< SLE > const &sle, beast::Journal j)
Delete an offer.
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.
A pair of SHAMap key and LedgerEntryType.
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.
Represents a transfer rate.