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;
184 if (!saTakerPays.native())
191 Issue(uPaysCurrency, uPaysIssuerID));
201 ctx.
view,
id, ctx.
tx[sfDomainID]))
219 "ripple::CreateOffer::checkAcceptAsset : input is not XRP");
226 <<
"delay: can't receive IOUs from non-existent issuer: "
238 auto const trustLine =
249 bool const canonical_gt(
id > issue.
account);
251 bool const is_authorized(
257 <<
"delay: can't receive IOUs from issuer without auth.";
271 auto const trustLine =
281 bool const deepFrozen =
296 Amounts
const& takerAmount,
309 if (inStartBalance <= beast::zero)
312 JLOG(
j_.
debug()) <<
"Not crossing: taker is unfunded.";
319 Rate gatewayXferRate{QUALITY_ONE};
324 if (gatewayXferRate.value != QUALITY_ONE)
329 takerAmount.in.issue(),
336 Quality threshold{takerAmount.out, sendMax};
345 if (sendMax > inStartBalance)
346 sendMax = inStartBalance;
353 if (!takerAmount.in.native() && !takerAmount.out.native())
376 takerAmount.out.
issue(),
382 auto const result =
flow(
398 for (
auto const& toRemove : result.removableOffers)
407 auto afterCross = takerAmount;
413 if (takerInBalance <= beast::zero)
417 afterCross.in.clear();
418 afterCross.out.clear();
423 Quality{takerAmount.out, takerAmount.in}.rate()};
435 STAmount nonGatewayAmountIn = result.actualAmountIn;
436 if (gatewayXferRate.value != QUALITY_ONE)
438 result.actualAmountIn,
440 takerAmount.in.issue(),
443 afterCross.in -= nonGatewayAmountIn;
447 if (afterCross.in < beast::zero)
450 afterCross.in.
clear();
453 afterCross.in, rate, takerAmount.out.issue(),
false);
460 afterCross.out -= result.actualAmountOut;
462 afterCross.out >= beast::zero,
463 "ripple::CreateOffer::flowCross : minimum offer");
464 if (afterCross.out < beast::zero)
465 afterCross.out.clear();
467 afterCross.out, rate, takerAmount.in.issue(),
true);
477 JLOG(
j_.
error()) <<
"Exception during offer crossing: " << e.
what();
500 if (!sleOffer->isFieldPresent(sfDomainID))
511 bool const bookExists = sb.
exists(dir);
522 <<
"final result: failed to add hybrid offer to open book";
526 STArray bookArr(sfAdditionalBooks, 1);
528 bookInfo.setFieldH256(sfBookDirectory, dir.key);
529 bookInfo.setFieldU64(sfBookNode, *bookNode);
535 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
546 bool const bPassive(uTxFlags &
tfPassive);
549 bool const bSell(uTxFlags &
tfSell);
550 bool const bHybrid(uTxFlags &
tfHybrid);
552 auto saTakerPays =
ctx_.
tx[sfTakerPays];
553 auto saTakerGets =
ctx_.
tx[sfTakerGets];
554 auto const domainID =
ctx_.
tx[~sfDomainID];
556 auto const cancelSequence =
ctx_.
tx[~sfOfferSequence];
565 auto uRate =
getRate(saTakerGets, saTakerPays);
574 auto const sleCancel =
582 JLOG(
j_.
debug()) <<
"Create cancels order " << *cancelSequence;
587 auto const expiration =
ctx_.
tx[~sfExpiration];
596 bool const bOpenLedger = sb.
open();
597 bool crossed =
false;
602 auto const& uPaysIssuerID = saTakerPays.
getIssuer();
603 auto const& uGetsIssuerID = saTakerGets.
getIssuer();
606 if (!
isXRP(uPaysIssuerID))
609 if (sle && sle->isFieldPresent(sfTickSize))
610 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
612 if (!
isXRP(uGetsIssuerID))
615 if (sle && sle->isFieldPresent(sfTickSize))
616 uTickSize =
std::min(uTickSize, (*sle)[sfTickSize]);
618 if (uTickSize < Quality::maxTickSize)
621 Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
629 saTakerPays =
multiply(saTakerGets, rate, saTakerPays.
issue());
634 saTakerGets =
divide(saTakerPays, rate, saTakerGets.
issue());
636 if (!saTakerGets || !saTakerPays)
638 JLOG(
j_.
debug()) <<
"Offer rounded to zero";
639 return {result,
true};
642 uRate =
getRate(saTakerGets, saTakerPays);
646 Amounts
const takerAmount(saTakerGets, saTakerPays);
648 JLOG(
j_.
debug()) <<
"Attempting cross: "
649 <<
to_string(takerAmount.in.issue()) <<
" -> "
654 stream <<
" mode: " << (bPassive ?
"passive " :
"")
655 << (bSell ?
"sell" :
"buy");
668 flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
670 psbCancelFlow.apply(sbCancel);
676 "ripple::CreateOffer::applyGuts : result is tesSUCCESS or "
681 stream <<
"Cross result: " <<
transToken(result);
692 return {result,
true};
696 saTakerGets.
issue() == place_offer.in.issue(),
697 "ripple::CreateOffer::applyGuts : taker gets issue match");
699 saTakerPays.
issue() == place_offer.out.issue(),
700 "ripple::CreateOffer::applyGuts : taker pays issue match");
702 if (takerAmount != place_offer)
707 if (place_offer.in < zero || place_offer.out < zero)
709 JLOG(
j_.
fatal()) <<
"Cross left offer negative!"
715 if (place_offer.in == zero || place_offer.out == zero)
717 JLOG(
j_.
debug()) <<
"Offer fully crossed!";
718 return {result,
true};
724 saTakerPays = place_offer.out;
725 saTakerGets = place_offer.in;
729 saTakerPays > zero && saTakerGets > zero,
730 "ripple::CreateOffer::applyGuts : taker pays and gets positive");
735 return {result,
true};
740 stream <<
"Place" << (crossed ?
" remaining " :
" ") <<
"offer:";
749 JLOG(
j_.
trace()) <<
"Fill or Kill: offer killed";
755 if (bImmediateOrCancel)
757 JLOG(
j_.
trace()) <<
"Immediate or cancel: offer canceled";
787 return {result,
true};
802 <<
"final result: failed to add offer to owner's directory";
812 << (domainID ? (
" : " +
to_string(*domainID)) :
"");
814 Book const book{saTakerPays.
issue(), saTakerGets.
issue(), domainID};
828 bool const bookExisted =
static_cast<bool>(sb.
peek(dir));
832 sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.
issue().
currency);
833 sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.
issue().
account);
834 sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.
issue().
currency);
835 sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.
issue().
account);
836 sle->setFieldU64(sfExchangeRate, uRate);
838 sle->setFieldH256(sfDomainID, *maybeDomain);
843 setBookDir(sle, domainID);
849 JLOG(
j_.
debug()) <<
"final result: failed to add offer to book";
855 sleOffer->setAccountID(sfAccount,
account_);
856 sleOffer->setFieldU32(sfSequence, offerSequence);
857 sleOffer->setFieldH256(sfBookDirectory, dir.key);
858 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
859 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
860 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
861 sleOffer->setFieldU64(sfBookNode, *bookNode);
863 sleOffer->setFieldU32(sfExpiration, *expiration);
869 sleOffer->setFieldH256(sfDomainID, *domainID);
875 sb, sleOffer, offer_index, saTakerPays, saTakerGets, setBookDir);
885 JLOG(
j_.
debug()) <<
"final result: success";
902 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.
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.
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.