1#include <xrpld/app/ledger/OrderBookDB.h>
2#include <xrpld/app/misc/PermissionedDEXHelpers.h>
3#include <xrpld/app/paths/Flow.h>
4#include <xrpld/app/tx/detail/CreateOffer.h>
6#include <xrpl/basics/base_uint.h>
7#include <xrpl/beast/utility/WrappedSink.h>
8#include <xrpl/ledger/PaymentSandbox.h>
9#include <xrpl/protocol/Feature.h>
10#include <xrpl/protocol/STAmount.h>
11#include <xrpl/protocol/TER.h>
12#include <xrpl/protocol/TxFlags.h>
13#include <xrpl/protocol/st.h>
20 auto const& amount{tx[sfTakerGets]};
21 return amount.native() ? amount.xrp() : beast::zero;
57 if (tx.isFlag(
tfHybrid) && !tx.isFieldPresent(sfDomainID))
63 if (bImmediateOrCancel && bFillOrKill)
65 JLOG(j.debug()) <<
"Malformed transaction: both IoC and FoK set.";
69 bool const bHaveExpiration(tx.isFieldPresent(sfExpiration));
71 if (bHaveExpiration && (tx.getFieldU32(sfExpiration) == 0))
73 JLOG(j.debug()) <<
"Malformed offer: bad expiration";
77 if (
auto const cancelSequence = tx[~sfOfferSequence];
78 cancelSequence && *cancelSequence == 0)
80 JLOG(j.debug()) <<
"Malformed offer: bad cancel sequence";
84 STAmount saTakerPays = tx[sfTakerPays];
85 STAmount saTakerGets = tx[sfTakerGets];
92 JLOG(j.debug()) <<
"Malformed offer: redundant (XRP for XRP)";
95 if (saTakerPays <= beast::zero || saTakerGets <= beast::zero)
97 JLOG(j.debug()) <<
"Malformed offer: bad amount";
101 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
102 auto const& uPaysCurrency = saTakerPays.
getCurrency();
104 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
105 auto const& uGetsCurrency = saTakerGets.
getCurrency();
107 if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID)
109 JLOG(j.debug()) <<
"Malformed offer: redundant (IOU for IOU)";
115 JLOG(j.debug()) <<
"Malformed offer: bad currency";
119 if (saTakerPays.
native() != !uPaysIssuerID ||
120 saTakerGets.
native() != !uGetsIssuerID)
122 JLOG(j.debug()) <<
"Malformed offer: bad issuer";
132 auto const id = ctx.
tx[sfAccount];
134 auto saTakerPays = ctx.
tx[sfTakerPays];
135 auto saTakerGets = ctx.
tx[sfTakerGets];
137 auto const& uPaysIssuerID = saTakerPays.getIssuer();
138 auto const& uPaysCurrency = saTakerPays.getCurrency();
140 auto const& uGetsIssuerID = saTakerGets.getIssuer();
142 auto const cancelSequence = ctx.
tx[~sfOfferSequence];
148 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
155 JLOG(ctx.
j.
debug()) <<
"Offer involves frozen asset";
163 <<
"delay: Offers must be at least partially funded.";
169 if (cancelSequence && (uAccountSequence <= *cancelSequence))
171 JLOG(ctx.
j.
debug()) <<
"uAccountSequenceNext=" << uAccountSequence
172 <<
" uOfferSequence=" << *cancelSequence;
190 if (!saTakerPays.native())
197 Issue(uPaysCurrency, uPaysIssuerID));
207 ctx.
view,
id, ctx.
tx[sfDomainID]))
225 "ripple::CreateOffer::checkAcceptAsset : input is not XRP");
232 <<
"delay: can't receive IOUs from non-existent issuer: "
247 auto const trustLine =
258 bool const canonical_gt(
id > issue.
account);
260 bool const is_authorized(
266 <<
"delay: can't receive IOUs from issuer without auth.";
280 auto const trustLine =
290 bool const deepFrozen =
305 Amounts
const& takerAmount,
318 if (inStartBalance <= beast::zero)
321 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
328 Rate gatewayXferRate{QUALITY_ONE};
333 if (gatewayXferRate.value != QUALITY_ONE)
338 takerAmount.in.issue(),
345 Quality threshold{takerAmount.out, sendMax};
354 if (sendMax > inStartBalance)
355 sendMax = inStartBalance;
362 if (!takerAmount.in.native() && !takerAmount.out.native())
385 takerAmount.out.
issue(),
391 auto const result =
flow(
407 for (
auto const& toRemove : result.removableOffers)
416 auto afterCross = takerAmount;
422 if (takerInBalance <= beast::zero)
426 afterCross.in.clear();
427 afterCross.out.clear();
432 Quality{takerAmount.out, takerAmount.in}.rate()};
444 STAmount nonGatewayAmountIn = result.actualAmountIn;
445 if (gatewayXferRate.value != QUALITY_ONE)
447 result.actualAmountIn,
449 takerAmount.in.issue(),
452 afterCross.in -= nonGatewayAmountIn;
456 if (afterCross.in < beast::zero)
459 afterCross.in.
clear();
462 afterCross.in, rate, takerAmount.out.issue(),
false);
469 afterCross.out -= result.actualAmountOut;
471 afterCross.out >= beast::zero,
472 "ripple::CreateOffer::flowCross : minimum offer");
473 if (afterCross.out < beast::zero)
474 afterCross.out.clear();
476 afterCross.out, rate, takerAmount.in.issue(),
true);
486 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
509 if (!sleOffer->isFieldPresent(sfDomainID))
520 bool const bookExists = sb.
exists(dir);
531 <<
"final result: failed to add hybrid offer to open book";
535 STArray bookArr(sfAdditionalBooks, 1);
537 bookInfo.setFieldH256(sfBookDirectory, dir.key);
538 bookInfo.setFieldU64(sfBookNode, *bookNode);
544 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
555 bool const bPassive(uTxFlags &
tfPassive);
558 bool const bSell(uTxFlags &
tfSell);
559 bool const bHybrid(uTxFlags &
tfHybrid);
561 auto saTakerPays =
ctx_.
tx[sfTakerPays];
562 auto saTakerGets =
ctx_.
tx[sfTakerGets];
563 auto const domainID =
ctx_.
tx[~sfDomainID];
565 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
574 auto uRate =
getRate(saTakerGets, saTakerPays);
583 auto const sleCancel =
591 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
596 auto const expiration =
ctx_.
tx[~sfExpiration];
611 bool const bOpenLedger = sb.
open();
612 bool crossed =
false;
617 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
618 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
621 if (!
isXRP(uPaysIssuerID))
624 if (sle && sle->isFieldPresent(sfTickSize))
625 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
627 if (!
isXRP(uGetsIssuerID))
630 if (sle && sle->isFieldPresent(sfTickSize))
631 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
633 if (uTickSize < Quality::maxTickSize)
636 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
644 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
649 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
651 if (!saTakerGets || !saTakerPays)
653 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
654 return {result,
true};
657 uRate =
getRate(saTakerGets, saTakerPays);
661 Amounts
const takerAmount(saTakerGets, saTakerPays);
663 JLOG(
j_.
debug()) <<
"Attempting cross: "
664 <<
to_string(takerAmount.in.issue()) <<
" -> "
669 stream <<
" mode: " << (bPassive ?
"passive " :
"")
670 << (bSell ?
"sell" :
"buy");
683 flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
685 psbCancelFlow.apply(sbCancel);
691 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
696 stream <<
"Cross result: " <<
transToken(result);
707 return {result,
true};
711 saTakerGets.
issue() == place_offer.in.issue(),
712 "ripple::CreateOffer::applyGuts : taker gets issue match");
714 saTakerPays.
issue() == place_offer.out.issue(),
715 "ripple::CreateOffer::applyGuts : taker pays issue match");
717 if (takerAmount != place_offer)
722 if (place_offer.in < zero || place_offer.out < zero)
724 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
730 if (place_offer.in == zero || place_offer.out == zero)
732 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
733 return {result,
true};
739 saTakerPays = place_offer.out;
740 saTakerGets = place_offer.in;
744 saTakerPays > zero && saTakerGets > zero,
745 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
750 return {result,
true};
755 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
764 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
770 if (bImmediateOrCancel)
772 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
802 return {result,
true};
817 <<
"final result: failed to add offer to owner's directory";
827 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
829 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
843 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
847 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
848 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
849 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
850 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
851 sle->setFieldU64(sfExchangeRate, uRate);
853 sle->setFieldH256(sfDomainID, *maybeDomain);
858 setBookDir(sle, domainID);
864 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
870 sleOffer->setAccountID(sfAccount,
account_);
871 sleOffer->setFieldU32(sfSequence, offerSequence);
872 sleOffer->setFieldH256(sfBookDirectory, dir.key);
873 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
874 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
875 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
876 sleOffer->setFieldU64(sfBookNode, *bookNode);
878 sleOffer->setFieldU32(sfExpiration, *expiration);
884 sleOffer->setFieldH256(sfDomainID, *domainID);
890 sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
900 JLOG(
j_.
debug()) <<
"final result: success";
917 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.