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;
56 if (tx.isFlag(
tfHybrid) && !tx.isFieldPresent(sfDomainID))
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]; cancelSequence && *cancelSequence == 0)
78 JLOG(j.debug()) <<
"Malformed offer: bad cancel sequence";
82 STAmount saTakerPays = tx[sfTakerPays];
83 STAmount saTakerGets = tx[sfTakerGets];
90 JLOG(j.debug()) <<
"Malformed offer: redundant (XRP for XRP)";
93 if (saTakerPays <= beast::zero || saTakerGets <= beast::zero)
95 JLOG(j.debug()) <<
"Malformed offer: bad amount";
99 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
100 auto const& uPaysCurrency = saTakerPays.
getCurrency();
102 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
103 auto const& uGetsCurrency = saTakerGets.
getCurrency();
105 if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID)
107 JLOG(j.debug()) <<
"Malformed offer: redundant (IOU for IOU)";
113 JLOG(j.debug()) <<
"Malformed offer: bad currency";
117 if (saTakerPays.
native() != !uPaysIssuerID || saTakerGets.
native() != !uGetsIssuerID)
119 JLOG(j.debug()) <<
"Malformed offer: bad issuer";
129 auto const id = ctx.
tx[sfAccount];
131 auto saTakerPays = ctx.
tx[sfTakerPays];
132 auto saTakerGets = ctx.
tx[sfTakerGets];
134 auto const& uPaysIssuerID = saTakerPays.getIssuer();
135 auto const& uPaysCurrency = saTakerPays.getCurrency();
137 auto const& uGetsIssuerID = saTakerGets.getIssuer();
139 auto const cancelSequence = ctx.
tx[~sfOfferSequence];
145 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
151 JLOG(ctx.
j.
debug()) <<
"Offer involves frozen asset";
157 JLOG(ctx.
j.
debug()) <<
"delay: Offers must be at least partially funded.";
163 if (cancelSequence && (uAccountSequence <= *cancelSequence))
165 JLOG(ctx.
j.
debug()) <<
"uAccountSequenceNext=" << uAccountSequence <<
" uOfferSequence=" << *cancelSequence;
177 if (!saTakerPays.native())
204 XRPL_ASSERT(!
isXRP(issue.
currency),
"xrpl::CreateOffer::checkAcceptAsset : input is not XRP");
210 JLOG(j.
debug()) <<
"delay: can't receive IOUs from non-existent issuer: " <<
to_string(issue.
account);
231 bool const canonical_gt(
id > issue.
account);
237 JLOG(j.
debug()) <<
"delay: can't receive IOUs from issuer without auth.";
274 Amounts
const& takerAmount,
286 if (inStartBalance <= beast::zero)
289 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
296 Rate gatewayXferRate{QUALITY_ONE};
301 if (gatewayXferRate.value != QUALITY_ONE)
303 sendMax =
multiplyRound(takerAmount.in, gatewayXferRate, takerAmount.in.issue(),
true);
309 Quality threshold{takerAmount.out, sendMax};
318 if (sendMax > inStartBalance)
319 sendMax = inStartBalance;
326 if (!takerAmount.in.native() && !takerAmount.out.native())
352 auto const result =
flow(
368 for (
auto const& toRemove : result.removableOffers)
377 auto afterCross = takerAmount;
382 if (takerInBalance <= beast::zero)
386 afterCross.in.clear();
387 afterCross.out.clear();
391 STAmount const rate{Quality{takerAmount.out, takerAmount.in}.rate()};
403 STAmount nonGatewayAmountIn = result.actualAmountIn;
404 if (gatewayXferRate.value != QUALITY_ONE)
406 divideRound(result.actualAmountIn, gatewayXferRate, takerAmount.in.issue(),
true);
408 afterCross.in -= nonGatewayAmountIn;
412 if (afterCross.in < beast::zero)
415 afterCross.in.
clear();
417 afterCross.out =
divRoundStrict(afterCross.in, rate, takerAmount.out.issue(),
false);
424 afterCross.out -= result.actualAmountOut;
425 XRPL_ASSERT(afterCross.out >= beast::zero,
"xrpl::CreateOffer::flowCross : minimum offer");
426 if (afterCross.out < beast::zero)
427 afterCross.out.clear();
428 afterCross.in =
mulRound(afterCross.out, rate, takerAmount.in.issue(),
true);
438 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
448 txt +=
to_string(amount.issue().currency);
461 if (!sleOffer->isFieldPresent(sfDomainID))
471 bool const bookExists = sb.
exists(dir);
481 JLOG(
j_.
debug()) <<
"final result: failed to add hybrid offer to open book";
485 STArray bookArr(sfAdditionalBooks, 1);
487 bookInfo.setFieldH256(sfBookDirectory, dir.key);
488 bookInfo.setFieldU64(sfBookNode, *bookNode);
494 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
505 bool const bPassive(uTxFlags &
tfPassive);
508 bool const bSell(uTxFlags &
tfSell);
509 bool const bHybrid(uTxFlags &
tfHybrid);
511 auto saTakerPays =
ctx_.
tx[sfTakerPays];
512 auto saTakerGets =
ctx_.
tx[sfTakerGets];
513 auto const domainID =
ctx_.
tx[~sfDomainID];
515 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
524 auto uRate =
getRate(saTakerGets, saTakerPays);
540 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
545 auto const expiration =
ctx_.
tx[~sfExpiration];
554 bool const bOpenLedger = sb.
open();
555 bool crossed =
false;
560 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
561 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
564 if (!
isXRP(uPaysIssuerID))
567 if (sle && sle->isFieldPresent(sfTickSize))
568 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
570 if (!
isXRP(uGetsIssuerID))
573 if (sle && sle->isFieldPresent(sfTickSize))
574 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
576 if (uTickSize < Quality::maxTickSize)
578 auto const rate = Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
586 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
591 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
593 if (!saTakerGets || !saTakerPays)
595 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
596 return {result,
true};
599 uRate =
getRate(saTakerGets, saTakerPays);
603 Amounts
const takerAmount(saTakerGets, saTakerPays);
605 JLOG(
j_.
debug()) <<
"Attempting cross: " <<
to_string(takerAmount.in.issue()) <<
" -> "
610 stream <<
" mode: " << (bPassive ?
"passive " :
"") << (bSell ?
"sell" :
"buy");
622 std::tie(result, place_offer) =
flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
624 psbCancelFlow.apply(sbCancel);
630 "xrpl::CreateOffer::applyGuts : result is tesSUCCESS or "
635 stream <<
"Cross result: " <<
transToken(result);
646 return {result,
true};
650 saTakerGets.
issue() == place_offer.in.issue(),
"xrpl::CreateOffer::applyGuts : taker gets issue match");
652 saTakerPays.
issue() == place_offer.out.issue(),
"xrpl::CreateOffer::applyGuts : taker pays issue match");
654 if (takerAmount != place_offer)
659 if (place_offer.in < zero || place_offer.out < zero)
661 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
667 if (place_offer.in == zero || place_offer.out == zero)
669 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
670 return {result,
true};
676 saTakerPays = place_offer.out;
677 saTakerGets = place_offer.in;
681 saTakerPays > zero && saTakerGets > zero,
"xrpl::CreateOffer::applyGuts : taker pays and gets positive");
686 return {result,
true};
691 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
700 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
706 if (bImmediateOrCancel)
708 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
737 return {result,
true};
750 JLOG(
j_.
debug()) <<
"final result: failed to add offer to owner's directory";
759 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
761 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
775 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
778 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
779 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
780 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
781 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
782 sle->setFieldU64(sfExchangeRate, uRate);
784 sle->setFieldH256(sfDomainID, *maybeDomain);
789 setBookDir(sle, domainID);
795 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
801 sleOffer->setAccountID(sfAccount,
account_);
802 sleOffer->setFieldU32(sfSequence, offerSequence);
803 sleOffer->setFieldH256(sfBookDirectory, dir.key);
804 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
805 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
806 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
807 sleOffer->setFieldU64(sfBookNode, *bookNode);
809 sleOffer->setFieldU32(sfExpiration, *expiration);
815 sleOffer->setFieldH256(sfDomainID, *domainID);
820 auto const res =
applyHybrid(sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
830 JLOG(
j_.
debug()) <<
"final result: success";
847 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 > dirInsert(Keylet const &directory, uint256 const &key, std::function< void(std::shared_ptr< SLE > const &)> const &describe)
Insert an entry to a directory.
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.
static TER preclaim(PreclaimContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
TER doApply() override
Precondition: fee collection is likely.
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
static TxConsequences makeTxConsequences(PreflightContext const &ctx)
static bool checkExtraFeatures(PreflightContext const &ctx)
static std::string format_amount(STAmount const &amount)
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)
std::pair< TER, Amounts > flowCross(PaymentSandbox &psb, PaymentSandbox &psbCancel, Amounts const &takerAmount, std::optional< uint256 > const &domainID)
std::pair< TER, bool > applyGuts(Sandbox &view, Sandbox &view_cancel)
static NotTEC preflight(PreflightContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
static TER checkAcceptAsset(ReadView const &view, ApplyFlags const flags, AccountID const id, beast::Journal const j, Issue const &issue)
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.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
std::string getFullText() const override
static constexpr std::uint64_t cMaxValue
Issue const & issue() const
static int const cMaxOffset
Currency const & getCurrency() const
bool native() const noexcept
static constexpr std::uint64_t cMaxNative
AccountID const & getIssuer() const
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)
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...
bool open() const override
Returns true if this reflects an open ledger.
std::shared_ptr< SLE > peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
Fees const & fees() const override
Returns the fees for the base 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.
Keylet quality(Keylet const &k, std::uint64_t q) noexcept
The initial directory page for a specific quality.
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.
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.
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.
constexpr std::uint32_t tfSell
STAmount divide(STAmount const &amount, Rate const &rate)
constexpr std::uint32_t tfPassive
constexpr std::uint32_t tfImmediateOrCancel
constexpr std::uint32_t tfFillOrKill
bool isXRP(AccountID const &c)
std::string to_string(base_uint< Bits, Tag > const &a)
constexpr std::uint32_t tfHybrid
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp)
Determines whether the given expiration time has passed.
bool isLegalNet(STAmount const &value)
constexpr std::uint32_t tfOfferCreateMask
STAmount multiply(STAmount const &amount, Rate const &rate)
std::string transToken(TER code)
Currency const & xrpCurrency()
XRP currency.
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
bool isGlobalFrozen(ReadView const &view, AccountID const &issuer)
void adjustOwnerCount(ApplyView &view, std::shared_ptr< SLE > const &sle, std::int32_t amount, beast::Journal j)
Adjust the owner count up or down.
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.
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
STAmount multiplyRound(STAmount const &amount, Rate const &rate, bool roundUp)
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
std::function< void(SLE::ref)> describeOwnerDir(AccountID const &account)
TER offerDelete(ApplyView &view, std::shared_ptr< SLE > const &sle, beast::Journal j)
Delete an offer.
STAmount mulRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
bool isTesSuccess(TER x) noexcept
STAmount divRoundStrict(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
bool isTecClaim(TER x) noexcept
Currency const & badCurrency()
We deliberately disallow the currency that looks like "XRP" because too many people were using it ins...
STAmount divideRound(STAmount const &amount, Rate const &rate, bool roundUp)
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.