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;
63 JLOG(j.debug()) <<
"Malformed transaction: Invalid flags set.";
70 if (tx.isFlag(
tfHybrid) && !tx.isFieldPresent(sfDomainID))
76 if (bImmediateOrCancel && bFillOrKill)
78 JLOG(j.debug()) <<
"Malformed transaction: both IoC and FoK set.";
82 bool const bHaveExpiration(tx.isFieldPresent(sfExpiration));
84 if (bHaveExpiration && (tx.getFieldU32(sfExpiration) == 0))
86 JLOG(j.debug()) <<
"Malformed offer: bad expiration";
90 if (
auto const cancelSequence = tx[~sfOfferSequence];
91 cancelSequence && *cancelSequence == 0)
93 JLOG(j.debug()) <<
"Malformed offer: bad cancel sequence";
97 STAmount saTakerPays = tx[sfTakerPays];
98 STAmount saTakerGets = tx[sfTakerGets];
105 JLOG(j.debug()) <<
"Malformed offer: redundant (XRP for XRP)";
108 if (saTakerPays <= beast::zero || saTakerGets <= beast::zero)
110 JLOG(j.debug()) <<
"Malformed offer: bad amount";
114 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
115 auto const& uPaysCurrency = saTakerPays.
getCurrency();
117 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
118 auto const& uGetsCurrency = saTakerGets.
getCurrency();
120 if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID)
122 JLOG(j.debug()) <<
"Malformed offer: redundant (IOU for IOU)";
128 JLOG(j.debug()) <<
"Malformed offer: bad currency";
132 if (saTakerPays.
native() != !uPaysIssuerID ||
133 saTakerGets.
native() != !uGetsIssuerID)
135 JLOG(j.debug()) <<
"Malformed offer: bad issuer";
145 auto const id = ctx.
tx[sfAccount];
147 auto saTakerPays = ctx.
tx[sfTakerPays];
148 auto saTakerGets = ctx.
tx[sfTakerGets];
150 auto const& uPaysIssuerID = saTakerPays.getIssuer();
151 auto const& uPaysCurrency = saTakerPays.getCurrency();
153 auto const& uGetsIssuerID = saTakerGets.getIssuer();
155 auto const cancelSequence = ctx.
tx[~sfOfferSequence];
161 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
168 JLOG(ctx.
j.
debug()) <<
"Offer involves frozen asset";
176 <<
"delay: Offers must be at least partially funded.";
182 if (cancelSequence && (uAccountSequence <= *cancelSequence))
184 JLOG(ctx.
j.
debug()) <<
"uAccountSequenceNext=" << uAccountSequence
185 <<
" uOfferSequence=" << *cancelSequence;
203 if (!saTakerPays.native())
210 Issue(uPaysCurrency, uPaysIssuerID));
220 ctx.
view,
id, ctx.
tx[sfDomainID]))
238 "ripple::CreateOffer::checkAcceptAsset : input is not XRP");
245 <<
"delay: can't receive IOUs from non-existent issuer: "
260 auto const trustLine =
271 bool const canonical_gt(
id > issue.
account);
273 bool const is_authorized(
279 <<
"delay: can't receive IOUs from issuer without auth.";
293 auto const trustLine =
303 bool const deepFrozen =
318 Amounts
const& takerAmount,
331 if (inStartBalance <= beast::zero)
334 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
341 Rate gatewayXferRate{QUALITY_ONE};
346 if (gatewayXferRate.value != QUALITY_ONE)
351 takerAmount.in.issue(),
358 Quality threshold{takerAmount.out, sendMax};
367 if (sendMax > inStartBalance)
368 sendMax = inStartBalance;
375 if (!takerAmount.in.native() && !takerAmount.out.native())
398 takerAmount.out.
issue(),
404 auto const result =
flow(
420 for (
auto const& toRemove : result.removableOffers)
429 auto afterCross = takerAmount;
435 if (takerInBalance <= beast::zero)
439 afterCross.in.clear();
440 afterCross.out.clear();
445 Quality{takerAmount.out, takerAmount.in}.rate()};
457 STAmount nonGatewayAmountIn = result.actualAmountIn;
458 if (gatewayXferRate.value != QUALITY_ONE)
460 result.actualAmountIn,
462 takerAmount.in.issue(),
465 afterCross.in -= nonGatewayAmountIn;
469 if (afterCross.in < beast::zero)
472 afterCross.in.
clear();
474 afterCross.out = [&]() {
484 takerAmount.out.issue(),
488 afterCross.in, rate, takerAmount.out.issue(),
true);
496 afterCross.out -= result.actualAmountOut;
498 afterCross.out >= beast::zero,
499 "ripple::CreateOffer::flowCross : minimum offer");
500 if (afterCross.out < beast::zero)
501 afterCross.out.clear();
503 afterCross.out, rate, takerAmount.in.issue(),
true);
513 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
536 if (!sleOffer->isFieldPresent(sfDomainID))
547 bool const bookExists = sb.
exists(dir);
558 <<
"final result: failed to add hybrid offer to open book";
562 STArray bookArr(sfAdditionalBooks, 1);
564 bookInfo.setFieldH256(sfBookDirectory, dir.key);
565 bookInfo.setFieldU64(sfBookNode, *bookNode);
571 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
582 bool const bPassive(uTxFlags &
tfPassive);
585 bool const bSell(uTxFlags &
tfSell);
586 bool const bHybrid(uTxFlags &
tfHybrid);
588 auto saTakerPays =
ctx_.
tx[sfTakerPays];
589 auto saTakerGets =
ctx_.
tx[sfTakerGets];
590 auto const domainID =
ctx_.
tx[~sfDomainID];
592 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
601 auto uRate =
getRate(saTakerGets, saTakerPays);
610 auto const sleCancel =
618 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
623 auto const expiration =
ctx_.
tx[~sfExpiration];
638 bool const bOpenLedger = sb.
open();
639 bool crossed =
false;
644 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
645 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
648 if (!
isXRP(uPaysIssuerID))
651 if (sle && sle->isFieldPresent(sfTickSize))
652 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
654 if (!
isXRP(uGetsIssuerID))
657 if (sle && sle->isFieldPresent(sfTickSize))
658 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
660 if (uTickSize < Quality::maxTickSize)
663 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
671 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
676 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
678 if (!saTakerGets || !saTakerPays)
680 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
681 return {result,
true};
684 uRate =
getRate(saTakerGets, saTakerPays);
688 Amounts
const takerAmount(saTakerGets, saTakerPays);
690 JLOG(
j_.
debug()) <<
"Attempting cross: "
691 <<
to_string(takerAmount.in.issue()) <<
" -> "
696 stream <<
" mode: " << (bPassive ?
"passive " :
"")
697 << (bSell ?
"sell" :
"buy");
710 flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
712 psbCancelFlow.apply(sbCancel);
718 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
723 stream <<
"Cross result: " <<
transToken(result);
734 return {result,
true};
738 saTakerGets.
issue() == place_offer.in.issue(),
739 "ripple::CreateOffer::applyGuts : taker gets issue match");
741 saTakerPays.
issue() == place_offer.out.issue(),
742 "ripple::CreateOffer::applyGuts : taker pays issue match");
744 if (takerAmount != place_offer)
749 if (place_offer.in < zero || place_offer.out < zero)
751 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
757 if (place_offer.in == zero || place_offer.out == zero)
759 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
760 return {result,
true};
766 saTakerPays = place_offer.out;
767 saTakerGets = place_offer.in;
771 saTakerPays > zero && saTakerGets > zero,
772 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
777 return {result,
true};
782 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
791 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
799 if (bImmediateOrCancel)
801 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
802 if (!crossed && sb.
rules().
enabled(featureImmediateOfferKilled))
832 return {result,
true};
846 <<
"final result: failed to add offer to owner's directory";
855 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
857 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
871 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
875 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
876 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
877 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
878 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
879 sle->setFieldU64(sfExchangeRate, uRate);
881 sle->setFieldH256(sfDomainID, *maybeDomain);
886 setBookDir(sle, domainID);
891 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
896 sleOffer->setAccountID(sfAccount,
account_);
897 sleOffer->setFieldU32(sfSequence, offerSequence);
898 sleOffer->setFieldH256(sfBookDirectory, dir.key);
899 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
900 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
901 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
902 sleOffer->setFieldU64(sfBookNode, *bookNode);
904 sleOffer->setFieldU32(sfExpiration, *expiration);
910 sleOffer->setFieldH256(sfDomainID, *domainID);
916 sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
926 JLOG(
j_.
debug()) <<
"final result: success";
943 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 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.
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
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
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
std::string transToken(TER code)
NotTEC preflight2(PreflightContext const &ctx)
Checks whether the signature appears valid.
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.