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();
480 afterCross.out = [&]() {
490 takerAmount.out.issue(),
494 afterCross.in, rate, takerAmount.out.issue(),
true);
502 afterCross.out -= result.actualAmountOut;
504 afterCross.out >= beast::zero,
505 "ripple::CreateOffer::flowCross : minimum offer");
506 if (afterCross.out < beast::zero)
507 afterCross.out.clear();
509 afterCross.out, rate, takerAmount.in.issue(),
true);
519 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
542 if (!sleOffer->isFieldPresent(sfDomainID))
553 bool const bookExists = sb.
exists(dir);
564 <<
"final result: failed to add hybrid offer to open book";
568 STArray bookArr(sfAdditionalBooks, 1);
570 bookInfo.setFieldH256(sfBookDirectory, dir.key);
571 bookInfo.setFieldU64(sfBookNode, *bookNode);
577 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
588 bool const bPassive(uTxFlags &
tfPassive);
591 bool const bSell(uTxFlags &
tfSell);
592 bool const bHybrid(uTxFlags &
tfHybrid);
594 auto saTakerPays =
ctx_.
tx[sfTakerPays];
595 auto saTakerGets =
ctx_.
tx[sfTakerGets];
596 auto const domainID =
ctx_.
tx[~sfDomainID];
598 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
607 auto uRate =
getRate(saTakerGets, saTakerPays);
616 auto const sleCancel =
624 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
629 auto const expiration =
ctx_.
tx[~sfExpiration];
644 bool const bOpenLedger = sb.
open();
645 bool crossed =
false;
650 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
651 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
654 if (!
isXRP(uPaysIssuerID))
657 if (sle && sle->isFieldPresent(sfTickSize))
658 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
660 if (!
isXRP(uGetsIssuerID))
663 if (sle && sle->isFieldPresent(sfTickSize))
664 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
666 if (uTickSize < Quality::maxTickSize)
669 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
677 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
682 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
684 if (!saTakerGets || !saTakerPays)
686 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
687 return {result,
true};
690 uRate =
getRate(saTakerGets, saTakerPays);
694 Amounts
const takerAmount(saTakerGets, saTakerPays);
696 JLOG(
j_.
debug()) <<
"Attempting cross: "
697 <<
to_string(takerAmount.in.issue()) <<
" -> "
702 stream <<
" mode: " << (bPassive ?
"passive " :
"")
703 << (bSell ?
"sell" :
"buy");
716 flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
718 psbCancelFlow.apply(sbCancel);
724 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
729 stream <<
"Cross result: " <<
transToken(result);
740 return {result,
true};
744 saTakerGets.
issue() == place_offer.in.issue(),
745 "ripple::CreateOffer::applyGuts : taker gets issue match");
747 saTakerPays.
issue() == place_offer.out.issue(),
748 "ripple::CreateOffer::applyGuts : taker pays issue match");
750 if (takerAmount != place_offer)
755 if (place_offer.in < zero || place_offer.out < zero)
757 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
763 if (place_offer.in == zero || place_offer.out == zero)
765 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
766 return {result,
true};
772 saTakerPays = place_offer.out;
773 saTakerGets = place_offer.in;
777 saTakerPays > zero && saTakerGets > zero,
778 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
783 return {result,
true};
788 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
797 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
805 if (bImmediateOrCancel)
807 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
808 if (!crossed && sb.
rules().
enabled(featureImmediateOfferKilled))
838 return {result,
true};
853 <<
"final result: failed to add offer to owner's directory";
863 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
865 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
879 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
883 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
884 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
885 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
886 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
887 sle->setFieldU64(sfExchangeRate, uRate);
889 sle->setFieldH256(sfDomainID, *maybeDomain);
894 setBookDir(sle, domainID);
900 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
906 sleOffer->setAccountID(sfAccount,
account_);
907 sleOffer->setFieldU32(sfSequence, offerSequence);
908 sleOffer->setFieldH256(sfBookDirectory, dir.key);
909 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
910 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
911 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
912 sleOffer->setFieldU64(sfBookNode, *bookNode);
914 sleOffer->setFieldU32(sfExpiration, *expiration);
920 sleOffer->setFieldH256(sfDomainID, *domainID);
926 sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
936 JLOG(
j_.
debug()) <<
"final result: success";
953 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
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 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.