xrpld
Loading...
Searching...
No Matches
LoanBrokerCoverWithdraw.cpp
1#include <xrpl/tx/transactors/lending/LoanBrokerCoverWithdraw.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/ledger/View.h>
7#include <xrpl/ledger/helpers/AccountRootHelpers.h>
8#include <xrpl/ledger/helpers/CredentialHelpers.h>
9#include <xrpl/ledger/helpers/LendingHelpers.h>
10#include <xrpl/ledger/helpers/TokenHelpers.h>
11#include <xrpl/protocol/Feature.h>
12#include <xrpl/protocol/Indexes.h>
13#include <xrpl/protocol/Protocol.h>
14#include <xrpl/protocol/SField.h>
15#include <xrpl/protocol/STAmount.h>
16#include <xrpl/protocol/STLedgerEntry.h>
17#include <xrpl/protocol/STTakesAsset.h>
18#include <xrpl/protocol/STTx.h>
19#include <xrpl/protocol/TER.h>
20#include <xrpl/protocol/Units.h>
21#include <xrpl/protocol/XRPAmount.h>
22#include <xrpl/tx/Transactor.h>
23
24namespace xrpl {
25
26bool
28{
30 return false;
31
32 return !ctx.tx.isFieldPresent(sfCredentialIDs) ||
33 (ctx.rules.enabled(featureCredentials) && ctx.rules.enabled(fixCleanup3_4_0));
34}
35
38{
39 if (ctx.tx[sfLoanBrokerID] == beast::kZero)
40 return temINVALID;
41
42 auto const dstAmount = ctx.tx[sfAmount];
43 if (dstAmount <= beast::kZero)
44 return temBAD_AMOUNT;
45
46 if (!isLegalNet(dstAmount))
47 return temBAD_AMOUNT;
48
49 if (auto const destination = ctx.tx[~sfDestination])
50 {
51 if (*destination == beast::kZero)
52 {
53 return temMALFORMED;
54 }
55 }
56
57 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
58 return err;
59
60 return tesSUCCESS;
61}
62
63TER
65{
66 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
67 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
68 auto const fix340Enabled = ctx.view.rules().enabled(fixCleanup3_4_0);
69 auto const& tx = ctx.tx;
70
71 auto const account = tx[sfAccount];
72 auto const brokerID = tx[sfLoanBrokerID];
73 auto const amount = tx[sfAmount];
74
75 auto const dstAcct = tx[~sfDestination].value_or(account);
76
77 if (isPseudoAccount(ctx.view, dstAcct))
78 {
79 JLOG(ctx.j.warn()) << "Trying to withdraw into a pseudo-account.";
80 return tecPSEUDO_ACCOUNT;
81 }
82 auto const sleBroker = ctx.view.read(keylet::loanBroker(brokerID));
83 if (!sleBroker)
84 {
85 JLOG(ctx.j.warn()) << "LoanBroker does not exist.";
86 return tecNO_ENTRY;
87 }
88 if (account != sleBroker->at(sfOwner))
89 {
90 JLOG(ctx.j.warn()) << "Account is not the owner of the LoanBroker.";
91 return tecNO_PERMISSION;
92 }
93 auto const vault = ctx.view.read(keylet::vault(sleBroker->at(sfVaultID)));
94 if (!vault)
95 {
96 // LCOV_EXCL_START
97 JLOG(ctx.j.fatal()) << "Vault is missing for Broker " << brokerID;
98 return tefBAD_LEDGER;
99 // LCOV_EXCL_STOP
100 }
101
102 auto const vaultAsset = vault->at(sfAsset);
103 if (amount.asset() != vaultAsset)
104 return tecWRONG_ASSET;
105
106 // Helper handles both IOU and MPT correctly without explicit branching.
107 if (auto const ret = canApplyToBrokerCover(
108 ctx.view, sleBroker, vaultAsset, amount, ctx.j, "LoanBrokerCoverWithdraw"))
109 return ret;
110
111 // The broker's pseudo-account is the source of funds.
112 auto const pseudoAccountID = sleBroker->at(sfAccount);
113 // Post-fixCleanup3_2_0: cover withdraw is a recovery path that bypasses
114 // the lsfMPTCanTransfer flag check, so an issuer cannot trap a broker's
115 // first-loss capital. Other transferability checks (IOU NoRipple, freeze,
116 // requireAuth) still apply.
117 auto const waive = fix320Enabled ? WaiveMPTCanTransfer::Yes : WaiveMPTCanTransfer::No;
118 if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct, waive))
119 return ret;
120
121 // Validate credentials (if any) before canWithdraw, since canWithdraw may
122 // call credentials::authorizedDepositPreauth which assumes credentials
123 // already exist.
124 if (auto const err = credentials::valid(ctx.tx, ctx.view, account, ctx.j); !isTesSuccess(err))
125 return err;
126
127 // Withdrawal to a 3rd party destination account is essentially a transfer.
128 // Enforce all the usual asset transfer checks.
129 AuthType authType = AuthType::WeakAuth;
130 if (account != dstAcct)
131 {
132 if (auto const ret = canWithdraw(ctx.view, tx))
133 return ret;
134
135 // The destination account must have consented to receive the asset by
136 // creating a RippleState or MPToken
137 authType = AuthType::StrongAuth;
138 }
139
140 // Destination MPToken must exist (if asset is an MPT)
141 if (auto const ter = requireAuth(ctx.view, vaultAsset, dstAcct, authType))
142 return ter;
143
144 if (fix340Enabled && account == dstAcct && !holdingExists(ctx.view, dstAcct, vaultAsset))
145 {
146 if (auto const ter = canAddHolding(ctx.view, vaultAsset); !isTesSuccess(ter))
147 return ter;
148 }
149
150 if (fix330Enabled)
151 {
152 if (auto const ret =
153 checkWithdrawFreeze(ctx.view, pseudoAccountID, account, dstAcct, vaultAsset))
154 return ret;
155 }
156 else
157 { // Check for freezes, unless sending directly to the issuer
158 if (dstAcct != vaultAsset.getIssuer())
159 {
160 // Cannot send a frozen Asset
161 if (auto const ret = checkFrozen(ctx.view, pseudoAccountID, vaultAsset))
162 return ret;
163 // Destination account cannot receive if asset is deep frozen
164 if (auto const ret = checkDeepFrozen(ctx.view, dstAcct, vaultAsset))
165 return ret;
166 }
167 }
168
169 auto const coverAvail = sleBroker->at(sfCoverAvailable);
170 // Cover Rate is in 1/10 bips units
171 auto const currentDebtTotal = sleBroker->at(sfDebtTotal);
172 auto const minimumCover = [&]() {
173 if (fix320Enabled)
174 {
175 return minimumBrokerCover(
176 currentDebtTotal, TenthBips32{sleBroker->at(sfCoverRateMinimum)}, vault);
177 }
178
179 // Always round the minimum required up.
180 // Applies to `tenthBipsOfValue` as well as `roundToAsset`.
182 return roundToAsset(
183 vaultAsset,
184 tenthBipsOfValue(currentDebtTotal, TenthBips32(sleBroker->at(sfCoverRateMinimum))),
185 scale(currentDebtTotal, vaultAsset));
186 }();
187 if (coverAvail < amount)
189 if ((coverAvail - amount) < minimumCover)
191
192 auto const freezeHandling = fix330Enabled && dstAcct == vaultAsset.getIssuer()
195
196 if (accountHolds(
197 ctx.view,
198 pseudoAccountID,
199 vaultAsset,
200 freezeHandling,
202 ctx.j) < amount)
204
205 return tesSUCCESS;
206}
207
208TER
210{
211 auto const& tx = ctx_.tx;
212
213 auto const brokerID = tx[sfLoanBrokerID];
214 auto const amount = tx[sfAmount];
215 auto const dstAcct = tx[~sfDestination].value_or(accountID_);
216
217 auto broker = view().peek(keylet::loanBroker(brokerID));
218 if (!broker)
219 return tecINTERNAL; // LCOV_EXCL_LINE
220
221 auto const vault = view().read(keylet::vault(broker->at(sfVaultID)));
222 if (!vault)
223 return tecINTERNAL; // LCOV_EXCL_LINE
224
225 auto const vaultAsset = vault->at(sfAsset);
226
227 auto const brokerPseudoID = *broker->at(sfAccount);
228
229 // Decrease the LoanBroker's CoverAvailable by Amount
230 broker->at(sfCoverAvailable) -= amount;
231 view().update(broker);
232
233 associateAsset(*broker, vaultAsset);
234
235 return doWithdraw(
236 ctx_.getApplyViewContext(),
238 dstAcct,
239 brokerPseudoID,
241 amount,
242 j_);
243}
244
245void
247{
248 // No transaction-specific invariants yet (future work).
249}
250
251bool
253 STTx const&,
254 TER,
255 XRPAmount,
256 ReadView const&,
257 beast::Journal const&)
258{
259 // No transaction-specific invariants yet (future work).
260 return true;
261}
262
263//------------------------------------------------------------------------------
264
265} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream fatal() const
Definition Journal.h:368
Stream warn() const
Definition Journal.h:356
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void update(SLE::Ref sle)=0
Indicate changes to a peeked SLE.
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.
static NotTEC preflight(PreflightContext const &ctx)
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.
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
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
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
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)
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:591
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:597
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
TER checkDeepFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:794
@ tefBAD_LEDGER
Definition TER.h:165
bool isLegalNet(STAmount const &value)
Definition STAmount.h:616
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
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.
TER doWithdraw(ApplyViewContext ctx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &amount, beast::Journal j)
Definition View.cpp:507
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:614
TER canWithdraw(ReadView const &view, AccountID const &from, AccountID const &to, SLE::ConstRef toSle, STAmount const &amount, bool hasDestinationTag, std::optional< std::vector< UInt256 > > const &credentialIDs=std::nullopt)
Checks that can withdraw funds from an object to itself or a destination.
Definition View.cpp:437
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:735
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
@ temINVALID
Definition TER.h:98
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:683
TERSubset< CanCvtToTER > TER
Definition TER.h:654
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.
@ tecWRONG_ASSET
Definition TER.h:368
@ tecPSEUDO_ACCOUNT
Definition TER.h:370
@ tecNO_ENTRY
Definition TER.h:314
@ tecINTERNAL
Definition TER.h:318
@ tecINSUFFICIENT_FUNDS
Definition TER.h:333
@ tecNO_PERMISSION
Definition TER.h:313
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
TER checkWithdrawFreeze(ReadView const &view, AccountID const &pseudoAcct, AccountID const &submitterAcct, AccountID const &dstAcct, Asset const &asset)
Checks freeze compliance for withdrawing an asset from a pseudo-account (e.g.
TER canApplyToBrokerCover(ReadView const &view, SLE::ConstRef sleBroker, Asset const &vaultAsset, STAmount const &amount, beast::Journal j, std::string_view logPrefix)
Broker cover preclaim precision guard (fixCleanup3_2_0).
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const &currency, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j, SpendableHandling includeFullBalance=SpendableHandling::SimpleBalance)
@ tesSUCCESS
Definition TER.h:250
bool holdingExists(ReadView const &view, AccountID const &account, Asset const &asset)
True if the account already holds this asset (or is the issuer / XRP).
bool checkLendingProtocolDependencies(Rules const &rules, STTx const &tx)
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
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