xrpld
Loading...
Searching...
No Matches
OfferCreate.cpp
1#include <xrpl/tx/transactors/dex/OfferCreate.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/base_uint.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/core/ServiceRegistry.h>
8#include <xrpl/ledger/ApplyView.h>
9#include <xrpl/ledger/PaymentSandbox.h>
10#include <xrpl/ledger/Sandbox.h>
11#include <xrpl/ledger/View.h>
12#include <xrpl/ledger/helpers/AccountRootHelpers.h>
13#include <xrpl/ledger/helpers/CredentialHelpers.h>
14#include <xrpl/ledger/helpers/DirectoryHelpers.h>
15#include <xrpl/ledger/helpers/MPTokenHelpers.h>
16#include <xrpl/ledger/helpers/OfferHelpers.h>
17#include <xrpl/ledger/helpers/PermissionedDEXHelpers.h>
18#include <xrpl/ledger/helpers/TokenHelpers.h>
19#include <xrpl/protocol/AccountID.h>
20#include <xrpl/protocol/Asset.h>
21#include <xrpl/protocol/Book.h>
22#include <xrpl/protocol/Feature.h>
23#include <xrpl/protocol/Indexes.h>
24#include <xrpl/protocol/Issue.h>
25#include <xrpl/protocol/Keylet.h>
26#include <xrpl/protocol/LedgerFormats.h>
27#include <xrpl/protocol/MPTAmount.h>
28#include <xrpl/protocol/MPTIssue.h>
29#include <xrpl/protocol/Protocol.h>
30#include <xrpl/protocol/Quality.h>
31#include <xrpl/protocol/Rate.h>
32#include <xrpl/protocol/SField.h>
33#include <xrpl/protocol/STAmount.h>
34#include <xrpl/protocol/STArray.h>
35#include <xrpl/protocol/STLedgerEntry.h>
36#include <xrpl/protocol/STPathSet.h>
37#include <xrpl/protocol/STTx.h>
38#include <xrpl/protocol/SeqProxy.h>
39#include <xrpl/protocol/TER.h>
40#include <xrpl/protocol/TxFlags.h>
41#include <xrpl/protocol/UintTypes.h>
42#include <xrpl/protocol/XRPAmount.h>
43#include <xrpl/tx/Transactor.h>
44#include <xrpl/tx/applySteps.h>
45#include <xrpl/tx/paths/Flow.h>
46#include <xrpl/tx/paths/detail/Steps.h>
47
48#include <algorithm>
49#include <cstdint>
50#include <exception>
51#include <functional>
52#include <memory>
53#include <optional>
54#include <stdexcept>
55#include <tuple>
56#include <utility>
57
58namespace xrpl {
61{
62 auto const calculateMaxXRPSpend = [](STTx const& tx) -> XRPAmount {
63 auto const& amount{tx[sfTakerGets]};
64 return amount.native() ? amount.xrp() : beast::kZero;
65 };
66
67 return TxConsequences{ctx.tx, calculateMaxXRPSpend(ctx.tx)};
68}
69
70bool
72{
73 if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDEX))
74 return false;
75
76 return ctx.rules.enabled(featureMPTokensV2) ||
77 (!ctx.tx[sfTakerPays].holds<MPTIssue>() && !ctx.tx[sfTakerGets].holds<MPTIssue>());
78}
79
82{
83 // The tfOfferCreateMask is built assuming that PermissionedDEX is
84 // enabled
85 if (ctx.rules.enabled(featurePermissionedDEX))
86 return tfOfferCreateMask;
87 // If PermissionedDEX is not enabled, add tfHybrid to the mask,
88 // indicating it is not allowed.
89 return tfOfferCreateMask | tfHybrid;
90}
91
94{
95 auto& tx = ctx.tx;
96 auto& j = ctx.j;
97
98 if (tx.isFlag(tfHybrid) && !tx.isFieldPresent(sfDomainID))
99 return temINVALID_FLAG;
100
101 // A zero DomainID is invalid for a PermissionedDomain ledger entry because
102 // keylet::permissionedDomain(UInt256) uses the DomainID as the ledger key.
103 if (auto const domainID = tx[~sfDomainID];
104 ctx.rules.enabled(fixCleanup3_2_0) && domainID && *domainID == beast::kZero)
105 return temMALFORMED;
106
107 bool const bImmediateOrCancel(tx.isFlag(tfImmediateOrCancel));
108 bool const bFillOrKill(tx.isFlag(tfFillOrKill));
109
110 if (bImmediateOrCancel && bFillOrKill)
111 {
112 JLOG(j.debug()) << "Malformed transaction: both IoC and FoK set.";
113 return temINVALID_FLAG;
114 }
115
116 bool const bHaveExpiration(tx.isFieldPresent(sfExpiration));
117
118 if (bHaveExpiration && (tx.getFieldU32(sfExpiration) == 0))
119 {
120 JLOG(j.debug()) << "Malformed offer: bad expiration";
121 return temBAD_EXPIRATION;
122 }
123
124 if (auto const cancelSequence = tx[~sfOfferSequence]; cancelSequence && *cancelSequence == 0)
125 {
126 JLOG(j.debug()) << "Malformed offer: bad cancel sequence";
127 return temBAD_SEQUENCE;
128 }
129
130 STAmount const saTakerPays = tx[sfTakerPays];
131 STAmount const saTakerGets = tx[sfTakerGets];
132
133 if (!isLegalNet(saTakerPays) || !isLegalNet(saTakerGets))
134 return temBAD_AMOUNT;
135
136 if (saTakerPays.native() && saTakerGets.native())
137 {
138 JLOG(j.debug()) << "Malformed offer: redundant (XRP for XRP)";
139 return temBAD_OFFER;
140 }
141 if (saTakerPays <= beast::kZero || saTakerGets <= beast::kZero)
142 {
143 JLOG(j.debug()) << "Malformed offer: bad amount";
144 return temBAD_OFFER;
145 }
146
147 auto const& uPaysIssuerID = saTakerPays.getIssuer();
148 auto const& uPaysAsset = saTakerPays.asset();
149
150 auto const& uGetsIssuerID = saTakerGets.getIssuer();
151 auto const& uGetsAsset = saTakerGets.asset();
152
153 if (uPaysAsset == uGetsAsset)
154 {
155 JLOG(j.debug()) << "Malformed offer: redundant (IOU for IOU)";
156 return temREDUNDANT;
157 }
158 // We don't allow a non-native currency to use the currency code XRP.
159 if (badAsset() == uPaysAsset || badAsset() == uGetsAsset)
160 {
161 JLOG(j.debug()) << "Malformed offer: bad currency";
162 return temBAD_CURRENCY;
163 }
164
165 if (saTakerPays.native() != !uPaysIssuerID || saTakerGets.native() != !uGetsIssuerID)
166 {
167 JLOG(j.debug()) << "Malformed offer: bad issuer";
168 return temBAD_ISSUER;
169 }
170
171 return tesSUCCESS;
172}
173
174TER
176{
177 auto const id = ctx.tx[sfAccount];
178
179 auto const saTakerPays = ctx.tx[sfTakerPays];
180 auto const saTakerGets = ctx.tx[sfTakerGets];
181
182 auto const& uPaysAsset = saTakerPays.asset();
183
184 auto const cancelSequence = ctx.tx[~sfOfferSequence];
185
186 auto const sleCreator = ctx.view.read(keylet::account(id));
187 if (!sleCreator)
188 return terNO_ACCOUNT;
189
190 std::uint32_t const uAccountSequence = sleCreator->getFieldU32(sfSequence);
191
192 auto const viewJ = ctx.registry.get().getJournal("View");
193
194 if (auto const ter = checkGlobalFrozen(ctx.view, saTakerPays.asset()); !isTesSuccess(ter))
195 {
196 JLOG(ctx.j.debug()) << "Offer involves frozen or locked asset";
197 return ter;
198 }
199 if (auto const ter = checkGlobalFrozen(ctx.view, saTakerGets.asset()); !isTesSuccess(ter))
200 {
201 JLOG(ctx.j.debug()) << "Offer involves frozen or locked asset";
202 return ter;
203 }
204
205 // Allow unfunded MPT for issuer (OutstandingAmount >= MaximumAmount)
206 if ((!saTakerGets.holds<MPTIssue>() || saTakerGets.getIssuer() != id) &&
208 ctx.view,
209 id,
210 saTakerGets,
213 viewJ) <= beast::kZero)
214 {
215 JLOG(ctx.j.debug()) << "delay: Offers must be at least partially funded.";
216 return tecUNFUNDED_OFFER;
217 }
218
219 // This can probably be simplified to make sure that you cancel sequences
220 // before the transaction sequence number.
221 if (cancelSequence && (uAccountSequence <= *cancelSequence))
222 {
223 JLOG(ctx.j.debug()) << "uAccountSequenceNext=" << uAccountSequence
224 << " uOfferSequence=" << *cancelSequence;
225 return temBAD_SEQUENCE;
226 }
227
228 if (hasExpired(ctx.view, ctx.tx[~sfExpiration]))
229 {
230 // Note that this will get checked again in applyGuts, but it saves
231 // us a call to checkAcceptAsset and possible false negative.
232 return tecEXPIRED;
233 }
234
235 // Make sure that we are authorized to hold what the taker will pay us.
236 if (!saTakerPays.native())
237 {
238 auto result = checkAcceptAsset(ctx.view, ctx.flags, id, ctx.j, uPaysAsset);
239 if (!isTesSuccess(result))
240 return result;
241 }
242
243 // if domain is specified, make sure that domain exists and the offer create
244 // is part of the domain
245 if (ctx.tx.isFieldPresent(sfDomainID))
246 {
247 if (ctx.view.rules().enabled(fixCleanup3_4_0))
248 {
249 auto const domainID = ctx.tx[sfDomainID];
250 auto const sleDomain = ctx.view.read(keylet::permissionedDomain(domainID));
251 if (!sleDomain)
252 return tecNO_PERMISSION;
253
254 // Domain owner is always considered in the domain, no credential check
255 // needed. For all other accounts, use validDomain which detects expired
256 // credentials. Suppress tecEXPIRED here so doApply can run and delete
257 // the expired credential SLEs from the ledger.
258 if (sleDomain->getAccountID(sfOwner) != id)
259 {
260 // validDomain returns tecNO_AUTH when no matching credential is
261 // found. Map it to tecNO_PERMISSION to preserve existing behavior.
262 if (auto const err = credentials::validDomain(ctx.view, domainID, id);
263 !isTesSuccess(err) && err != tecEXPIRED)
264 return tecNO_PERMISSION;
265 }
266 }
267 else
268 {
269 if (!permissioned_dex::accountInDomain(ctx.view, id, ctx.tx[sfDomainID]))
270 return tecNO_PERMISSION;
271 }
272 }
273
274 if (auto const ter = canTrade(ctx.view, saTakerPays.asset()); !isTesSuccess(ter))
275 return ter;
276 if (auto const ter = canTrade(ctx.view, saTakerGets.asset()); !isTesSuccess(ter))
277 return ter;
278
279 return tesSUCCESS;
280}
281
282TER
284 ReadView const& view,
285 ApplyFlags const flags,
286 AccountID const id,
287 beast::Journal const j,
288 Asset const& asset)
289{
290 // Only valid for custom currencies
291 XRPL_ASSERT(!isXRP(asset), "xrpl::OfferCreate::checkAcceptAsset : input is not XRP");
292
293 auto const issuerAccount = view.read(keylet::account(asset.getIssuer()));
294
295 if (!issuerAccount)
296 {
297 JLOG(j.debug()) << "delay: can't receive IOUs from non-existent issuer: "
298 << to_string(asset.getIssuer());
299
300 return ((flags & TapRetry) != 0u) ? TER{terNO_ACCOUNT} : TER{tecNO_ISSUER};
301 }
302
303 // An account cannot create a trustline to itself, so no line can exist
304 // to be frozen. Additionally, an issuer can always accept its own
305 // issuance.
306 if (asset.getIssuer() == id)
307 return tesSUCCESS;
308
309 return asset.visit(
310 [&](Issue const& issue) -> TER {
311 auto const& issuer = issue.getIssuer();
312 auto const trustLine = view.read(keylet::trustLine(id, issuer, issue.currency));
313
314 // Check if the issuer has lsfDisallowIncomingTrustline set.
315 // If so, the account must already have a trustline to receive tokens.
316 if (view.rules().enabled(fixCleanup3_4_0) &&
317 issuerAccount->isFlag(lsfDisallowIncomingTrustline))
318 {
319 if (!trustLine)
320 {
321 JLOG(j.debug()) << "delay: can't receive IOUs from issuer with "
322 "DisallowIncomingTrustline set";
323 return ((flags & TapRetry) != 0u) ? TER{terNO_LINE} : TER{tecNO_LINE};
324 }
325 }
326
327 if (issuerAccount->isFlag(lsfRequireAuth))
328 {
329 if (!trustLine)
330 {
331 return ((flags & TapRetry) != 0u) ? TER{terNO_LINE} : TER{tecNO_LINE};
332 }
333
334 // Entries have a canonical representation, determined by a
335 // lexicographical "greater than" comparison employing
336 // strict weak ordering. Determine which entry we need to
337 // access.
338 bool const canonicalGt(id > issuer);
339
340 bool const isAuthorized(trustLine->isFlag(canonicalGt ? lsfLowAuth : lsfHighAuth));
341
342 if (!isAuthorized)
343 {
344 JLOG(j.debug()) << "delay: can't receive IOUs from "
345 "issuer without auth.";
346
347 return ((flags & TapRetry) != 0u) ? TER{terNO_AUTH} : TER{tecNO_AUTH};
348 }
349 }
350
351 if (!trustLine)
352 {
353 return tesSUCCESS;
354 }
355
356 // There's no difference which side enacted deep freeze, accepting
357 // tokens shouldn't be possible.
358 bool const deepFrozen =
359 ((*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze)) != 0u;
360
361 if (deepFrozen)
362 {
363 return tecFROZEN;
364 }
365
366 return tesSUCCESS;
367 },
368 [&](MPTIssue const& issue) -> TER {
369 // WeakAuth - don't check if MPToken exists since it's created
370 // if needed.
371 if (auto const ter = requireAuth(view, issue, id, AuthType::WeakAuth);
372 !isTesSuccess(ter))
373 {
374 return ter;
375 }
376
377 return checkFrozen(view, id, issue);
378 });
379}
380
383 PaymentSandbox& psb,
384 PaymentSandbox& psbCancel,
385 Amounts const& takerAmount,
386 std::optional<UInt256> const& domainID)
387{
388 try
389 {
390 // If the taker is unfunded before we begin crossing there's nothing
391 // to do - just return an error.
392 //
393 // We check this in preclaim, but when selling XRP charged fees can
394 // cause a user's available balance to go to 0 (by causing it to dip
395 // below the reserve) so we check this case again.
396 STAmount const inStartBalance = accountFunds(
397 psb,
399 takerAmount.in,
402 j_);
403 // Allow unfunded MPT issuer
404 auto const disallowUnfunded =
405 !inStartBalance.holds<MPTIssue>() || inStartBalance.getIssuer() != accountID_;
406 if (disallowUnfunded && inStartBalance <= beast::kZero)
407 {
408 // The account balance can't cover even part of the offer.
409 JLOG(j_.debug()) << "Not crossing: taker is unfunded.";
410 return {tecUNFUNDED_OFFER, takerAmount};
411 }
412
413 // If the gateway has a transfer rate, accommodate that. The
414 // gateway takes its cut without any special consent from the
415 // offer taker. Set sendMax to allow for the gateway's cut.
416 Rate gatewayXferRate{QUALITY_ONE};
417 STAmount sendMax = takerAmount.in;
418 // Payment flow code compares quality after the transfer rate is
419 // included, so the threshold is computed from the grossed-up input.
420 STAmount thresholdIn = sendMax;
421 if (!sendMax.native() && (accountID_ != sendMax.getIssuer()))
422 {
423 gatewayXferRate = transferRate(psb, sendMax);
424 if (gatewayXferRate.value != QUALITY_ONE)
425 {
426 try
427 {
428 sendMax = multiplyRound(
429 takerAmount.in, gatewayXferRate, takerAmount.in.asset(), true);
430 thresholdIn = sendMax;
431 }
432 catch (std::overflow_error const&)
433 {
434 // Only an MPT amount can overflow here (IOU rescales and
435 // XRP has no transfer rate), and MPT offers require
436 // featureMPTokensV2 at preflight, so this legacy re-throw
437 // is unreachable in practice.
438 // LCOV_EXCL_START
439 if (!takerAmount.in.holds<MPTIssue>() ||
440 !psb.rules().enabled(featureMPTokensV2))
441 throw;
442 // LCOV_EXCL_STOP
443
444 // The grossed-up MPT amount exceeds 2^63-1. The taker can't
445 // send more than its balance anyway. The threshold only
446 // needs the ratio, so compute it as an IOU, which can't
447 // overflow.
448 sendMax = inStartBalance;
449 thresholdIn = multiplyRound(
450 STAmount{noIssue(), takerAmount.in.mantissa()},
451 gatewayXferRate,
452 noIssue(),
453 true);
454 }
455 }
456 }
457
458 Quality threshold{takerAmount.out, thresholdIn};
459
460 // If we're creating a passive offer adjust the threshold so we only
461 // cross offers that have a better quality than this one.
462 if (ctx_.tx.isFlag(tfPassive))
463 ++threshold;
464
465 // Don't send more than our balance.
466 if (sendMax > inStartBalance)
467 sendMax = inStartBalance;
468
469 // Always invoke flow() with the default path. However if neither
470 // of the takerAmount currencies are XRP then we cross through an
471 // additional path with XRP as the intermediate between two books.
472 // This second path we have to build ourselves.
473 STPathSet paths;
474 if (!takerAmount.in.native() && !takerAmount.out.native())
475 {
476 STPath path;
477 path.emplaceBack(std::nullopt, xrpCurrency(), std::nullopt);
478 paths.emplaceBack(std::move(path));
479 }
480 // Special handling for the tfSell flag.
481 STAmount deliver = takerAmount.out;
482 auto const& deliverAsset = deliver.asset();
483 OfferCrossing offerCrossing = OfferCrossing::Yes;
484 if (ctx_.tx.isFlag(tfSell))
485 {
486 offerCrossing = OfferCrossing::Sell;
487 // We are selling, so we will accept *more* than the offer
488 // specified. Since we don't know how much they might offer,
489 // we allow delivery of the largest possible amount.
490 deliver.asset().visit(
491 [&](Issue const& issue) {
492 if (issue.native())
493 {
495 }
496 // We can't use the maximum possible currency here because
497 // there might be a gateway transfer rate to account for.
498 // Since the transfer rate cannot exceed 200%, we use 1/2
499 // maxValue for our limit.
500 else
501 {
502 deliver =
504 }
505 },
506 [&](MPTIssue const&) { deliver = STAmount{deliverAsset, kMaxMpTokenAmount / 2}; });
507 }
508
509 // Call the payment engine's flow() to do the actual work.
510 auto const result = flow(
511 psb,
512 deliver,
515 paths,
516 true, // default path
517 !ctx_.tx.isFlag(tfFillOrKill), // partial payment
518 true, // owner pays transfer fee
519 offerCrossing,
520 threshold,
521 sendMax,
522 domainID,
523 j_);
524
525 // If stale offers were found remove them.
526 for (auto const& toRemove : result.removableOffers)
527 {
528 if (auto const otr = psb.peek(keylet::offer(toRemove)))
529 offerDelete(psb, otr, j_);
530 if (auto const otr = psbCancel.peek(keylet::offer(toRemove)))
531 offerDelete(psbCancel, otr, j_);
532 }
533
534 // Determine the size of the final offer after crossing.
535 auto afterCross = takerAmount; // If !tesSUCCESS offer unchanged
536 if (isTesSuccess(result.result()))
537 {
538 STAmount const takerInBalance = accountFunds(
539 psb,
541 takerAmount.in,
544 j_);
545
546 if (disallowUnfunded && takerInBalance <= beast::kZero)
547 {
548 // If offer crossing exhausted the account's funds don't
549 // create the offer.
550 afterCross.in.clear();
551 afterCross.out.clear();
552 }
553 else
554 {
555 STAmount const rate{Quality{takerAmount.out, takerAmount.in}.rate()};
556
557 if (ctx_.tx.isFlag(tfSell))
558 {
559 // If selling then scale the new out amount based on how
560 // much we sold during crossing. This preserves the offer
561 // Quality,
562
563 // Reduce the offer that is placed by the crossed amount.
564 // Note that we must ignore the portion of the
565 // actualAmountIn that may have been consumed by a
566 // gateway's transfer rate.
567 STAmount nonGatewayAmountIn = result.actualAmountIn;
568 if (gatewayXferRate.value != QUALITY_ONE)
569 {
570 nonGatewayAmountIn = divideRound(
571 result.actualAmountIn, gatewayXferRate, takerAmount.in.asset(), true);
572 }
573
574 afterCross.in -= nonGatewayAmountIn;
575
576 // It's possible that the divRound will cause our subtract
577 // to go slightly negative. So limit afterCross.in to beast::kZero.
578 if (afterCross.in < beast::kZero)
579 {
580 // We should verify that the difference *is* small, but
581 // what is a good threshold to check?
582 afterCross.in.clear();
583 }
584
585 afterCross.out =
586 divRoundStrict(afterCross.in, rate, takerAmount.out.asset(), false);
587 }
588 else
589 {
590 // If not selling, we scale the input based on the
591 // remaining output. This too preserves the offer
592 // Quality.
593 afterCross.out -= result.actualAmountOut;
594 XRPL_ASSERT(
595 afterCross.out >= beast::kZero,
596 "xrpl::OfferCreate::flowCross : minimum offer");
597 if (afterCross.out < beast::kZero)
598 afterCross.out.clear();
599 afterCross.in = mulRound(afterCross.out, rate, takerAmount.in.asset(), true);
600 }
601 }
602 }
603
604 // Return how much of the offer is left.
605 return {tesSUCCESS, afterCross};
606 }
607 catch (std::exception const& e)
608 {
609 JLOG(j_.error()) << "Exception during offer crossing: " << e.what();
610 }
611 return {tecINTERNAL, takerAmount};
612}
613
616{
617 std::string txt = amount.getText();
618 txt += '/';
619 amount.asset().visit(
620 [&](Issue const& issue) { txt += to_string(issue.currency); },
621 [&](MPTIssue const& issue) { txt += to_string(issue); });
622 return txt;
623}
624
625TER
627 Sandbox& sb,
628 STLedgerEntry::pointer sleOffer,
629 Keylet const& offerKey,
630 STAmount const& saTakerPays,
631 STAmount const& saTakerGets,
632 std::uint64_t openRate,
633 std::function<void(SLE::Ref, std::optional<UInt256>)> const& setDir)
634{
635 if (!sleOffer->isFieldPresent(sfDomainID))
636 return tecINTERNAL; // LCOV_EXCL_LINE
637
638 // set hybrid flag
639 sleOffer->setFlag(lsfHybrid);
640
641 // if offer is hybrid, need to also place into open offer dir
642 Book const book{saTakerPays.asset(), saTakerGets.asset(), std::nullopt};
643
644 auto const dir = keylet::quality(keylet::book(book), openRate);
645 bool const bookExists = sb.exists(dir);
646
647 auto const bookNode = sb.dirAppend(dir, offerKey, [&](SLE::Ref sle) {
648 // don't set domainID on the directory object since this directory is
649 // for open book
650 setDir(sle, std::nullopt);
651 });
652
653 if (!bookNode)
654 {
655 JLOG(j_.debug()) << "final result: failed to add hybrid offer to open book";
656 return tecDIR_FULL; // LCOV_EXCL_LINE
657 }
658
659 STArray bookArr(sfAdditionalBooks, 1);
660 auto bookInfo = STObject::makeInnerObject(sfBook);
661 bookInfo.setFieldH256(sfBookDirectory, dir.key);
662 bookInfo.setFieldU64(sfBookNode, *bookNode);
663 bookArr.pushBack(std::move(bookInfo));
664
665 if (!bookExists)
666 ctx_.addOrderBook(book);
667
668 sleOffer->setFieldArray(sfAdditionalBooks, bookArr);
669 return tesSUCCESS;
670}
671
674{
675 using beast::kZero;
676
677 bool const bPassive(ctx_.tx.isFlag(tfPassive));
678 bool const bImmediateOrCancel(ctx_.tx.isFlag(tfImmediateOrCancel));
679 bool const bFillOrKill(ctx_.tx.isFlag(tfFillOrKill));
680 bool const bSell(ctx_.tx.isFlag(tfSell));
681 bool const bHybrid(ctx_.tx.isFlag(tfHybrid));
682
683 auto saTakerPays = ctx_.tx[sfTakerPays];
684 auto saTakerGets = ctx_.tx[sfTakerGets];
685 auto const domainID = ctx_.tx[~sfDomainID];
686
687 auto const cancelSequence = ctx_.tx[~sfOfferSequence];
688
689 // Note that we use the value from the sequence or ticket as the
690 // offer sequence. For more explanation see comments in SeqProxy.h.
691 auto const offerSequence = ctx_.tx.getSeqProxy();
692
693 // This is the original rate of the offer, and is the rate at which
694 // it will be placed, even if crossing offers change the amounts that
695 // end up on the books.
696 auto uRate = getRate(saTakerGets, saTakerPays);
697
698 auto const viewJ = ctx_.registry.get().getJournal("View");
699
700 TER result = tesSUCCESS;
701
702 // Process a cancellation request that's passed along with an offer.
703 if (cancelSequence)
704 {
705 auto const seqProxy = SeqProxy::rawSequence(*cancelSequence);
706 auto const sleCancel = sb.peek(keylet::offer(accountID_, seqProxy));
707
708 // It's not an error to not find the offer to cancel: it might have
709 // been consumed or removed. If it is found, however, it's an error
710 // to fail to delete it.
711 if (sleCancel)
712 {
713 JLOG(j_.debug()) << "Create cancels order " << *cancelSequence;
714 result = offerDelete(sb, sleCancel, viewJ);
715 }
716 }
717
718 auto const expiration = ctx_.tx[~sfExpiration];
719
720 if (hasExpired(sb, expiration))
721 {
722 // If the offer has expired, the transaction has successfully
723 // done nothing, so short circuit from here.
724 return {tecEXPIRED, true};
725 }
726
727 bool crossed = false;
728 bool const mptV2 = ctx_.view().rules().enabled(featureMPTokensV2);
729
730 if (isTesSuccess(result))
731 {
732 // If a tick size applies, round the offer to the tick size
733 auto const& uPaysIssuerID = saTakerPays.getIssuer();
734 auto const& uGetsIssuerID = saTakerGets.getIssuer();
735
737 // Not XRP or MPT
738 if (!saTakerPays.integral())
739 {
740 auto const sle = sb.read(keylet::account(uPaysIssuerID));
741 if (sle && sle->isFieldPresent(sfTickSize))
742 uTickSize = std::min(uTickSize, (*sle)[sfTickSize]);
743 }
744 // Not XRP or MPT
745 if (!saTakerGets.integral())
746 {
747 auto const sle = sb.read(keylet::account(uGetsIssuerID));
748 if (sle && sle->isFieldPresent(sfTickSize))
749 uTickSize = std::min(uTickSize, (*sle)[sfTickSize]);
750 }
751 // Quality's ctor is the same getRate() call that produced uRate, and
752 // round() maps zero to zero, so an unrepresentable quality would make
753 // divide() below throw (tefEXCEPTION). Skip the rounding instead: the
754 // offer still crosses, and any residual is stopped before placement.
755 bool const unrepresentableRate = mptV2 && uRate == 0;
756 if (uTickSize < Quality::kMaxTickSize && !unrepresentableRate)
757 {
758 auto const rate = Quality{saTakerGets, saTakerPays}.round(uTickSize).rate();
759
760 // We round the side that's not exact,
761 // just as if the offer happened to execute
762 // at a slightly better (for the placer) rate
763 if (bSell)
764 {
765 // this is a sell, round taker pays
766 if (!saTakerPays.holds<MPTIssue>())
767 saTakerPays = multiply(saTakerGets, rate, saTakerPays.asset());
768 }
769 else if (!saTakerGets.holds<MPTIssue>())
770 {
771 // this is a buy, round taker gets
772 saTakerGets = divide(saTakerPays, rate, saTakerGets.asset());
773 }
774 if (!saTakerGets || !saTakerPays)
775 {
776 JLOG(j_.debug()) << "Offer rounded to zero";
777 return {result, true};
778 }
779
780 uRate = getRate(saTakerGets, saTakerPays);
781 }
782
783 // We reverse pays and gets because during crossing we are taking.
784 Amounts const takerAmount(saTakerGets, saTakerPays);
785
786 JLOG(j_.debug()) << "Attempting cross: " << to_string(takerAmount.in.asset()) << " -> "
787 << to_string(takerAmount.out.asset());
788
789 if (auto const stream = j_.trace())
790 {
791 stream << " mode: " << (bPassive ? "passive " : "") << (bSell ? "sell" : "buy");
792 stream << " in: " << formatAmount(takerAmount.in);
793 stream << " out: " << formatAmount(takerAmount.out);
794 }
795
796 // The amount of the offer that is unfilled after crossing has been
797 // performed. It may be equal to the original amount (didn't cross),
798 // empty (fully crossed), or something in-between.
799 Amounts placeOffer;
800 PaymentSandbox psbFlow{&sb};
801 PaymentSandbox psbCancelFlow{&sbCancel};
802
803 std::tie(result, placeOffer) = flowCross(psbFlow, psbCancelFlow, takerAmount, domainID);
804 psbFlow.apply(sb);
805 psbCancelFlow.apply(sbCancel);
806
807 // We expect the implementation of cross to succeed
808 // or give a tec.
809 XRPL_ASSERT(
810 isTesSuccess(result) || isTecClaim(result),
811 "xrpl::OfferCreate::applyGuts : result is tesSUCCESS or "
812 "tecCLAIM");
813
814 if (auto const stream = j_.trace())
815 {
816 stream << "Cross result: " << transToken(result);
817 stream << " in: " << formatAmount(placeOffer.in);
818 stream << " out: " << formatAmount(placeOffer.out);
819 }
820
821 if (result == tecFAILED_PROCESSING && sb.open())
822 result = telFAILED_PROCESSING;
823
824 if (!isTesSuccess(result))
825 {
826 JLOG(j_.debug()) << "final result: " << transToken(result);
827 return {result, true};
828 }
829
830 XRPL_ASSERT(
831 saTakerGets.asset() == placeOffer.in.asset(),
832 "xrpl::OfferCreate::applyGuts : taker gets issue match");
833 XRPL_ASSERT(
834 saTakerPays.asset() == placeOffer.out.asset(),
835 "xrpl::OfferCreate::applyGuts : taker pays issue match");
836
837 if (takerAmount != placeOffer)
838 crossed = true;
839
840 // The offer that we need to place after offer crossing should
841 // never be negative. If it is, something went very very wrong.
842 if (placeOffer.in < kZero || placeOffer.out < kZero)
843 {
844 JLOG(j_.fatal()) << "Cross left offer negative!"
845 << " in: " << formatAmount(placeOffer.in)
846 << " out: " << formatAmount(placeOffer.out);
847 return {tefINTERNAL, true};
848 }
849
850 if (placeOffer.in == kZero || placeOffer.out == kZero)
851 {
852 JLOG(j_.debug()) << "Offer fully crossed!";
853 return {result, true};
854 }
855
856 // We now need to adjust the offer to reflect the amount left after
857 // crossing. We reverse in and out here, since during crossing we
858 // were the taker.
859 saTakerPays = placeOffer.out;
860 saTakerGets = placeOffer.in;
861 }
862
863 XRPL_ASSERT(
864 saTakerPays > beast::kZero && saTakerGets > beast::kZero,
865 "xrpl::OfferCreate::applyGuts : taker pays and gets positive");
866
867 if (!isTesSuccess(result))
868 {
869 JLOG(j_.debug()) << "final result: " << transToken(result);
870 return {result, true};
871 }
872
873 if (auto const stream = j_.trace())
874 {
875 stream << "Place" << (crossed ? " remaining " : " ") << "offer:";
876 stream << " Pays: " << saTakerPays.getFullText();
877 stream << " Gets: " << saTakerGets.getFullText();
878 }
879
880 // For 'fill or kill' offers, failure to fully cross means that the
881 // entire operation should be aborted, with only fees paid.
882 if (bFillOrKill)
883 {
884 JLOG(j_.trace()) << "Fill or Kill: offer killed";
885 return {tecKILLED, false};
886 }
887
888 // For 'immediate or cancel' offers, the amount remaining doesn't get
889 // placed - it gets canceled and the operation succeeds.
890 if (bImmediateOrCancel)
891 {
892 JLOG(j_.trace()) << "Immediate or cancel: offer canceled";
893 if (!crossed)
894 {
895 // Any ImmediateOrCancel offer that transfers absolutely no funds
896 // returns tecKILLED rather than tesSUCCESS. Motivation for the
897 // change is here: https://github.com/XRPLF/rippled/issues/4115
898 return {tecKILLED, false};
899 }
900 return {tesSUCCESS, true};
901 }
902
903 // A taker redeeming an MPT into this offer pays the transfer fee, and
904 // BookStep grosses up TakerPays by the rate before anything else. If that
905 // doesn't fit in an MPT amount, every fee-paying taker overflows and
906 // BookStep removes the offer on the first attempt (the issuer pays no fee,
907 // but its send is bounded by what it can still issue). Conservative for a
908 // bid above MaximumAmount, which BookStep grosses up only to the cap.
909 // Checked on the remainder: it may fit even if the original amount didn't.
910 bool cannotRest = false;
911 if (mptV2 && saTakerPays.holds<MPTIssue>())
912 {
913 auto const rate = transferRate(sb, saTakerPays);
914 cannotRest = rate != kParityRate &&
915 !tryMulRatio(saTakerPays.mpt(), rate.value, QUALITY_ONE, /*roundUp*/ true);
916 }
917
918 // The remainder rests at uRate, the original pre-crossing rate. A zero
919 // rate (quality not representable) puts it in the directory whose index
920 // equals getBookBase(book), and BookTip scans keys strictly greater, so it
921 // could never be crossed while holding the owner's reserve. Likewise, a
922 // bid whose fee-grossed TakerPays doesn't fit would be removed by BookStep
923 // on the first take. Don't place it; anything that crossed is kept, and a
924 // fully crossed offer has already returned above. Gated to preserve
925 // pre-amendment behavior.
926 if ((mptV2 && uRate == 0) || cannotRest)
927 {
928 JLOG(j_.debug()) << "Unrepresentable quality or fee: remainder not placed";
929 if (!crossed)
930 return {tecKILLED, false};
931 return {tesSUCCESS, true};
932 }
933
934 auto const sleCreator = sb.peek(keylet::account(accountID_));
935 if (!sleCreator)
936 return {tefINTERNAL, false};
937
938 {
939 XRPAmount const reserve = accountReserve(sb, sleCreator, viewJ, {.ownerCountDelta = 1});
940 if (preFeeBalance_ < reserve)
941 {
942 // If we are here, the signing account had an insufficient reserve
943 // *prior* to our processing. If something actually crossed, then
944 // we allow this; otherwise, we just claim a fee.
945 if (!crossed)
946 result = tecINSUF_RESERVE_OFFER;
947
948 if (!isTesSuccess(result))
949 {
950 JLOG(j_.debug()) << "final result: " << transToken(result);
951 }
952
953 return {result, true};
954 }
955 }
956
957 // We need to place the remainder of the offer into its order book.
958 auto const offerIndex = keylet::offer(accountID_, offerSequence);
959
960 // Add offer to owner's directory.
961 auto const ownerNode =
963
964 if (!ownerNode)
965 {
966 // LCOV_EXCL_START
967 JLOG(j_.debug()) << "final result: failed to add offer to owner's directory";
968 return {tecDIR_FULL, true};
969 // LCOV_EXCL_STOP
970 }
971
972 // Update owner count.
973 increaseOwnerCount(sb, sleCreator, {}, 1, viewJ);
974
975 JLOG(j_.trace()) << "adding to book: " << to_string(saTakerPays.asset()) << " : "
976 << to_string(saTakerGets.asset())
977 << (domainID ? (" : " + to_string(*domainID)) : "");
978
979 Book const book{saTakerPays.asset(), saTakerGets.asset(), domainID};
980
981 // Add offer to order book, using the original rate
982 // before any crossing occurred.
983 //
984 // Regular offer - BookDirectory points to open directory
985 //
986 // Domain offer (w/o hybrid) - BookDirectory points to domain
987 // directory
988 //
989 // Hybrid domain offer - BookDirectory points to domain directory,
990 // and AdditionalBooks field stores one entry that points to the open
991 // directory
992 auto const dir = keylet::quality(keylet::book(book), uRate);
993 bool const bookExisted = static_cast<bool>(sb.peek(dir));
994
995 auto setBookDir = [&](SLE::Ref sle, std::optional<UInt256> const& maybeDomain) {
996 saTakerPays.asset().visit(
997 [&](Issue const& issue) {
998 sle->setFieldH160(sfTakerPaysCurrency, issue.currency);
999 sle->setFieldH160(sfTakerPaysIssuer, issue.account);
1000 },
1001 [&](MPTIssue const& issue) { sle->setFieldH192(sfTakerPaysMPT, issue.getMptID()); });
1002 saTakerGets.asset().visit(
1003 [&](Issue const& issue) {
1004 sle->setFieldH160(sfTakerGetsCurrency, issue.currency);
1005 sle->setFieldH160(sfTakerGetsIssuer, issue.account);
1006 },
1007 [&](MPTIssue const& issue) { sle->setFieldH192(sfTakerGetsMPT, issue.getMptID()); });
1008 sle->setFieldU64(sfExchangeRate, uRate);
1009 if (maybeDomain)
1010 sle->setFieldH256(sfDomainID, *maybeDomain);
1011 };
1012
1013 auto const bookNode = sb.dirAppend(dir, offerIndex, [&](SLE::Ref sle) {
1014 // sets domainID on book directory if it's a domain offer
1015 setBookDir(sle, domainID);
1016 });
1017
1018 if (!bookNode)
1019 {
1020 // LCOV_EXCL_START
1021 JLOG(j_.debug()) << "final result: failed to add offer to book";
1022 return {tecDIR_FULL, true};
1023 // LCOV_EXCL_STOP
1024 }
1025
1026 auto const sleOffer = std::make_shared<SLE>(offerIndex);
1027 sleOffer->setAccountID(sfAccount, accountID_);
1028 sleOffer->setFieldU32(sfSequence, offerSequence.value());
1029 sleOffer->setFieldH256(sfBookDirectory, dir.key);
1030 sleOffer->setFieldAmount(sfTakerPays, saTakerPays);
1031 sleOffer->setFieldAmount(sfTakerGets, saTakerGets);
1032 sleOffer->setFieldU64(sfOwnerNode, *ownerNode);
1033 sleOffer->setFieldU64(sfBookNode, *bookNode);
1034 if (expiration)
1035 sleOffer->setFieldU32(sfExpiration, *expiration);
1036 if (bPassive)
1037 sleOffer->setFlag(lsfPassive);
1038 if (bSell)
1039 sleOffer->setFlag(lsfSell);
1040 if (domainID)
1041 sleOffer->setFieldH256(sfDomainID, *domainID);
1042
1043 // if it's a hybrid offer, set hybrid flag, and create an open dir
1044 if (bHybrid)
1045 {
1046 // Pre-fixCleanup3_2_0: the open-book directory quality was computed
1047 // from post-crossing amounts, which may differ from the original rate
1048 // due to rounding in rate preservation. Post-fixCleanup3_2_0: use the
1049 // original placement rate so the open-book directory quality matches
1050 // the domain-book directory.
1051 auto const openRate = ctx_.view().rules().enabled(fixCleanup3_2_0)
1052 ? uRate
1053 : getRate(saTakerGets, saTakerPays);
1054 auto const res =
1055 applyHybrid(sb, sleOffer, offerIndex, saTakerPays, saTakerGets, openRate, setBookDir);
1056 if (!isTesSuccess(res))
1057 return {res, true}; // LCOV_EXCL_LINE
1058 }
1059
1060 sb.insert(sleOffer);
1061
1062 if (!bookExisted)
1063 ctx_.addOrderBook(book);
1064
1065 JLOG(j_.debug()) << "final result: success";
1066
1067 return {tesSUCCESS, true};
1068}
1069
1070TER
1072{
1073 // If a DomainID is present, verify the account is still in the domain and
1074 // delete any expired credential SLEs. This must happen before the Sandboxes
1075 // are created: if we return a tec error, the engine applies sbCancel (not
1076 // sb) to rawView, so deletions made inside sb would be lost. Deletions made
1077 // directly to ctx_.view() here are preserved regardless of which branch
1078 // applyGuts takes.
1079 if (ctx_.tx.isFieldPresent(sfDomainID) && ctx_.view().rules().enabled(fixCleanup3_4_0))
1080 {
1081 auto const domainID = ctx_.tx[sfDomainID];
1082 auto const sleDomain = ctx_.view().read(keylet::permissionedDomain(domainID));
1083 if (!sleDomain)
1084 return tecINTERNAL; // LCOV_EXCL_LINE
1085
1086 if (sleDomain->getAccountID(sfOwner) != accountID_)
1087 {
1088 if (auto const err = verifyValidDomain(ctx_.view(), accountID_, domainID, j_);
1089 !isTesSuccess(err))
1090 return err;
1091 }
1092 }
1093
1094 // This is the ledger view that we work against. Transactions are applied
1095 // as we go on processing transactions.
1096 Sandbox sb(&ctx_.view());
1097
1098 // This is a ledger with just the fees paid and any unfunded or expired
1099 // offers we encounter removed. It's used when handling Fill-or-Kill offers,
1100 // if the order isn't going to be placed, to avoid wasting the work we did.
1101 Sandbox sbCancel(&ctx_.view());
1102
1103 auto const result = applyGuts(sb, sbCancel);
1104 if (result.second)
1105 {
1106 sb.apply(ctx_.rawView());
1107 }
1108 else
1109 {
1110 sbCancel.apply(ctx_.rawView());
1111 }
1112 return result.first;
1113}
1114
1115void
1117{
1118 // No transaction-specific invariants yet (future work).
1119}
1120
1121bool
1123{
1124 // No transaction-specific invariants yet (future work).
1125 return true;
1126}
1127
1128} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
std::optional< std::uint64_t > dirInsert(Keylet const &directory, UInt256 const &key, std::function< void(SLE::Ref)> const &describe)
Insert an entry to a directory.
Definition ApplyView.h:373
std::optional< std::uint64_t > dirAppend(Keylet const &directory, Keylet const &key, std::function< void(SLE::Ref)> const &describe)
Append an entry to a directory.
Definition ApplyView.h:333
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
Definition Asset.h:117
AccountID const & getIssuer() const
Definition Asset.cpp:21
Specifies an order book.
Definition Book.h:28
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
AccountID account
Definition Issue.h:21
bool native() const
Definition Issue.cpp:54
AccountID const & getIssuer() const
Definition Issue.h:30
AccountID const & getIssuer() const
Definition MPTIssue.cpp:29
static TER preclaim(PreclaimContext 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, Asset const &asset)
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
TER doApply() override
Precondition: fee collection is likely.
static TxConsequences makeTxConsequences(PreflightContext const &ctx)
static bool checkExtraFeatures(PreflightContext const &ctx)
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
static NotTEC preflight(PreflightContext const &ctx)
Enforce constraints beyond those of the Transactor base class.
std::pair< TER, bool > applyGuts(Sandbox &view, Sandbox &viewCancel)
std::pair< TER, Amounts > flowCross(PaymentSandbox &psb, PaymentSandbox &psbCancel, Amounts const &takerAmount, std::optional< UInt256 > const &domainID)
static std::string formatAmount(STAmount const &amount)
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
TER applyHybrid(Sandbox &sb, STLedgerEntry::pointer sleOffer, Keylet const &offerIndex, STAmount const &saTakerPays, STAmount const &saTakerGets, std::uint64_t openRate, std::function< void(SLE::Ref, std::optional< UInt256 >)> const &setDir)
A wrapper which makes credits unavailable to balances.
void apply(RawView &to)
Apply changes to base view.
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
static int const kMaxTickSize
Definition Quality.h:97
STAmount rate() const
Returns the quality as STAmount.
Definition Quality.h:162
Quality round(int tickSize) const
Returns the quality rounded up to the specified number of decimal digits.
Definition Quality.cpp:171
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual SLE::const_pointer 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.
Definition Rules.cpp:182
constexpr bool holds() const noexcept
Definition STAmount.h:478
std::string getFullText() const override
std::uint64_t mantissa() const noexcept
Definition STAmount.h:490
std::string getText() const override
bool integral() const noexcept
Definition STAmount.h:465
bool native() const noexcept
Definition STAmount.h:471
Asset const & asset() const
Definition STAmount.h:496
AccountID const & getIssuer() const
Definition STAmount.h:516
static constexpr std::uint64_t kMaxValue
Definition STAmount.h:67
static constexpr std::uint64_t kMaxNative
Definition STAmount.h:69
static constexpr int kMaxOffset
Definition STAmount.h:62
void pushBack(STObject const &object)
Definition STArray.h:212
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry > const & Ref
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:79
bool emplaceBack(Args &&... args)
emplaceBack adds a path to the set.
Definition STPathSet.h:676
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
AccountID const accountID_
Definition Transactor.h:166
XRPAmount preFeeBalance_
Definition Transactor.h:167
ApplyContext & ctx_
Definition Transactor.h:162
Class describing the consequences to the account of applying a transaction if the transaction consume...
Definition applySteps.h:53
void insert(SLE::Ref sle) override
Insert a new state SLE.
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
bool open() const override
Returns true if this reflects an open ledger.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
Rules const & rules() const override
Returns the tx processing rules.
bool exists(Keylet const &k) const override
Determine if a state item exists.
T make_shared(T... args)
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
TER validDomain(ReadView const &view, UInt256 domainID, AccountID const &subject)
Keylet quality(Keylet const &k, std::uint64_t const q) noexcept
The initial directory page for a specific quality.
Definition Indexes.cpp:316
Keylet offer(AccountID const &id, SeqProxy const &seq) noexcept
An offer from an account.
Definition Indexes.cpp:310
Keylet book(Book const &b)
The beginning of an order book.
Definition Indexes.cpp:281
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet permissionedDomain(AccountID const &account, SeqProxy const &seq) noexcept
Definition Indexes.cpp:583
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
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.
Definition algorithm.h:5
@ telFAILED_PROCESSING
Definition TER.h:42
STAmount divide(STAmount const &amount, Rate const &rate)
Definition Rate2.cpp:69
@ terNO_LINE
Definition TER.h:221
@ terNO_AUTH
Definition TER.h:220
@ terNO_ACCOUNT
Definition TER.h:219
TER offerDelete(ApplyView &view, SLE::Ref sle, beast::Journal j)
Delete an offer.
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp, ExpiryComparison comparison=ExpiryComparison::Inclusive)
Determines whether the given expiration time has passed.
Definition View.cpp:52
bool isXRP(AccountID const &c)
Definition AccountID.h:84
TAmounts< STAmount, STAmount > Amounts
Definition Quality.h:69
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
@ tefINTERNAL
Definition TER.h:167
bool isLegalNet(STAmount const &value)
Definition STAmount.h:616
void increaseOwnerCount(ApplyView &view, SLE::Ref accountSle, SLE::Ref sponsorSle, std::uint32_t count, beast::Journal j)
Increase owner-count fields when the caller supplies the sponsor.
std::string transToken(TER code)
Definition TER.cpp:259
Currency const & xrpCurrency()
XRP currency.
Definition UintTypes.cpp:99
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
TER canTrade(ReadView const &view, Asset const &asset, std::uint8_t depth=0)
Check whether asset may be traded on the DEX.
std::optional< MPTAmount > tryMulRatio(MPTAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Definition MPTAmount.h:179
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
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.
Definition StrandFlow.h:101
Rate transferRate(ReadView const &view, AccountID const &issuer)
Returns IOU issuer transfer fee as Rate.
TER verifyValidDomain(ApplyView &view, AccountID const &account, UInt256 domainID, beast::Journal j)
STAmount multiplyRound(STAmount const &amount, Rate const &rate, bool roundUp)
Definition Rate2.cpp:45
Rate const kParityRate
A transfer rate signifying a 1:1 exchange.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
TER checkGlobalFrozen(ReadView const &view, Asset const &asset)
ApplyFlags
Definition ApplyView.h:27
@ TapRetry
Definition ApplyView.h:36
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
STAmount mulRound(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
@ temBAD_ISSUER
Definition TER.h:81
@ temBAD_CURRENCY
Definition TER.h:78
@ temBAD_EXPIRATION
Definition TER.h:79
@ temBAD_SEQUENCE
Definition TER.h:92
@ temINVALID_FLAG
Definition TER.h:99
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
@ temBAD_OFFER
Definition TER.h:83
@ temREDUNDANT
Definition TER.h:100
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
STAmount divRoundStrict(STAmount const &v1, STAmount const &v2, Asset const &asset, bool roundUp)
TERSubset< CanCvtToTER > TER
Definition TER.h:657
XRPAmount accountReserve(ReadView const &view, SLE::ConstRef sle, beast::Journal j, Adjustment adj={})
Returns the account reserve, in drops.
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:118
@ tecINSUF_RESERVE_OFFER
Definition TER.h:300
@ tecDIR_FULL
Definition TER.h:298
@ tecNO_AUTH
Definition TER.h:311
@ tecINTERNAL
Definition TER.h:321
@ tecFAILED_PROCESSING
Definition TER.h:297
@ tecFROZEN
Definition TER.h:314
@ tecUNFUNDED_OFFER
Definition TER.h:295
@ tecEXPIRED
Definition TER.h:325
@ tecNO_LINE
Definition TER.h:312
@ tecKILLED
Definition TER.h:327
@ tecNO_PERMISSION
Definition TER.h:316
@ tecNO_ISSUER
Definition TER.h:310
STAmount multiply(STAmount const &amount, Number const &frac, Number::RoundingMode rm)
bool isTecClaim(TER x) noexcept
Definition TER.h:693
BadAsset const & badAsset()
Definition Asset.h:40
OfferCrossing
Definition Steps.h:41
std::function< void(SLE::Ref)> describeOwnerDir(AccountID const &account)
Returns a function that sets the owner on a directory SLE.
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
STAmount divideRound(STAmount const &amount, Rate const &rate, bool roundUp)
Definition Rate2.cpp:80
@ tesSUCCESS
Definition TER.h:253
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
std::reference_wrapper< ServiceRegistry > registry
Definition Transactor.h:94
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46
Represents a transfer rate.
Definition Rate.h:21
std::uint32_t value
Definition Rate.h:22
T tie(T... args)
T what(T... args)