1#include <xrpl/tx/transactors/check/CheckCash.h>
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/scope.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/core/ServiceRegistry.h>
7#include <xrpl/ledger/ApplyView.h>
8#include <xrpl/ledger/PaymentSandbox.h>
9#include <xrpl/ledger/View.h>
10#include <xrpl/ledger/entries/CheckEntry.h>
11#include <xrpl/ledger/helpers/AccountRootHelpers.h>
12#include <xrpl/ledger/helpers/MPTokenHelpers.h>
13#include <xrpl/ledger/helpers/RippleStateHelpers.h>
14#include <xrpl/ledger/helpers/SponsorHelpers.h>
15#include <xrpl/ledger/helpers/TokenHelpers.h>
16#include <xrpl/protocol/AccountID.h>
17#include <xrpl/protocol/Asset.h>
18#include <xrpl/protocol/Feature.h>
19#include <xrpl/protocol/Indexes.h>
20#include <xrpl/protocol/Issue.h>
21#include <xrpl/protocol/Keylet.h>
22#include <xrpl/protocol/LedgerFormats.h>
23#include <xrpl/protocol/MPTAmount.h>
24#include <xrpl/protocol/MPTIssue.h>
25#include <xrpl/protocol/Quality.h>
26#include <xrpl/protocol/SField.h>
27#include <xrpl/protocol/STAmount.h>
28#include <xrpl/protocol/STLedgerEntry.h>
29#include <xrpl/protocol/STTx.h>
30#include <xrpl/protocol/TER.h>
31#include <xrpl/protocol/UintTypes.h>
32#include <xrpl/protocol/XRPAmount.h>
33#include <xrpl/tx/Transactor.h>
34#include <xrpl/tx/paths/Flow.h>
35#include <xrpl/tx/paths/detail/Steps.h>
46 auto const optAmount = ctx.
tx[~sfAmount];
47 auto const optDeliverMin = ctx.
tx[~sfDeliverMin];
50 (!(optAmount && optAmount->holds<
MPTIssue>()) &&
51 !(optDeliverMin && optDeliverMin->holds<
MPTIssue>()));
61 auto const optAmount = ctx.
tx[~sfAmount];
62 auto const optDeliverMin = ctx.
tx[~sfDeliverMin];
64 if (
static_cast<bool>(optAmount) ==
static_cast<bool>(optDeliverMin))
66 JLOG(ctx.
j.
debug()) <<
"Malformed transaction: "
67 "does not specify exactly one of Amount and DeliverMin.";
72 STAmount const value{optAmount ? *optAmount : *optDeliverMin};
75 JLOG(ctx.
j.
debug()) <<
"Malformed transaction: bad amount: " << value.getFullText();
81 JLOG(ctx.
j.
debug()) <<
"Malformed transaction: Bad currency.";
94 JLOG(ctx.
j.
debug()) <<
"Check does not exist.";
99 AccountID const dstId = sleCheck->
at(sfDestination);
100 if (ctx.
tx[sfAccount] != dstId)
102 JLOG(ctx.
j.
debug()) <<
"Cashing a check with wrong Destination.";
111 JLOG(ctx.
j.
error()) <<
"Malformed transaction: Cashing check to self.";
118 if (!sleSrc || !sleDst)
121 JLOG(ctx.
j.
debug()) <<
"Malformed transaction: source or destination not in ledger";
125 if (sleDst->isFlag(lsfRequireDestTag) && !sleCheck->
isFieldPresent(sfDestinationTag))
129 JLOG(ctx.
j.
debug()) <<
"Malformed transaction: DestinationTag required in check.";
136 JLOG(ctx.
j.
debug()) <<
"Cashing a check that has already expired.";
145 auto const optAmount = tx[~sfAmount];
146 return optAmount ? *optAmount : tx[sfDeliverMin];
150 STAmount const sendMax = sleCheck->
at(sfSendMax);
158 JLOG(ctx.
j.
debug()) <<
"Check cash does not match check currency.";
161 AccountID const issuerId{value.getIssuer()};
164 JLOG(ctx.
j.
debug()) <<
"Check cash does not match check issuer.";
169 JLOG(ctx.
j.
debug()) <<
"Check cashed for more than check sendMax.";
179 sleCheck->
at(sfAccount),
193 if (value > availableFunds)
195 JLOG(ctx.
j.
debug()) <<
"Check cashed for more than owner's balance.";
201 if (!value.native() && (value.getIssuer() != dstId))
203 return value.asset().visit(
206 auto const sleTrustLine =
212 JLOG(ctx.
j.
debug()) <<
"Can't receive IOUs from "
213 "non-existent issuer: "
218 if (sleIssuer->isFlag(lsfRequireAuth))
231 bool const canonicalGt(dstId > issuerId);
233 bool const isAuthorized(
234 (sleTrustLine->at(sfFlags) &
235 (canonicalGt ? lsfLowAuth : lsfHighAuth)) != 0u);
239 JLOG(ctx.
j.
debug()) <<
"Can't receive IOUs from "
240 "issuer without auth.";
254 JLOG(ctx.
j.
debug()) <<
"Cashing a check to a frozen trustline.";
264 JLOG(ctx.
j.
debug()) <<
"Can't receive MPTs from "
265 "non-existent issuer: "
273 JLOG(ctx.
j.
debug()) <<
"Cashing a check to a MPT requiring auth.";
279 JLOG(ctx.
j.
debug()) <<
"Cashing a check to a frozen MPT.";
286 JLOG(ctx.
j.
debug()) <<
"MPT transfer is disabled.";
309 JLOG(
j_.fatal()) <<
"Precheck did not verify check's existence.";
314 AccountID const srcId{(*sleCheck)->getAccountID(sfAccount)};
318 JLOG(
ctx_.journal.fatal()) <<
"Precheck did not verify source or destination's existence.";
335 auto viewJ =
ctx_.registry.get().getJournal(
"View");
336 auto const optDeliverMin =
ctx_.tx[~sfDeliverMin];
340 STAmount const sendMax = (*sleCheck)->at(sfSendMax);
353 STAmount const srcLiquid{
xrpLiquid(psb, srcId, sponsorCheckSle ? 0 : -1, viewJ)};
358 :
ctx_.tx.getFieldAmount(sfAmount)};
360 if (srcLiquid < xrpDeliver)
364 JLOG(
j_.trace()) <<
"Cash Check: Insufficient XRP: " << srcLiquid.
getFullText()
372 ctx_.deliver(xrpDeliver);
390 auto const maxDeliverMin = [&] {
391 return optDeliverMin->asset().visit(
398 auto const& issuer = issue.getIssuer();
412 optDeliverMin ? maxDeliverMin() :
ctx_.tx.getFieldAmount(sfAmount),
418 return sponsorSle.error();
431 {.ownerCountDelta = 1},
435 JLOG(
j_.trace()) <<
"Trust line does not exist. "
436 "Insufficient reserve to create line.";
445 bool destLow =
false;
450 if (deliverIssuer ==
accountID_ &&
ctx_.view().rules().enabled(fixCleanup3_4_0))
456 Issue const& trustLineIssue = issue;
461 if (!psb.
exists(*trustLineKey))
473 auto const sleDst = checkDstReserve();
474 if (sleDst ==
nullptr)
489 !sleDst->isFlag(lsfDefaultRipple),
516 auto const sleTrustLine = psb.
peek(*trustLineKey);
520 SF_AMOUNT const& tweakedLimit = destLow ? sfLowLimit : sfHighLimit;
521 savedLimit = sleTrustLine->at(tweakedLimit);
527 sleTrustLine->at(tweakedLimit) = bigAmount;
534 auto const& mptID = issue.getMptID();
537 if (!psb.
exists(mptokenKey))
539 auto const sleDst = checkDstReserve();
540 if (sleDst ==
nullptr)
558 ScopeExit const fixup([&psb, &trustLineKey, destLow, &savedLimit] {
561 SF_AMOUNT const& tweakedLimit = destLow ? sfLowLimit : sfHighLimit;
562 if (
auto const sleTrustLine = psb.
peek(*trustLineKey))
563 sleTrustLine->at(tweakedLimit) = savedLimit;
568 auto const result =
flow(
575 static_cast<bool>(optDeliverMin),
579 (*sleCheck)->getFieldAmount(sfSendMax),
585 JLOG(
ctx_.journal.debug()) <<
"flow failed when cashing check.";
586 return result.result();
592 if (result.actualAmountOut < *optDeliverMin)
594 JLOG(
ctx_.journal.debug()) <<
"flow did not produce DeliverMin.";
597 ctx_.deliver(result.actualAmountOut);
602 ctx_.deliver(result.actualAmountOut);
613 (*sleCheck)->at(sfDestinationNode),
618 JLOG(
j_.fatal()) <<
"Unable to delete check from destination.";
625 keylet::ownerDir(srcId), (*sleCheck)->at(sfOwnerNode), (*sleCheck)->key(),
true))
628 JLOG(
j_.fatal()) <<
"Unable to delete check from owner.";
A generic endpoint for log messages.
bool dirRemove(Keylet const &directory, std::uint64_t page, UInt256 const &key, bool keepRoot)
Remove an entry from a directory.
constexpr auto visit(Visitors &&... visitors) const -> decltype(auto)
static TER preclaim(PreclaimContext 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)
static bool checkExtraFeatures(PreflightContext const &ctx)
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.
A currency issued by an account.
A wrapper which makes credits unavailable to balances.
void apply(RawView &to)
Apply changes to base view.
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.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
constexpr TIss const & get() const
std::string getFullText() const override
bool native() const noexcept
Asset const & asset() const
AccountID const & getIssuer() const
static constexpr std::uint64_t kMaxValue
static constexpr int kMaxOffset
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
T::value_type at(TypedField< T > const &f) const
Get the value of a field.
bool isFieldPresent(SField const &field) const
AccountID const accountID_
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
bool exists(Keylet const &k) const override
Determine if a state item exists.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
Calculate liquid XRP balance for an account.
bool isLegalMPT(STAmount const &value)
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp, ExpiryComparison comparison=ExpiryComparison::Inclusive)
Determines whether the given expiration time has passed.
CheckEntry< ReadView > CheckEntryR
TER checkCreateMPT(xrpl::ApplyView &view, xrpl::MPTIssue const &mptIssue, xrpl::AccountID const &holder, SLE::Ref sponsorSle, std::uint32_t flags, beast::Journal j)
bool isLegalNet(STAmount const &value)
BaseUInt< 160, detail::CurrencyTag > Currency
Currency is a hash representing a specific currency.
TER checkReserve(ApplyViewContext ctx, SLE::ConstRef accSle, XRPAmount accBalance, SLE::ConstRef sponsorSle, Adjustment adj, beast::Journal j, TER insufReserveCode=tecINSUFFICIENT_RESERVE)
Check if an account has sufficient reserve.
TER trustCreate(ApplyView &view, bool const bSrcHigh, AccountID const &uSrcAccountID, AccountID const &uDstAccountID, UInt256 const &uIndex, SLE::Ref sleAccount, bool const bAuth, bool const bNoRipple, bool const bFreeze, bool bDeepFreeze, STAmount const &saBalance, STAmount const &saLimit, std::uint32_t uQualityIn, std::uint32_t uQualityOut, SLE::Ref sponsorSle, beast::Journal j)
Create a trust line.
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.
TypedField< STAmount > SF_AMOUNT
std::string to_string(BaseUInt< Bits, Tag > const &a)
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
std::expected< SLE::pointer, TER > getTxReserveSponsor(ApplyViewContext ctx)
Return a mutable SLE for the transaction's reserve sponsor account.
TERSubset< CanCvtToNotTEC > NotTEC
void decreaseOwnerCountForObject(ApplyView &view, SLE::Ref accountSle, SLE::Ref objectSle, std::uint32_t count, beast::Journal j)
Decrease owner-count fields for an existing ledger object.
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.
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 transferXRP(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &amount, beast::Journal j)
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
Returns true if account cannot send or receive tokens of mptIssue because a freeze applies.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
AccountID const & noAccount()
A placeholder for empty accounts.
bool isTesSuccess(TER x) noexcept
SLE::pointer getLedgerEntryReserveSponsor(ApplyView &view, SLE::ConstRef sle, SF_ACCOUNT const &field=sfSponsor)
Return a mutable SLE for the reserve sponsor recorded on a ledger entry.
TERSubset< CanCvtToTER > TER
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.
@ tecNO_LINE_INSUF_RESERVE
@ tecINSUFFICIENT_RESERVE
BadAsset const & badAsset()
constexpr bool equalTokens(Asset const &lhs, Asset const &rhs)
Bundles the mutable ledger view and the transaction being applied.
XRPAmount increment
Additional XRP reserve required per owned ledger object.
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.