xrpld
Loading...
Searching...
No Matches
Payment.cpp
1#include <xrpl/tx/transactors/payment/Payment.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/beast/utility/Zero.h>
5#include <xrpl/beast/utility/instrumentation.h>
6#include <xrpl/core/ServiceRegistry.h>
7#include <xrpl/ledger/PaymentSandbox.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/helpers/AccountRootHelpers.h>
10#include <xrpl/ledger/helpers/CredentialHelpers.h>
11#include <xrpl/ledger/helpers/MPTokenHelpers.h>
12#include <xrpl/ledger/helpers/PermissionedDEXHelpers.h>
13#include <xrpl/ledger/helpers/SponsorHelpers.h>
14#include <xrpl/ledger/helpers/TokenHelpers.h>
15#include <xrpl/protocol/AccountID.h>
16#include <xrpl/protocol/Asset.h>
17#include <xrpl/protocol/Feature.h>
18#include <xrpl/protocol/Indexes.h>
19#include <xrpl/protocol/Issue.h>
20#include <xrpl/protocol/LedgerFormats.h>
21#include <xrpl/protocol/MPTAmount.h>
22#include <xrpl/protocol/MPTIssue.h>
23#include <xrpl/protocol/Permissions.h>
24#include <xrpl/protocol/Quality.h>
25#include <xrpl/protocol/Rate.h>
26#include <xrpl/protocol/SField.h>
27#include <xrpl/protocol/STAmount.h>
28#include <xrpl/protocol/STLedgerEntry.h>
29#include <xrpl/protocol/STPathSet.h>
30#include <xrpl/protocol/STTx.h>
31#include <xrpl/protocol/TER.h>
32#include <xrpl/protocol/TxFlags.h>
33#include <xrpl/protocol/UintTypes.h>
34#include <xrpl/protocol/XRPAmount.h>
35#include <xrpl/protocol/jss.h>
36#include <xrpl/tx/Transactor.h>
37#include <xrpl/tx/applySteps.h>
38#include <xrpl/tx/paths/RippleCalc.h>
39
40#include <algorithm>
41#include <cstdint>
42#include <limits>
43#include <memory>
44#include <optional>
45#include <unordered_set>
46
47namespace xrpl {
48
51{
52 auto const calculateMaxXRPSpend = [](STTx const& tx) -> XRPAmount {
53 STAmount const maxAmount = tx.isFieldPresent(sfSendMax) ? tx[sfSendMax] : tx[sfAmount];
54
55 // If there's no sfSendMax in XRP, and the sfAmount isn't
56 // in XRP, then the transaction does not spend XRP.
57 return maxAmount.native() ? maxAmount.xrp() : beast::kZero;
58 };
59
60 return TxConsequences{ctx.tx, calculateMaxXRPSpend(ctx.tx)};
61}
62
65 AccountID const& account,
66 STAmount const& dstAmount,
67 std::optional<STAmount> const& sendMax)
68{
69 if (sendMax)
70 {
71 return *sendMax;
72 }
73 return dstAmount.asset().visit(
74 [&](MPTIssue const& issue) { return dstAmount; },
75 [&](Issue const& issue) {
76 if (issue.native())
77 return dstAmount;
78 return STAmount(
79 Issue{issue.currency, account},
80 dstAmount.mantissa(),
81 dstAmount.exponent(),
82 dstAmount < beast::kZero);
83 });
84}
85
86bool
88{
89 if (ctx.tx.isFieldPresent(sfCredentialIDs) && !ctx.rules.enabled(featureCredentials))
90 return false;
91 if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDEX))
92 return false;
93
94 return true;
95}
96
99{
100 auto& tx = ctx.tx;
101
102 STAmount const dstAmount(tx.getFieldAmount(sfAmount));
103 bool const isDstMPT = dstAmount.holds<MPTIssue>();
104 bool const mpTokensV2 = ctx.rules.enabled(featureMPTokensV2);
105
106 static constexpr std::uint32_t kTfMptPaymentMaskV1 = ~(tfUniversal | tfPartialPayment);
107 std::uint32_t const paymentMask =
108 (isDstMPT && !mpTokensV2) ? kTfMptPaymentMaskV1 : tfPaymentMask;
109
110 return paymentMask;
111}
112
113NotTEC
115{
116 auto& tx = ctx.tx;
117 auto& j = ctx.j;
118
119 STAmount const dstAmount(tx.getFieldAmount(sfAmount));
120 bool const isDstMPT = dstAmount.holds<MPTIssue>();
121 bool const mpTokensV2 = ctx.rules.enabled(featureMPTokensV2);
122
123 if (!ctx.rules.enabled(featureMPTokensV1) && isDstMPT)
124 return temDISABLED;
125
126 if (tx.isFlag(tfSponsorCreatedAccount))
127 {
128 if (!ctx.rules.enabled(featureSponsor))
129 return temDISABLED;
130
131 if (tx.isFlag(tfNoRippleDirect) || tx.isFlag(tfPartialPayment) || tx.isFlag(tfLimitQuality))
132 return temINVALID_FLAG;
133
134 if (tx.isFieldPresent(sfSendMax) || tx.isFieldPresent(sfPaths))
135 return temINVALID;
136
137 if (!dstAmount.native())
138 return temBAD_AMOUNT;
139 }
140
141 if (!mpTokensV2 && isDstMPT && ctx.tx.isFieldPresent(sfPaths))
142 return temMALFORMED;
143
144 // A zero DomainID is invalid for a PermissionedDomain ledger entry because
145 // keylet::permissionedDomain(UInt256) uses the DomainID as the ledger key.
146 if (auto const domainID = tx[~sfDomainID];
147 ctx.rules.enabled(fixCleanup3_2_0) && domainID && *domainID == beast::kZero)
148 return temMALFORMED;
149
150 bool const partialPaymentAllowed = tx.isFlag(tfPartialPayment);
151 bool const limitQuality = tx.isFlag(tfLimitQuality);
152 bool const defaultPathsAllowed = !tx.isFlag(tfNoRippleDirect);
153 bool const hasPaths = tx.isFieldPresent(sfPaths);
154 bool const hasMax = tx.isFieldPresent(sfSendMax);
155
156 auto const deliverMin = tx[~sfDeliverMin];
157
158 auto const account = tx.getAccountID(sfAccount);
159 STAmount const maxSourceAmount = getMaxSourceAmount(account, dstAmount, tx[~sfSendMax]);
160
161 if (!mpTokensV2 &&
162 ((isDstMPT && dstAmount.asset() != maxSourceAmount.asset()) ||
163 (!isDstMPT && maxSourceAmount.holds<MPTIssue>())))
164 {
165 JLOG(j.trace()) << "Malformed transaction: inconsistent issues: " << dstAmount.getFullText()
166 << " " << maxSourceAmount.getFullText() << " "
167 << deliverMin.value_or(STAmount{}).getFullText();
168 return temMALFORMED;
169 }
170
171 auto const& srcAsset = maxSourceAmount.asset();
172 auto const& dstAsset = dstAmount.asset();
173
174 bool const xrpDirect = srcAsset.native() && dstAsset.native();
175
176 if (!isLegalNet(dstAmount) || !isLegalNet(maxSourceAmount))
177 return temBAD_AMOUNT;
178
179 auto const dstAccountID = tx.getAccountID(sfDestination);
180
181 if (!dstAccountID)
182 {
183 JLOG(j.trace()) << "Malformed transaction: "
184 << "Payment destination account not specified.";
185 return temDST_NEEDED;
186 }
187 if (hasMax && maxSourceAmount <= beast::kZero)
188 {
189 JLOG(j.trace()) << "Malformed transaction: bad max amount: "
190 << maxSourceAmount.getFullText();
191 return temBAD_AMOUNT;
192 }
193 if (dstAmount <= beast::kZero)
194 {
195 JLOG(j.trace()) << "Malformed transaction: bad dst amount: " << dstAmount.getFullText();
196 return temBAD_AMOUNT;
197 }
198 auto const bad = [&](auto const& asset) {
199 if (ctx.rules.enabled(featureMPTokensV2))
200 return badAsset() == asset;
201 return badCurrency() == asset;
202 };
203 if (bad(srcAsset) || bad(dstAsset))
204 {
205 JLOG(j.trace()) << "Malformed transaction: Bad currency.";
206 return temBAD_CURRENCY;
207 }
208 if (account == dstAccountID && equalTokens(srcAsset, dstAsset) && !hasPaths)
209 {
210 // You're signing yourself a payment.
211 // If hasPaths is true, you might be trying some arbitrage.
212 JLOG(j.trace()) << "Malformed transaction: "
213 << "Redundant payment from " << to_string(account)
214 << " to self without path for " << to_string(dstAsset);
215 return temREDUNDANT;
216 }
217 if (xrpDirect && hasMax)
218 {
219 // Consistent but redundant transaction.
220 JLOG(j.trace()) << "Malformed transaction: "
221 << "SendMax specified for XRP to XRP.";
222 return temBAD_SEND_XRP_MAX;
223 }
224 if ((xrpDirect || (!mpTokensV2 && isDstMPT)) && hasPaths)
225 {
226 // XRP is sent without paths.
227 JLOG(j.trace()) << "Malformed transaction: "
228 << "Paths specified for XRP to XRP or MPT to MPT.";
230 }
231 if (xrpDirect && partialPaymentAllowed)
232 {
233 // Consistent but redundant transaction.
234 JLOG(j.trace()) << "Malformed transaction: "
235 << "Partial payment specified for XRP to XRP.";
237 }
238 if ((xrpDirect || (!mpTokensV2 && isDstMPT)) && limitQuality)
239 {
240 // Consistent but redundant transaction.
241 JLOG(j.trace()) << "Malformed transaction: "
242 << "Limit quality specified for XRP to XRP or MPT to MPT.";
244 }
245 if ((xrpDirect || (!mpTokensV2 && isDstMPT)) && !defaultPathsAllowed)
246 {
247 // Consistent but redundant transaction.
248 JLOG(j.trace()) << "Malformed transaction: "
249 << "No ripple direct specified for XRP to XRP or MPT to MPT.";
251 }
252
253 if (deliverMin)
254 {
255 if (!partialPaymentAllowed)
256 {
257 JLOG(j.trace()) << "Malformed transaction: Partial payment not "
258 "specified for "
259 << jss::DeliverMin.cStr() << ".";
260 return temBAD_AMOUNT;
261 }
262
263 auto const dMin = *deliverMin;
264 if (!isLegalNet(dMin) || dMin <= beast::kZero)
265 {
266 JLOG(j.trace()) << "Malformed transaction: Invalid " << jss::DeliverMin.cStr()
267 << " amount. " << dMin.getFullText();
268 return temBAD_AMOUNT;
269 }
270 if (dMin.asset() != dstAmount.asset())
271 {
272 JLOG(j.trace()) << "Malformed transaction: Dst issue differs "
273 "from "
274 << jss::DeliverMin.cStr() << ". " << dMin.getFullText();
275 return temBAD_AMOUNT;
276 }
277 if (dMin > dstAmount)
278 {
279 JLOG(j.trace()) << "Malformed transaction: Dst amount less than "
280 << jss::DeliverMin.cStr() << ". " << dMin.getFullText();
281 return temBAD_AMOUNT;
282 }
283 }
284
285 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
286 return err;
287
288 return tesSUCCESS;
289}
290
291NotTEC
293 ReadView const& view,
294 STTx const& tx,
295 std::unordered_set<GranularPermissionType> const& heldGranularPermissions)
296{
297 auto const& dstAmount = tx.getFieldAmount(sfAmount);
298 auto const& amountAsset = dstAmount.asset();
299
300 // Granular permissions are only valid for direct payments.
301 if (tx.isFieldPresent(sfSendMax) && tx[sfSendMax].asset() != amountAsset)
303
304 if (isXRP(amountAsset))
306
307 return amountAsset.visit(
308 [&](MPTIssue const& mptIssue) -> NotTEC {
309 // For MPT payments, the MPTokenIssuanceID encodes the issuer unambiguously,
310 // unlike IOU, there is no endpoint aliasing where either side of the
311 // trustline can appear as the issuer.
312 if (heldGranularPermissions.contains(PaymentMint) &&
313 mptIssue.getIssuer() == tx[sfAccount])
314 return tesSUCCESS;
315 if (heldGranularPermissions.contains(PaymentBurn) &&
316 mptIssue.getIssuer() == tx[sfDestination])
317 return tesSUCCESS;
319 },
320 [&](Issue const& issue) -> NotTEC {
321 // For IOU payments, either endpoint may be encoded as the issuer in
322 // sfAmount. PaySteps normalizes those endpoint aliases, so sfAmount.issuer
323 // alone does not reliably identify whether the transaction issues or redeems
324 // IOUs. We determine PaymentMint vs PaymentBurn from the trustline balance
325 // direction instead.
326 auto const account = tx[sfAccount];
327 auto const destination = tx[sfDestination];
328
329 // Reject if neither endpoint is the issuer.
330 if (issue.getIssuer() != account && issue.getIssuer() != destination)
332
333 auto const sle = view.read(keylet::trustLine(account, destination, issue.currency));
334 if (!sle)
336
337 bool const accountIsLow = (account < destination);
338 auto const destLimit = sle->getFieldAmount(accountIsLow ? sfHighLimit : sfLowLimit);
339 auto const rawBalance = sle->getFieldAmount(sfBalance);
340 bool const accountIsHolder =
341 accountIsLow ? rawBalance > beast::kZero : rawBalance < beast::kZero;
342
343 bool const mayIssue =
344 heldGranularPermissions.contains(PaymentMint) && destLimit > beast::kZero;
345
346 // PaymentMint requires the destination to be the holder and the account to be the
347 // issuer. destLimit > 0: destination is willing to hold account's IOUs (account is the
348 // issuer). !accountIsHolder: DirectStepI will issue, not redeem.
349 if (mayIssue && !accountIsHolder)
350 return tesSUCCESS;
351
352 // PaymentBurn requires the source account to be the holder and the destination to be
353 // the issuer. accountIsHolder: DirectStepI will redeem, not issue.
354 if (heldGranularPermissions.contains(PaymentBurn) && accountIsHolder)
355 {
356 if (view.rules().enabled(fixCleanup3_4_0))
357 {
358 // Redeeming stops at the balance held; beyond that the payment engine
359 // crosses zero and issues the account's own IOUs, which is a mint. So with
360 // only PaymentBurn we must check the amount against the balance held. The
361 // granular template forbids sfPaths, tfPartialPayment and a cross-asset
362 // sfSendMax, so this is a single direct step, sfAmount is what the
363 // trustline is debited.
364 STAmount const held = accountIsLow ? rawBalance : -rawBalance;
365 if (dstAmount <= held || mayIssue)
366 return tesSUCCESS;
367 }
368 else
369 {
370 return tesSUCCESS;
371 }
372 }
373
375 });
376}
377
378TER
380{
381 // Ripple if source or destination is non-native or if there are paths.
382 bool const partialPaymentAllowed = ctx.tx.isFlag(tfPartialPayment);
383 auto const hasPaths = ctx.tx.isFieldPresent(sfPaths);
384 auto const sendMax = ctx.tx[~sfSendMax];
385
386 AccountID const dstAccountID(ctx.tx[sfDestination]);
387 STAmount const dstAmount(ctx.tx[sfAmount]);
388
389 auto const k = keylet::account(dstAccountID);
390 auto const sleDst = ctx.view.read(k);
391
392 if (!sleDst)
393 {
394 // Destination account does not exist.
395 if (!dstAmount.native())
396 {
397 JLOG(ctx.j.trace()) << "Delay transaction: Destination account does not exist.";
398
399 // Another transaction could create the account and then this
400 // transaction would succeed.
401 return tecNO_DST;
402 }
403 // A partial payment may not fund a new account.
404 if (partialPaymentAllowed)
405 {
406 // Open view: the soft tel (unchanged).
407 if (ctx.view.open())
408 {
409 // Make retry work smaller, by rejecting this.
410 JLOG(ctx.j.trace()) << "Delay transaction: Partial payment not "
411 "allowed to create account.";
412 return telNO_DST_PARTIAL;
413 }
414 // Inner batch txns are claimed on a closed view, where a tel is
415 // invalid, so use the tef.
416 if (ctx.parentBatchId && ctx.view.rules().enabled(featureBatchV1_1))
417 return tefNO_DST_PARTIAL;
418 }
419 if (dstAmount < STAmount(ctx.view.fees().reserve))
420 {
421 // accountReserve is the minimum amount that an account can have.
422 // Reserve is not scaled by load.
423 if (!ctx.tx.isFlag(tfSponsorCreatedAccount))
424 {
425 // The minimum amount when creating a Sponsored Account is 1 drop.
426 // Since the reserve is covered by the sponsor, you don't need to hold the
427 // 1-increment reserve yourself.
428 JLOG(ctx.j.trace()) << "Delay transaction: Destination account does not exist. "
429 << "Insufficient payment to create account.";
430
431 // TODO: de-dupe
432 // Another transaction could create the account and then this
433 // transaction would succeed.
434 return tecNO_DST_INSUF_XRP;
435 }
436 }
437 }
438 else if (ctx.tx.isFlag(tfSponsorCreatedAccount))
439 {
440 // The tfSponsorCreatedAccount flag is specific to account creation via
441 // sponsorship. If the destination account already exists, applying this
442 // flag is invalid.
444 }
445 else if (sleDst->isFlag(lsfRequireDestTag) && !ctx.tx.isFieldPresent(sfDestinationTag))
446 {
447 // The tag is basically account-specific information we don't
448 // understand, but we can require someone to fill it in.
449
450 // We didn't make this test for a newly-formed account because there's
451 // no way for this field to be set.
452 JLOG(ctx.j.trace()) << "Malformed transaction: DestinationTag required.";
453
454 return tecDST_TAG_NEEDED;
455 }
456
457 // Payment with at least one intermediate step and uses transitive balances.
458 if (hasPaths || sendMax || !dstAmount.native())
459 {
460 STPathSet const& paths = ctx.tx.getFieldPathSet(sfPaths);
461
462 if (paths.size() > kMaxPathSize || std::ranges::any_of(paths, [](STPath const& path) {
463 return path.size() > kMaxPathLength;
464 }))
465 {
466 // Open view: the soft tel (unchanged). Inner batch txns are claimed
467 // on a closed view, where a tel is invalid, so use the tef.
468 if (ctx.view.open())
469 return telBAD_PATH_COUNT;
470 if (ctx.parentBatchId && ctx.view.rules().enabled(featureBatchV1_1))
471 return tefBAD_PATH_COUNT;
472 }
473 }
474
475 if (auto const err = credentials::valid(ctx.tx, ctx.view, ctx.tx[sfAccount], ctx.j);
476 !isTesSuccess(err))
477 return err;
478
479 if (ctx.tx.isFieldPresent(sfDomainID))
480 {
481 if (ctx.view.rules().enabled(fixCleanup3_4_0))
482 {
483 auto const domainID = ctx.tx[sfDomainID];
484 auto const sleDomain = ctx.view.read(keylet::permissionedDomain(domainID));
485 if (!sleDomain)
486 return tecNO_PERMISSION;
487
488 // Domain owner is always considered in the domain. For other accounts,
489 // suppress tecEXPIRED so doApply can run and delete expired credential
490 // SLEs from the ledger.
491 auto const checkAccount = [&](AccountID const& acct) -> TER {
492 if (sleDomain->getAccountID(sfOwner) == acct)
493 return tesSUCCESS;
494 // validDomain returns tecNO_AUTH when no matching credential is
495 // found. Map it to tecNO_PERMISSION to preserve existing behavior.
496 if (auto const err = credentials::validDomain(ctx.view, domainID, acct);
497 !isTesSuccess(err) && err != tecEXPIRED)
498 return tecNO_PERMISSION;
499 return tesSUCCESS;
500 };
501
502 if (auto const err = checkAccount(ctx.tx[sfAccount]); !isTesSuccess(err))
503 return err;
504 if (auto const err = checkAccount(ctx.tx[sfDestination]); !isTesSuccess(err))
505 return err;
506 }
507 else
508 {
509 if (!permissioned_dex::accountInDomain(ctx.view, ctx.tx[sfAccount], ctx.tx[sfDomainID]))
510 return tecNO_PERMISSION;
511
513 ctx.view, ctx.tx[sfDestination], ctx.tx[sfDomainID]))
514 return tecNO_PERMISSION;
515 }
516 }
517
518 return tesSUCCESS;
519}
520
521TER
523{
524 // If a DomainID is present, verify both sender and destination are still in
525 // the domain and delete any expired credential SLEs from the ledger.
526 if (ctx_.tx.isFieldPresent(sfDomainID) && ctx_.view().rules().enabled(fixCleanup3_4_0))
527 {
528 auto const domainID = ctx_.tx[sfDomainID];
529 auto const sleDomain = ctx_.view().read(keylet::permissionedDomain(domainID));
530 if (!sleDomain)
531 return tecINTERNAL; // LCOV_EXCL_LINE
532
533 auto const cleanupFor = [&](AccountID const& acct) -> TER {
534 if (sleDomain->getAccountID(sfOwner) == acct)
535 return tesSUCCESS;
536 return verifyValidDomain(ctx_.view(), acct, domainID, j_);
537 };
538
539 auto const destination = ctx_.tx[sfDestination];
540 auto const senderErr = cleanupFor(accountID_);
541 auto const destinationErr = accountID_ == destination ? senderErr : cleanupFor(destination);
542
543 if (!isTesSuccess(senderErr))
544 return senderErr;
545 if (!isTesSuccess(destinationErr))
546 return destinationErr;
547 }
548
549 auto const deliverMin = ctx_.tx[~sfDeliverMin];
550
551 // Ripple if source or destination is non-native or if there are paths.
552 bool const partialPaymentAllowed = ctx_.tx.isFlag(tfPartialPayment);
553 bool const limitQuality = ctx_.tx.isFlag(tfLimitQuality);
554 bool const defaultPathsAllowed = !ctx_.tx.isFlag(tfNoRippleDirect);
555 auto const hasPaths = ctx_.tx.isFieldPresent(sfPaths);
556 auto const sendMax = ctx_.tx[~sfSendMax];
557
558 AccountID const dstAccountID(ctx_.tx.getAccountID(sfDestination));
559 STAmount const dstAmount(ctx_.tx.getFieldAmount(sfAmount));
560 bool const isDstMPT = dstAmount.holds<MPTIssue>();
561 STAmount const maxSourceAmount = getMaxSourceAmount(accountID_, dstAmount, sendMax);
562
563 JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText()
564 << " dstAmount=" << dstAmount.getFullText();
565
566 // Open a ledger for editing.
567 auto const k = keylet::account(dstAccountID);
568 SLE::pointer sleDst = view().peek(k);
569
570 if (!sleDst)
571 {
572 // Create the account.
573 sleDst = std::make_shared<SLE>(k);
574 sleDst->setAccountID(sfAccount, dstAccountID);
575 sleDst->setFieldU32(sfSequence, view().seq());
576 sleDst->setFieldAmount(sfBalance, XRPAmount(beast::kZero));
577
578 if (ctx_.tx.isFlag(tfSponsorCreatedAccount))
579 {
580 auto const sponsor = view().peek(keylet::account(accountID_));
581 if (!sponsor)
582 return tefINTERNAL; // LCOV_EXCL_LINE
583 auto const currentSponsoringAccountCount =
584 sponsor->getFieldU32(sfSponsoringAccountCount);
585 if (currentSponsoringAccountCount == std::numeric_limits<std::uint32_t>::max())
586 {
587 // LCOV_EXCL_START
588 JLOG(j_.fatal()) << "Sponsoring account count overflow for account "
590 return tecINTERNAL;
591 // LCOV_EXCL_STOP
592 }
593 sponsor->setFieldU32(sfSponsoringAccountCount, currentSponsoringAccountCount + 1);
594
595 addSponsorToLedgerEntry(sleDst, sponsor);
596 view().update(sponsor);
597 }
598
599 view().insert(sleDst);
600 }
601 else
602 {
603 // Tell the engine that we are intending to change the destination
604 // account. The source account gets always charged a fee so it's always
605 // marked as modified.
606 view().update(sleDst);
607 }
608
609 bool const mpTokensV2 = view().rules().enabled(featureMPTokensV2);
610
611 // Direct MPT payment is handled by payment engine if MPTokensV2 is enabled
612 bool const ripple = (hasPaths || sendMax || !dstAmount.native()) && (!isDstMPT || mpTokensV2);
613
614 if (ripple)
615 {
616 // XRPL payment with at least one intermediate step and uses
617 // transitive balances.
618
619 // An account that requires authorization has two ways to get an
620 // IOU Payment in:
621 // 1. If Account == Destination, or
622 // 2. If Account is deposit preauthorized by destination.
623
624 if (auto err = verifyDepositPreauth(
625 ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal);
626 !isTesSuccess(err))
627 return err;
628
630 rcInput.partialPaymentAllowed = partialPaymentAllowed;
631 rcInput.defaultPathsAllowed = defaultPathsAllowed;
632 rcInput.limitQuality = limitQuality;
633 rcInput.isLedgerOpen = view().open();
634
636 {
637 PaymentSandbox pv(&view());
638 JLOG(j_.debug()) << "Entering RippleCalc in payment: " << ctx_.tx.getTransactionID();
640 pv,
641 maxSourceAmount,
642 dstAmount,
643 dstAccountID,
645 ctx_.tx.getFieldPathSet(sfPaths),
646 ctx_.tx[~sfDomainID],
647 ctx_.registry,
648 &rcInput);
649 // VFALCO NOTE We might not need to apply, depending
650 // on the TER. But always applying *should*
651 // be safe.
652 pv.apply(ctx_.rawView());
653 }
654
655 // TODO: is this right? If the amount is the correct amount, was
656 // the delivered amount previously set?
657 if (isTesSuccess(rc.result()) && rc.actualAmountOut != dstAmount)
658 {
659 if (deliverMin && rc.actualAmountOut < *deliverMin)
660 {
662 }
663 else
664 {
665 ctx_.deliver(rc.actualAmountOut);
666 }
667 }
668
669 auto terResult = rc.result();
670
671 // Because of its overhead, if RippleCalc
672 // fails with a retry code, claim a fee
673 // instead. Maybe the user will be more
674 // careful with their path spec next time.
675 if (isTerRetry(terResult))
676 terResult = tecPATH_DRY;
677 return terResult;
678 }
679 if (isDstMPT)
680 {
681 JLOG(j_.trace()) << " dstAmount=" << dstAmount.getFullText();
682 auto const& mptIssue = dstAmount.get<MPTIssue>();
683
684 if (auto const ter = requireAuth(view(), mptIssue, accountID_); !isTesSuccess(ter))
685 return ter;
686
687 if (auto const ter = requireAuth(view(), mptIssue, dstAccountID); !isTesSuccess(ter))
688 return ter;
689
690 if (auto const ter = canTransfer(view(), mptIssue, accountID_, dstAccountID);
691 !isTesSuccess(ter))
692 return ter;
693
694 if (auto err = verifyDepositPreauth(
695 ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal);
696 !isTesSuccess(err))
697 return err;
698
699 auto const& issuer = mptIssue.getIssuer();
700
701 // Transfer rate
702 Rate rate{QUALITY_ONE};
703 // Payment between the holders
704 if (accountID_ != issuer && dstAccountID != issuer)
705 {
706 // If globally/individually locked then
707 // - can't send between holders
708 // - holder can send back to issuer
709 // - issuer can send to holder
710 if (isAnyFrozen(view(), {accountID_, dstAccountID}, mptIssue))
711 return tecLOCKED;
712
713 // Get the rate for a payment between the holders.
714 rate = transferRate(view(), mptIssue.getMptID());
715 }
716
717 // Amount to deliver.
718 STAmount amountDeliver = dstAmount;
719 // True if the sender would pay more than SendMax.
720 bool exceedsSendMax = false;
721
722 if (view().rules().enabled(fixCleanup3_5_0))
723 {
724 // The legacy multiply() and divide() can overflow on large MPT
725 // amounts, and Number rounding can charge more than SendMax.
726 // MPTs are integral, so use exact integer arithmetic. The cost
727 // is rounded up, matching the transfer fee that accountSend
728 // charges. If the cost overflows, it exceeds any SendMax.
729 auto const requiredMaxSourceAmount =
730 tryMulRatio(dstAmount.mpt(), rate.value, QUALITY_ONE, true);
731 exceedsSendMax =
732 !requiredMaxSourceAmount || maxSourceAmount.mpt() < *requiredMaxSourceAmount;
733
734 // Send more than the account wants to pay or less than
735 // the account wants to deliver (if no SendMax).
736 // Adjust the amount to deliver.
737 if (partialPaymentAllowed && exceedsSendMax)
738 {
739 // Round the delivered amount down so that the sender is
740 // never charged more than SendMax.
741 auto const delivered =
742 mulRatio(maxSourceAmount.mpt(), QUALITY_ONE, rate.value, false);
743 amountDeliver = STAmount(maxSourceAmount.asset(), delivered.value());
744 if (amountDeliver <= beast::kZero)
745 return tecPATH_PARTIAL;
746 exceedsSendMax = false;
747 }
748 }
749 else
750 {
751 // Factor in the transfer rate.
752 // No rounding. It'll change once MPT integrated into DEX.
753 STAmount requiredMaxSourceAmount = multiply(dstAmount, rate);
754
755 // Send more than the account wants to pay or less than
756 // the account wants to deliver (if no SendMax).
757 // Adjust the amount to deliver.
758 if (partialPaymentAllowed && requiredMaxSourceAmount > maxSourceAmount)
759 {
760 requiredMaxSourceAmount = maxSourceAmount;
761 // No rounding. It'll change once MPT integrated into DEX.
762 amountDeliver = divide(maxSourceAmount, rate);
763 }
764 exceedsSendMax = requiredMaxSourceAmount > maxSourceAmount;
765 }
766
767 if (exceedsSendMax || (deliverMin && amountDeliver < *deliverMin))
768 return tecPATH_PARTIAL;
769
770 PaymentSandbox pv(&view());
771 auto res = accountSend(pv, accountID_, dstAccountID, amountDeliver, ctx_.journal);
772 if (isTesSuccess(res))
773 {
774 pv.apply(ctx_.rawView());
775
776 // If the actual amount delivered is different from the original
777 // amount due to partial payment or transfer fee, we need to update
778 // DeliveredAmount using the actual delivered amount
779 if (view().rules().enabled(fixMPTDeliveredAmount) && amountDeliver != dstAmount)
780 ctx_.deliver(amountDeliver);
781 }
782 else if (res == tecINSUFFICIENT_FUNDS || res == tecPATH_DRY)
783 {
784 res = tecPATH_PARTIAL;
785 }
786
787 return res;
788 }
789
790 XRPL_ASSERT(dstAmount.native(), "xrpl::Payment::doApply : amount is XRP");
791
792 // Direct XRP payment.
793
794 auto const sleSrc = view().peek(keylet::account(accountID_));
795 if (!sleSrc)
796 return tefINTERNAL; // LCOV_EXCL_LINE
797
798 // the number of reserves in this ledger for this account that require a
799 // reserve.
800 auto const reserve = accountReserve(view(), sleSrc, j_);
801
802 // In a delegated / fee sponsored payment, the fee payer is not the source account (accountID_).
803 bool const accountIsPayer = ctx_.tx.getFeePayerID() == accountID_;
804
805 // preFeeBalance_ is the balance on the source account (accountID_) BEFORE the fees
806 // were charged. If source account is the fee payer, it must also cover the fee.
807 // The final spend may use the reserve to cover fees.
808 auto const minRequiredFunds =
809 accountIsPayer ? std::max(reserve, ctx_.tx.getFieldAmount(sfFee).xrp()) : reserve;
810
811 if (preFeeBalance_ < dstAmount.xrp() + minRequiredFunds)
812 {
813 // Vote no. However the transaction might succeed, if applied in
814 // a different order.
815 JLOG(j_.trace()) << "Delay transaction: Insufficient funds: " << to_string(preFeeBalance_)
816 << " / " << to_string(dstAmount.xrp() + minRequiredFunds) << " ("
817 << to_string(reserve) << ")";
818
819 return tecUNFUNDED_PAYMENT;
820 }
821
822 // Pseudo-accounts cannot receive payments, other than these native to
823 // their underlying ledger object - implemented in their respective
824 // transaction types. Note, this is not amendment-gated because all writes
825 // to pseudo-account discriminator fields **are** amendment gated, hence the
826 // behaviour of this check will always match the active amendments.
827 if (isPseudoAccount(sleDst))
828 return tecNO_PERMISSION;
829
830 // The source account does have enough money. Make sure the
831 // source account has authority to deposit to the destination.
832 // An account that requires authorization has three ways to get an XRP
833 // Payment in:
834 // 1. If Account == Destination, or
835 // 2. If Account is deposit preauthorized by destination, or
836 // 3. If the destination's XRP balance is
837 // a. less than or equal to the base reserve and
838 // b. the deposit amount is less than or equal to the base reserve,
839 // then we allow the deposit.
840 //
841 // Rule 3 is designed to keep an account from getting wedged
842 // in an unusable state if it sets the lsfDepositAuth flag and
843 // then consumes all of its XRP. Without the rule if an
844 // account with lsfDepositAuth set spent all of its XRP, it
845 // would be unable to acquire more XRP required to pay fees.
846 //
847 // We choose the base reserve as our bound because it is
848 // a small number that seldom changes but is always sufficient
849 // to get the account un-wedged.
850
851 // Get the base reserve.
852 XRPAmount const dstReserve{view().fees().reserve};
853
854 if (dstAmount > dstReserve || sleDst->getFieldAmount(sfBalance) > dstReserve)
855 {
856 if (auto err = verifyDepositPreauth(
857 ctx_.tx, ctx_.view(), accountID_, dstAccountID, sleDst, ctx_.journal);
858 !isTesSuccess(err))
859 return err;
860 }
861
862 // Do the arithmetic for the transfer and make the ledger change.
863 sleSrc->setFieldAmount(sfBalance, sleSrc->getFieldAmount(sfBalance) - dstAmount);
864 sleDst->setFieldAmount(sfBalance, sleDst->getFieldAmount(sfBalance) + dstAmount);
865
866 // Re-arm the password change fee if we can and need to.
867 if (sleDst->isFlag(lsfPasswordSpent))
868 sleDst->clearFlag(lsfPasswordSpent);
869
870 return tesSUCCESS;
871}
872
873void
875{
876 // No transaction-specific invariants yet (future work).
877}
878
879bool
881{
882 // No transaction-specific invariants yet (future work).
883 return true;
884}
885
886} // namespace xrpl
T any_of(T... args)
A generic endpoint for log messages.
Definition Journal.h:44
Stream trace() const
Severity stream access functions.
Definition Journal.h:338
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void insert(SLE::Ref sle)=0
Insert a new state SLE.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
Definition Asset.h:117
constexpr bool native() const
Definition Asset.h:125
A currency issued by an account.
Definition Issue.h:18
static bool native()
Definition MPTIssue.h:61
AccountID const & getIssuer() const
Definition MPTIssue.cpp:29
A wrapper which makes credits unavailable to balances.
void apply(RawView &to)
Apply changes to base view.
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Definition Payment.cpp:874
static TxConsequences makeTxConsequences(PreflightContext const &ctx)
Definition Payment.cpp:50
static NotTEC preflight(PreflightContext const &ctx)
Definition Payment.cpp:114
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
Definition Payment.cpp:98
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition Payment.cpp:87
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.
Definition Payment.cpp:880
static std::size_t const kMaxPathSize
TER doApply() override
Definition Payment.cpp:522
static NotTEC checkGranularSemantics(ReadView const &view, STTx const &tx, std::unordered_set< GranularPermissionType > const &heldGranularPermissions)
Definition Payment.cpp:292
static TER preclaim(PreclaimContext const &ctx)
Definition Payment.cpp:379
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
virtual bool open() const =0
Returns true if this reflects an open ledger.
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
constexpr TIss const & get() const
std::string getFullText() const override
std::uint64_t mantissa() const noexcept
Definition STAmount.h:490
bool native() const noexcept
Definition STAmount.h:471
Asset const & asset() const
Definition STAmount.h:496
int exponent() const noexcept
Definition STAmount.h:459
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFlag(std::uint32_t) const
Definition STObject.cpp:511
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
STPathSet const & getFieldPathSet(SField const &field) const
Definition STObject.cpp:664
STAmount const & getFieldAmount(SField const &field) const
Definition STObject.cpp:657
std::vector< STPath >::size_type size() const
Definition STPathSet.h:624
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
static Output rippleCalculate(PaymentSandbox &view, STAmount const &saMaxAmountReq, STAmount const &saDstAmountReq, AccountID const &uDstAccountID, AccountID const &uSrcAccountID, STPathSet const &spsPaths, std::optional< UInt256 > const &domainID, ServiceRegistry &registry, Input const *const pInputs=nullptr)
T contains(T... args)
T make_shared(T... args)
T max(T... args)
constexpr Zero kZero
Definition Zero.h:30
NotTEC checkFields(STTx const &tx, Rules const &rules, beast::Journal j)
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
TER validDomain(ReadView const &view, UInt256 domainID, AccountID const &subject)
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
@ telBAD_PATH_COUNT
Definition TER.h:40
@ telNO_DST_PARTIAL
Definition TER.h:44
STAmount divide(STAmount const &amount, Rate const &rate)
Definition Rate2.cpp:69
@ terNO_DELEGATE_PERMISSION
Definition TER.h:232
bool isTerRetry(TER x) noexcept
Definition TER.h:680
bool isXRP(AccountID const &c)
Definition AccountID.h:84
STAmount getMaxSourceAmount(AccountID const &account, STAmount const &dstAmount, std::optional< STAmount > const &sendMax)
Definition Payment.cpp:64
@ tefBAD_PATH_COUNT
Definition TER.h:183
@ tefNO_DST_PARTIAL
Definition TER.h:182
@ tefINTERNAL
Definition TER.h:167
bool isLegalNet(STAmount const &value)
Definition STAmount.h:616
TER canTransfer(ReadView const &view, MPTIssue const &mptIssue, AccountID const &from, AccountID const &to, WaiveMPTCanTransfer waive=WaiveMPTCanTransfer::No, std::uint8_t depth=0)
Check whether to may receive the given MPT from from.
constexpr FlagValue tfUniversal
Definition TxFlags.h:45
void addSponsorToLedgerEntry(SLE::Ref sle, SLE::ConstRef sponsorSle, SF_ACCOUNT const &field=sfSponsor)
Stamp a reserve sponsor onto a ledger entry using an explicit sponsor SLE.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
std::optional< MPTAmount > tryMulRatio(MPTAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
Definition MPTAmount.h:179
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, SLE::Ref sponsorSle={}, WaiveTransferFee waiveFee=WaiveTransferFee::No, AllowMPTOverflow allowOverflow=AllowMPTOverflow::No)
Calls static accountSendIOU if saAmount represents Issue.
IOUAmount mulRatio(IOUAmount const &amt, std::uint32_t num, std::uint32_t den, bool roundUp)
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)
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temBAD_SEND_XRP_PATHS
Definition TER.h:91
@ temBAD_CURRENCY
Definition TER.h:78
@ temBAD_SEND_XRP_MAX
Definition TER.h:88
@ temBAD_SEND_XRP_LIMIT
Definition TER.h:87
@ temINVALID
Definition TER.h:98
@ temINVALID_FLAG
Definition TER.h:99
@ temBAD_SEND_XRP_PARTIAL
Definition TER.h:90
@ temDST_NEEDED
Definition TER.h:97
@ temMALFORMED
Definition TER.h:75
@ temBAD_SEND_XRP_NO_DIRECT
Definition TER.h:89
@ temDISABLED
Definition TER.h:102
@ temBAD_AMOUNT
Definition TER.h:77
@ temREDUNDANT
Definition TER.h:100
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
bool isAnyFrozen(ReadView const &view, std::initializer_list< AccountID > const &accounts, MPTIssue const &mptIssue, std::uint8_t depth=0)
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.
@ tecLOCKED
Definition TER.h:369
@ tecPATH_PARTIAL
Definition TER.h:293
@ tecUNFUNDED_PAYMENT
Definition TER.h:296
@ tecPATH_DRY
Definition TER.h:305
@ tecNO_DST_INSUF_XRP
Definition TER.h:302
@ tecNO_SPONSOR_PERMISSION
Definition TER.h:380
@ tecINTERNAL
Definition TER.h:321
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecEXPIRED
Definition TER.h:325
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDST_TAG_NEEDED
Definition TER.h:320
@ tecNO_DST
Definition TER.h:301
STAmount multiply(STAmount const &amount, Number const &frac, Number::RoundingMode rm)
BadAsset const & badAsset()
Definition Asset.h:40
TER verifyDepositPreauth(STTx const &tx, ApplyView &view, AccountID const &src, AccountID const &dst, SLE::ConstRef sleDst, beast::Journal j)
Currency const & badCurrency()
We deliberately disallow the currency that looks like "XRP" because too many people were using it ins...
@ tesSUCCESS
Definition TER.h:253
constexpr bool equalTokens(Asset const &lhs, Asset const &rhs)
Definition Asset.h:286
XRPAmount reserve
Minimum XRP an account must hold to exist on the ledger.
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::optional< UInt256 const > const parentBatchId
Definition Transactor.h:99
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
void setResult(TER const value)
Definition RippleCalc.h:64