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/ledger/helpers/VaultHelpers.h>
12#include <xrpl/protocol/Feature.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/Protocol.h>
15#include <xrpl/protocol/SField.h>
16#include <xrpl/protocol/STAmount.h>
17#include <xrpl/protocol/STLedgerEntry.h>
18#include <xrpl/protocol/STTakesAsset.h>
19#include <xrpl/protocol/STTx.h>
20#include <xrpl/protocol/TER.h>
21#include <xrpl/protocol/Units.h>
22#include <xrpl/protocol/XRPAmount.h>
23#include <xrpl/tx/Transactor.h>
24
25namespace xrpl {
26
27bool
29{
31 return false;
32
33 return !ctx.tx.isFieldPresent(sfCredentialIDs) ||
34 (ctx.rules.enabled(featureCredentials) && ctx.rules.enabled(fixCleanup3_4_0));
35}
36
39{
40 if (ctx.tx[sfLoanBrokerID] == beast::kZero)
41 return temINVALID;
42
43 auto const dstAmount = ctx.tx[sfAmount];
44 if (dstAmount <= beast::kZero)
45 return temBAD_AMOUNT;
46
47 if (!isLegalNet(dstAmount))
48 return temBAD_AMOUNT;
49
50 if (auto const destination = ctx.tx[~sfDestination])
51 {
52 if (*destination == beast::kZero)
53 {
54 return temMALFORMED;
55 }
56 }
57
58 if (auto const err = credentials::checkFields(ctx.tx, ctx.rules, ctx.j); !isTesSuccess(err))
59 return err;
60
61 return tesSUCCESS;
62}
63
64TER
66{
67 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
68 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
69 auto const fix340Enabled = ctx.view.rules().enabled(fixCleanup3_4_0);
70 auto const& tx = ctx.tx;
71
72 auto const account = tx[sfAccount];
73 auto const brokerID = tx[sfLoanBrokerID];
74 auto const amount = tx[sfAmount];
75
76 auto const dstAcct = tx[~sfDestination].value_or(account);
77
78 if (isPseudoAccount(ctx.view, dstAcct))
79 {
80 JLOG(ctx.j.warn()) << "Trying to withdraw into a pseudo-account.";
81 return tecPSEUDO_ACCOUNT;
82 }
83 auto const sleBroker = ctx.view.read(keylet::loanBroker(brokerID));
84 if (!sleBroker)
85 {
86 JLOG(ctx.j.warn()) << "LoanBroker does not exist.";
87 return tecNO_ENTRY;
88 }
89 if (account != sleBroker->at(sfOwner))
90 {
91 JLOG(ctx.j.warn()) << "Account is not the owner of the LoanBroker.";
92 return tecNO_PERMISSION;
93 }
94 auto const vault = ctx.view.read(keylet::vault(sleBroker->at(sfVaultID)));
95 if (!vault)
96 {
97 // LCOV_EXCL_START
98 JLOG(ctx.j.fatal()) << "Vault is missing for Broker " << brokerID;
99 return tefBAD_LEDGER;
100 // LCOV_EXCL_STOP
101 }
102
103 auto const vaultAsset = vault->at(sfAsset);
104 if (amount.asset() != vaultAsset)
105 return tecWRONG_ASSET;
106
107 STAmount roundedAmount{amount};
109 {
110 // FixedPrecision outflows are rounded at the posterior exponent here
111 // instead of going through canApplyToBrokerCover: the live
112 // CoverAvailable scale it uses would reject a re-fining withdrawal as
113 // sub-ULP.
114 roundedAmount = debitToPosteriorBrokerCoverScale(
115 vault, sleBroker, amount, Number::RoundingMode::TowardsZero);
116 if (roundedAmount == beast::kZero)
117 {
118 JLOG(ctx.j.warn()) << "LoanBrokerCoverWithdraw: withdraw amount: " << amount
119 << " is zero at loan broker scale";
120 return tecPRECISION_LOSS;
121 }
122 }
123 else
124 {
125 if (auto const ret = canApplyToBrokerCover(
126 ctx.view, sleBroker, vaultAsset, roundedAmount, ctx.j, "LoanBrokerCoverWithdraw"))
127 return ret;
128 }
129
130 // The broker's pseudo-account is the source of funds.
131 auto const pseudoAccountID = sleBroker->at(sfAccount);
132 // Post-fixCleanup3_2_0: cover withdraw is a recovery path that bypasses
133 // the lsfMPTCanTransfer flag check, so an issuer cannot trap a broker's
134 // first-loss capital. Other transferability checks (IOU NoRipple, freeze,
135 // requireAuth) still apply.
136 auto const waive = fix320Enabled ? WaiveMPTCanTransfer::Yes : WaiveMPTCanTransfer::No;
137 if (auto const ret = canTransfer(ctx.view, vaultAsset, pseudoAccountID, dstAcct, waive))
138 return ret;
139
140 // Validate credentials (if any) before canWithdraw, since canWithdraw may
141 // call credentials::authorizedDepositPreauth which assumes credentials
142 // already exist.
143 if (auto const err = credentials::valid(ctx.tx, ctx.view, account, ctx.j); !isTesSuccess(err))
144 return err;
145
146 // Withdrawal to a 3rd party destination account is essentially a transfer.
147 // Enforce all the usual asset transfer checks.
148 AuthType authType = AuthType::WeakAuth;
149 if (account != dstAcct)
150 {
151 // Check the amount actually sent: on FixedPrecision it is the rounded
152 // amount, not sfAmount.
153 if (auto const ret = canWithdraw(
154 ctx.view,
155 account,
156 dstAcct,
157 roundedAmount,
158 tx.isFieldPresent(sfDestinationTag),
159 tx[~sfCredentialIDs]))
160 return ret;
161
162 // The destination account must have consented to receive the asset by
163 // creating a RippleState or MPToken
164 authType = AuthType::StrongAuth;
165 }
166
167 // Destination MPToken must exist (if asset is an MPT)
168 if (auto const ter = requireAuth(ctx.view, vaultAsset, dstAcct, authType))
169 return ter;
170
171 if (fix340Enabled && account == dstAcct && !holdingExists(ctx.view, dstAcct, vaultAsset))
172 {
173 if (auto const ter = canAddHolding(ctx.view, vaultAsset); !isTesSuccess(ter))
174 return ter;
175 }
176
177 if (fix330Enabled)
178 {
179 if (auto const ret =
180 checkWithdrawFreeze(ctx.view, pseudoAccountID, account, dstAcct, vaultAsset))
181 return ret;
182 }
183 else
184 { // Check for freezes, unless sending directly to the issuer
185 if (dstAcct != vaultAsset.getIssuer())
186 {
187 // Cannot send a frozen Asset
188 if (auto const ret = checkFrozen(ctx.view, pseudoAccountID, vaultAsset))
189 return ret;
190 // Destination account cannot receive if asset is deep frozen
191 if (auto const ret = checkDeepFrozen(ctx.view, dstAcct, vaultAsset))
192 return ret;
193 }
194 }
195
196 auto const coverAvail = sleBroker->at(sfCoverAvailable);
197 // Cover Rate is in 1/10 bips units
198 auto const currentDebtTotal = sleBroker->at(sfDebtTotal);
199 auto const minimumCover = [&] {
200 if (fix320Enabled)
201 {
202 return minimumBrokerCover(
203 currentDebtTotal, TenthBips32{sleBroker->at(sfCoverRateMinimum)}, vault);
204 }
205
206 // Always round the minimum required up.
207 // Applies to `tenthBipsOfValue` as well as `roundToAsset`.
209 return roundToAsset(
210 vaultAsset,
211 tenthBipsOfValue(currentDebtTotal, TenthBips32(sleBroker->at(sfCoverRateMinimum))),
212 scale(currentDebtTotal, vaultAsset));
213 }();
214 if (coverAvail < roundedAmount)
216 if ((coverAvail - roundedAmount) < minimumCover)
218
219 auto const freezeHandling = fix330Enabled && dstAcct == vaultAsset.getIssuer()
222
223 if (accountHolds(
224 ctx.view,
225 pseudoAccountID,
226 vaultAsset,
227 freezeHandling,
229 ctx.j) < roundedAmount)
231
232 return tesSUCCESS;
233}
234
235TER
237{
238 auto const& tx = ctx_.tx;
239
240 auto const brokerID = tx[sfLoanBrokerID];
241 auto const requestedAmount = tx[sfAmount];
242 auto const dstAcct = tx[~sfDestination].value_or(accountID_);
243
244 auto const broker = view().peek(keylet::loanBroker(brokerID));
245 if (!broker)
246 return tecINTERNAL; // LCOV_EXCL_LINE
247
248 auto const vault = view().read(keylet::vault(broker->at(sfVaultID)));
249 if (!vault)
250 return tecINTERNAL; // LCOV_EXCL_LINE
251
252 auto const vaultAsset = vault->at(sfAsset);
253 auto const amount = getVaultVersion(vault) == VaultVersion::FixedPrecision
255 vault, broker, requestedAmount, Number::RoundingMode::TowardsZero)
256 : requestedAmount;
257
258 auto const brokerPseudoID = *broker->at(sfAccount);
259
260 // Decrease the LoanBroker's CoverAvailable by Amount
261 broker->at(sfCoverAvailable) -= amount;
262 view().update(broker);
263
264 associateAsset(*broker, vaultAsset);
265
266 return doWithdraw(
267 ctx_.getApplyViewContext(),
269 dstAcct,
270 brokerPseudoID,
272 amount,
273 amount,
274 j_);
275}
276
277void
279{
280 // No transaction-specific invariants yet (future work).
281}
282
283bool
285 STTx const&,
286 TER,
287 XRPAmount,
288 ReadView const&,
289 beast::Journal const&)
290{
291 // No transaction-specific invariants yet (future work).
292 return true;
293}
294
295//------------------------------------------------------------------------------
296
297} // 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:565
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:571
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)
STAmount debitToPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, STAmount const &amount, Number::RoundingMode roundingMode)
Round a cover debit (cover withdraw, cover clawback, the broker-side decrease of a default's cover cr...
TER doWithdraw(ApplyViewContext ctx, AccountID const &senderAcct, AccountID const &dstAcct, AccountID const &sourceAcct, XRPAmount priorBalance, STAmount const &destinationAmount, STAmount const &sourceAmount, beast::Journal j)
Pays out a withdrawal from a vault or loan broker pseudo-account.
Definition View.cpp:508
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:819
@ tefBAD_LEDGER
Definition TER.h:164
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.
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
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:438
void roundToAsset(A const &asset, Number &value)
Round an arbitrary precision Number IN PLACE to the precision of a given Asset.
Definition STAmount.h:745
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:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
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:371
@ tecPSEUDO_ACCOUNT
Definition TER.h:373
@ tecNO_ENTRY
Definition TER.h:317
@ tecINTERNAL
Definition TER.h:321
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecNO_PERMISSION
Definition TER.h:316
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
VaultVersion getVaultVersion(SLE::ConstRef vault)
Resolves a Vault's LEVersion.
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:253
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