xrpld
Loading...
Searching...
No Matches
LoanBrokerCoverClawback.cpp
1#include <xrpl/tx/transactors/lending/LoanBrokerCoverClawback.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/base_uint.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/core/ServiceRegistry.h>
8#include <xrpl/ledger/ReadView.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/AccountID.h>
13#include <xrpl/protocol/Asset.h>
14#include <xrpl/protocol/Concepts.h>
15#include <xrpl/protocol/Feature.h>
16#include <xrpl/protocol/Indexes.h>
17#include <xrpl/protocol/Issue.h>
18#include <xrpl/protocol/LedgerFormats.h>
19#include <xrpl/protocol/MPTIssue.h>
20#include <xrpl/protocol/Protocol.h>
21#include <xrpl/protocol/SField.h>
22#include <xrpl/protocol/STAmount.h>
23#include <xrpl/protocol/STLedgerEntry.h>
24#include <xrpl/protocol/STTakesAsset.h>
25#include <xrpl/protocol/STTx.h>
26#include <xrpl/protocol/TER.h>
27#include <xrpl/protocol/Units.h>
28#include <xrpl/protocol/XRPAmount.h>
29#include <xrpl/tx/Transactor.h>
30
31#include <expected>
32#include <optional>
33#include <variant>
34
35namespace xrpl {
36
37bool
42
45{
46 auto const brokerID = ctx.tx[~sfLoanBrokerID];
47 auto const amount = ctx.tx[~sfAmount];
48
49 if (!brokerID && !amount)
50 return temINVALID;
51
52 if (brokerID && *brokerID == beast::kZero)
53 return temINVALID;
54
55 if (amount)
56 {
57 // XRP has no counterparty, and thus nobody can claw it back
58 if (amount->native())
59 return temBAD_AMOUNT;
60
61 // Zero is OK, and indicates "take it all" (down to the minimum cover)
62 if (*amount < beast::kZero)
63 return temBAD_AMOUNT;
64
65 // This should be redundant
66 if (!isLegalNet(*amount))
67 return temBAD_AMOUNT; // LCOV_EXCL_LINE
68
69 if (!brokerID)
70 {
71 if (amount->holds<MPTIssue>())
72 return temINVALID;
73
74 auto const account = ctx.tx[sfAccount];
75 // Since we don't have a LoanBrokerID, holder _should_ be the loan
76 // broker's pseudo-account, but we don't know yet whether it is, so
77 // use a generic placeholder name.
78 auto const holder = amount->getIssuer();
79 if (holder == account || holder == beast::kZero)
80 return temINVALID;
81 }
82 }
83
84 return tesSUCCESS;
85}
86
87std::expected<UInt256, TER>
88determineBrokerID(ReadView const& view, STTx const& tx)
89{
90 // If the broker ID was provided in the transaction, that's all we
91 // need.
92 if (auto const brokerID = tx[~sfLoanBrokerID])
93 return *brokerID;
94
95 // If the broker ID was not provided, and the amount is either
96 // absent or holds a non-IOU - including MPT, something went wrong,
97 // because that should have been rejected in preflight().
98 auto const dstAmount = tx[~sfAmount];
99 if (!dstAmount || !dstAmount->holds<Issue>())
100 return std::unexpected{tecINTERNAL}; // LCOV_EXCL_LINE
101
102 // Every trust line is bidirectional. Both sides are simultaneously
103 // issuer and holder. For this transaction, the Account is acting as
104 // a holder, and clawing back funds from the LoanBroker
105 // Pseudo-account acting as holder. If the Amount is an IOU, and the
106 // `issuer` field specified in that Amount is a LoanBroker
107 // Pseudo-account, we can get the LoanBrokerID from there.
108 //
109 // Thus, Amount.issuer _should_ be the loan broker's
110 // pseudo-account, but we don't know yet whether it is.
111 auto const maybePseudo = dstAmount->getIssuer();
112 auto const sle = view.read(keylet::account(maybePseudo));
113
114 // If the account was not found, the transaction can't go further.
115 if (!sle)
117
118 // If the account was found, and has a LoanBrokerID (and therefore
119 // is a pseudo-account), that's the
120 // answer we need.
121 if (auto const brokerID = sle->at(~sfLoanBrokerID))
122 return *brokerID;
123
124 // If the account does not have a LoanBrokerID, the transaction
125 // can't go further, even if it's a different type of Pseudo-account.
127 // Or tecWRONG_ASSET?
128}
129
130std::expected<Asset, TER>
132 ReadView const& view,
133 AccountID const& account,
134 AccountID const& brokerPseudoAccountID,
135 STAmount const& amount)
136{
137 if (amount.holds<MPTIssue>())
138 return amount.asset();
139
140 // An IOU has an issue, which could be either end of the trust line.
141 // This check only applies to IOUs
142 auto const holder = amount.getIssuer();
143
144 // holder can be the submitting account (the issuer of the asset) if a
145 // LoanBrokerID was provided in the transaction.
146 if (holder == account)
147 {
148 return amount.asset();
149 }
150 if (holder == brokerPseudoAccountID)
151 {
152 // We want the asset to match the vault asset, so use the account as the
153 // issuer
154 return Issue{amount.get<Issue>().currency, account};
155 }
156
158}
159
160std::expected<STAmount, TER>
162 SLE::ConstRef sleBroker,
163 Asset const& vaultAsset,
164 std::optional<STAmount> const& amount,
165 SLE::ConstRef vaultSle,
166 Rules const& rules)
167{
168 auto const maxClawAmount = [&] {
169 auto const minRequiredCover = [&] {
170 if (rules.enabled(fixCleanup3_2_0))
171 {
172 return minimumBrokerCover(
173 sleBroker->at(sfDebtTotal),
174 TenthBips32(sleBroker->at(sfCoverRateMinimum)),
175 vaultSle);
176 }
177
178 // Always round the minimum required up
180 return tenthBipsOfValue(
181 sleBroker->at(sfDebtTotal), TenthBips32(sleBroker->at(sfCoverRateMinimum)));
182 }();
183 // The subtraction probably won't round, but round down if it does.
185 return sleBroker->at(sfCoverAvailable) - minRequiredCover;
186 }();
187 if (maxClawAmount <= beast::kZero)
189
190 // Use the vaultAsset here, because it will be the right type in all
191 // circumstances. The amount may be an IOU indicating the pseudo-account's
192 // asset, which is correct, but not what is needed here.
193 STAmount requested = [&] {
194 if (!amount || *amount == beast::kZero)
195 return STAmount{vaultAsset, maxClawAmount};
196 Number const magnitude{*amount};
197 if (magnitude > maxClawAmount)
198 return STAmount{vaultAsset, maxClawAmount};
199 return STAmount{vaultAsset, magnitude};
200 }();
201
203 return requested;
204
206 vaultSle, sleBroker, requested, Number::RoundingMode::TowardsZero);
207 if (rounded == beast::kZero)
209 return rounded;
210}
211
212template <ValidIssueType T>
213static TER
214preclaimHelper(PreclaimContext const& ctx, SLE const& sleIssuer, STAmount const& clawAmount);
215
216template <>
218preclaimHelper<Issue>(PreclaimContext const& ctx, SLE const& sleIssuer, STAmount const& clawAmount)
219{
220 // If AllowTrustLineClawback is not set or NoFreeze is set, return no
221 // permission
222 if (!sleIssuer.isFlag(lsfAllowTrustLineClawback) || sleIssuer.isFlag(lsfNoFreeze))
223 return tecNO_PERMISSION;
224
225 return tesSUCCESS;
226}
227
228template <>
231 PreclaimContext const& ctx,
232 SLE const& sleIssuer,
233 STAmount const& clawAmount)
234{
235 auto const issuanceKey = keylet::mptokenIssuance(clawAmount.get<MPTIssue>().getMptID());
236 auto const sleIssuance = ctx.view.read(issuanceKey);
237 if (!sleIssuance)
238 return tecOBJECT_NOT_FOUND;
239
240 if (!sleIssuance->isFlag(lsfMPTCanClawback))
241 return tecNO_PERMISSION;
242
243 // With all the checking already done, this should be impossible
244 if (sleIssuance->at(sfIssuer) != sleIssuer[sfAccount])
245 return tecINTERNAL; // LCOV_EXCL_LINE
246
247 return tesSUCCESS;
248}
249
250TER
252{
253 auto const& tx = ctx.tx;
254
255 auto const account = tx[sfAccount];
256 auto const findBrokerID = determineBrokerID(ctx.view, tx);
257 if (!findBrokerID)
258 return findBrokerID.error();
259 auto const brokerID = *findBrokerID;
260 auto const amount = tx[~sfAmount];
261
262 auto const sleBroker = ctx.view.read(keylet::loanBroker(brokerID));
263 if (!sleBroker)
264 {
265 JLOG(ctx.j.warn()) << "LoanBroker does not exist.";
266 return tecNO_ENTRY;
267 }
268
269 auto const brokerPseudoAccountID = sleBroker->at(sfAccount);
270
271 auto const vault = ctx.view.read(keylet::vault(sleBroker->at(sfVaultID)));
272 if (!vault)
273 {
274 // LCOV_EXCL_START
275 JLOG(ctx.j.fatal()) << "Vault is missing for Broker " << brokerID;
276 return tefBAD_LEDGER;
277 // LCOV_EXCL_STOP
278 }
279
280 auto const vaultAsset = vault->at(sfAsset);
281
282 if (vaultAsset.native())
283 {
284 JLOG(ctx.j.warn()) << "Cannot clawback native asset.";
285 return tecNO_PERMISSION;
286 }
287
288 // Only the issuer of the vault asset can claw it back from the broker's
289 // cover funds.
290 if (vaultAsset.getIssuer() != account)
291 {
292 JLOG(ctx.j.warn()) << "Account is not the issuer of the vault asset.";
293 return tecNO_PERMISSION;
294 }
295
296 if (amount)
297 {
298 auto const findAsset = determineAsset(ctx.view, account, brokerPseudoAccountID, *amount);
299 if (!findAsset)
300 return findAsset.error();
301 auto const txAsset = *findAsset;
302 if (txAsset != vaultAsset)
303 {
304 JLOG(ctx.j.warn()) << "Account is the correct issuer, but trying "
305 "to clawback the wrong asset from LoanBroker";
306 return tecWRONG_ASSET;
307 }
308 }
309
310 auto const findClawAmount =
311 determineClawAmount(sleBroker, vaultAsset, amount, vault, ctx.view.rules());
312 if (!findClawAmount)
313 {
314 JLOG(ctx.j.warn()) << "LoanBroker cover is already at minimum, or the claw amount "
315 "rounds to zero: "
316 << transToken(findClawAmount.error());
317 return findClawAmount.error();
318 }
319 STAmount const& clawAmount = *findClawAmount;
320
321 // FixedPrecision outflows already rounded at the posterior exponent; the
322 // live CoverAvailable scale used by canApplyToBrokerCover would reject a
323 // re-fining clawback as sub-ULP.
325 {
326 if (auto const ret = canApplyToBrokerCover(
327 ctx.view, sleBroker, vaultAsset, clawAmount, ctx.j, "LoanBrokerCoverClawback"))
328 return ret;
329 }
330
331 // Explicitly check the balance of the trust line / MPT to make sure the
332 // balance is actually there. It should always match `sfCoverAvailable`, so
333 // if there isn't, this is an internal error.
334 if (accountHolds(
335 ctx.view,
336 brokerPseudoAccountID,
337 vaultAsset,
340 ctx.j) < clawAmount)
341 return tecINTERNAL; // tecINSUFFICIENT_FUNDS; LCOV_EXCL_LINE
342
343 // Check if the vault asset issuer has the correct flags
344 auto const sleIssuer = ctx.view.read(keylet::account(vaultAsset.getIssuer()));
345 if (!sleIssuer)
346 {
347 // LCOV_EXCL_START
348 JLOG(ctx.j.fatal()) << "Issuer account does not exist.";
349 return tefBAD_LEDGER;
350 // LCOV_EXCL_STOP
351 }
352
353 return std::visit(
354 [&]<typename T>(T const&) { return preclaimHelper<T>(ctx, *sleIssuer, clawAmount); },
355 vaultAsset.value());
356}
357
358TER
360{
361 auto const& tx = ctx_.tx;
362 auto const account = tx[sfAccount];
363 auto const findBrokerID = determineBrokerID(view(), tx);
364 if (!findBrokerID)
365 return tecINTERNAL; // LCOV_EXCL_LINE
366 auto const brokerID = *findBrokerID;
367 auto const amount = tx[~sfAmount];
368
369 auto const sleBroker = view().peek(keylet::loanBroker(brokerID));
370 if (!sleBroker)
371 return tecINTERNAL; // LCOV_EXCL_LINE
372
373 auto const brokerPseudoID = *sleBroker->at(sfAccount);
374
375 auto const vault = view().read(keylet::vault(sleBroker->at(sfVaultID)));
376 if (!vault)
377 return tecINTERNAL; // LCOV_EXCL_LINE
378
379 auto const vaultAsset = vault->at(sfAsset);
380
381 auto const findClawAmount =
382 determineClawAmount(sleBroker, vaultAsset, amount, vault, view().rules());
383 if (!findClawAmount)
384 return tecINTERNAL; // LCOV_EXCL_LINE
385 STAmount const& clawAmount = *findClawAmount;
386 // Just for paranoia's sake
387 if (clawAmount.native())
388 return tecINTERNAL; // LCOV_EXCL_LINE
389
390 // Decrease the LoanBroker's CoverAvailable by Amount
391 sleBroker->at(sfCoverAvailable) -= clawAmount;
392 view().update(sleBroker);
393
394 associateAsset(*sleBroker, vaultAsset);
395
396 // Transfer assets from pseudo-account to depositor.
397 return accountSend(view(), brokerPseudoID, account, clawAmount, j_, {}, WaiveTransferFee::Yes);
398}
399
400void
402{
403 // No transaction-specific invariants yet (future work).
404}
405
406bool
408 STTx const&,
409 TER,
410 XRPAmount,
411 ReadView const&,
412 beast::Journal const&)
413{
414 // No transaction-specific invariants yet (future work).
415 return true;
416}
417
418//------------------------------------------------------------------------------
419
420} // 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.
A currency issued by an account.
Definition Issue.h:18
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 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)
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
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.
Rules controlling protocol behavior.
Definition Rules.h:40
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
bool native() const noexcept
Definition STAmount.h:471
Asset const & asset() const
Definition STAmount.h:496
AccountID const & getIssuer() const
Definition STAmount.h:516
std::shared_ptr< STLedgerEntry const > const & ConstRef
bool isFlag(std::uint32_t) const
Definition STObject.cpp:511
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
ApplyContext & ctx_
Definition Transactor.h:162
constexpr Zero kZero
Definition Zero.h:30
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
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
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...
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
@ tefBAD_LEDGER
Definition TER.h:164
bool isLegalNet(STAmount const &value)
Definition STAmount.h:616
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
std::string transToken(TER code)
Definition TER.cpp:259
STLedgerEntry SLE
std::expected< STAmount, TER > determineClawAmount(SLE::ConstRef sleBroker, Asset const &vaultAsset, std::optional< STAmount > const &amount, SLE::ConstRef vaultSle, Rules const &rules)
Number minimumBrokerCover(Number const &debtTotal, TenthBips32 coverRateMinimum, SLE::ConstRef vaultSle)
Minimum required broker cover, rounded up.
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.
std::expected< UInt256, TER > determineBrokerID(ReadView const &view, STTx const &tx)
TER preclaimHelper< Issue >(PreclaimContext const &ctx, SLE const &sleIssuer, STAmount const &clawAmount)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temINVALID
Definition TER.h:98
@ temBAD_AMOUNT
Definition TER.h:77
TERSubset< CanCvtToTER > TER
Definition TER.h:657
TER preclaimHelper< MPTIssue >(PreclaimContext const &ctx, SLE const &sleIssuer, STAmount const &clawAmount)
@ tecWRONG_ASSET
Definition TER.h:371
@ tecNO_ENTRY
Definition TER.h:317
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ 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 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
static TER preclaimHelper(PreclaimContext const &ctx, SLE const &sleIssuer, STAmount const &clawAmount)
bool checkLendingProtocolDependencies(Rules const &rules, STTx const &tx)
std::expected< Asset, TER > determineAsset(ReadView const &view, AccountID const &account, AccountID const &brokerPseudoAccountID, STAmount const &amount)
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
T unexpected(T... args)
T visit(T... args)