xrpld
Loading...
Searching...
No Matches
LoanBrokerSet.cpp
1#include <xrpl/tx/transactors/lending/LoanBrokerSet.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/core/ServiceRegistry.h>
7#include <xrpl/ledger/View.h>
8#include <xrpl/ledger/helpers/AccountRootHelpers.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/Feature.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/LedgerFormats.h>
17#include <xrpl/protocol/Protocol.h>
18#include <xrpl/protocol/SField.h>
19#include <xrpl/protocol/STAmount.h>
20#include <xrpl/protocol/STLedgerEntry.h>
21#include <xrpl/protocol/STNumber.h>
22#include <xrpl/protocol/STTakesAsset.h>
23#include <xrpl/protocol/STTx.h>
24#include <xrpl/protocol/TER.h>
25#include <xrpl/protocol/TxFlags.h>
26#include <xrpl/protocol/XRPAmount.h>
27#include <xrpl/tx/Transactor.h>
28
29#include <cstdint>
30#include <memory>
31#include <vector>
32
33namespace xrpl {
34
35bool
37{
38 if (!ctx.rules.enabled(featureLendingProtocolV1_2) && ctx.tx.isFieldPresent(sfDomainID))
39 return false;
41}
42
45{
46 using namespace lending;
47
48 auto const& tx = ctx.tx;
49 if (auto const data = tx[~sfData];
50 data && !data->empty() && !validDataLength(tx[~sfData], kMaxDataPayloadLength))
51 return temINVALID;
52 if (!validNumericRange(tx[~sfManagementFeeRate], kMaxManagementFeeRate))
53 return temINVALID;
54 if (!validNumericRange(tx[~sfCoverRateMinimum], kMaxCoverRate))
55 return temINVALID;
56 if (!validNumericRange(tx[~sfCoverRateLiquidation], kMaxCoverRate))
57 return temINVALID;
58 if (!validNumericRange(tx[~sfDebtMaximum], Number(kMaxMpTokenAmount), Number(0)))
59 return temINVALID;
60
61 if (tx.isFieldPresent(sfLoanBrokerID))
62 {
63 // We're modifying an existing LoanBroker.
64 // Fixed fields can not be specified if we're modifying an existing
65 // LoanBroker Object
66 if (tx.isFieldPresent(sfManagementFeeRate) || tx.isFieldPresent(sfCoverRateMinimum) ||
67 tx.isFieldPresent(sfCoverRateLiquidation))
68 return temINVALID;
69
70 if (tx[sfLoanBrokerID] == beast::kZero)
71 return temINVALID;
72
73 // Cannot change private flag on existing broker
74 if (tx.isFlag(tfLoanBrokerPrivate))
75 {
76 return temINVALID;
77 }
78 }
79 else
80 {
81 // We're creating a new LoanBroker.
82 if (auto const domainID = tx[~sfDomainID])
83 {
84 if (*domainID == beast::kZero)
85 {
86 // DomainID must not be zero if provided
87 return temMALFORMED;
88 }
89 if (!tx.isFlag(tfLoanBrokerPrivate))
90 {
91 // Public brokers cannot have a DomainID
92 return temINVALID;
93 }
94 }
95 }
96
97 if (auto const vaultID = tx.at(~sfVaultID))
98 {
99 if (*vaultID == beast::kZero)
100 return temINVALID;
101 }
102
103 {
104 auto const minimumZero = tx[~sfCoverRateMinimum].value_or(0) == 0;
105 auto const liquidationZero = tx[~sfCoverRateLiquidation].value_or(0) == 0;
106 // Both must be zero or non-zero.
107 if (minimumZero != liquidationZero)
108 {
109 return temINVALID;
110 }
111 }
112
113 return tesSUCCESS;
114}
115
118{
119 static std::vector<OptionaledField<STNumber>> const kValueFields{~sfDebtMaximum};
120
121 return kValueFields;
122}
123
126{
127 if (ctx.rules.enabled(featureLendingProtocolV1_2))
128 {
129 return tfLoanBrokerSetMask;
130 }
131 return tfUniversalMask;
132}
133
134TER
136{
137 auto const& tx = ctx.tx;
138
139 auto const account = tx[sfAccount];
140 auto const vaultID = tx[sfVaultID];
141
142 auto const sleVault = ctx.view.read(keylet::vault(vaultID));
143 if (!sleVault)
144 {
145 JLOG(ctx.j.warn()) << "Vault does not exist.";
146 return tecNO_ENTRY;
147 }
148 Asset const asset = sleVault->at(sfAsset);
149
150 if (account != sleVault->at(sfOwner))
151 {
152 JLOG(ctx.j.warn()) << "Account is not the owner of the Vault.";
153 return tecNO_PERMISSION;
154 }
155
156 if (auto const brokerID = tx[~sfLoanBrokerID])
157 {
158 // Updating an existing Broker
159
160 auto const sleBroker = ctx.view.read(keylet::loanBroker(*brokerID));
161 if (!sleBroker)
162 {
163 JLOG(ctx.j.warn()) << "LoanBroker does not exist.";
164 return tecNO_ENTRY;
165 }
166 if (vaultID != sleBroker->at(sfVaultID))
167 {
168 JLOG(ctx.j.warn()) << "Can not change VaultID on an existing LoanBroker.";
169 return tecNO_PERMISSION;
170 }
171 if (account != sleBroker->at(sfOwner))
172 {
173 JLOG(ctx.j.warn()) << "Account is not the owner of the LoanBroker.";
174 return tecNO_PERMISSION;
175 }
176
177 if (auto const debtMax = tx[~sfDebtMaximum])
178 {
179 // Can't reduce the debt maximum below the current total debt
180 auto const currentDebtTotal = sleBroker->at(sfDebtTotal);
181 if (*debtMax != 0 && *debtMax < currentDebtTotal)
182 {
183 JLOG(ctx.j.warn()) << "Cannot reduce DebtMaximum below current DebtTotal.";
184 return tecLIMIT_EXCEEDED;
185 }
186 }
187
188 if (!sleBroker->isFlag(lsfLoanBrokerPrivate) && tx.isFieldPresent(sfDomainID))
189 return tecNO_PERMISSION;
190 }
191 else
192 {
193 // LP V1.1: only closed-ended vaults may host a loan broker. The
194 // lending protocol relies on the closed-ended Subscription /
195 // Investment / Redemption phase structure; attaching a broker to
196 // an open-ended vault has no well-defined lifecycle. VaultCreate
197 // stays unrestricted so existing open-ended flows keep working;
198 // the constraint is enforced here, at the point where the vault
199 // is first bound to the lending protocol.
200 if (ctx.view.rules().enabled(featureLendingProtocolV1_1) &&
202 {
203 JLOG(ctx.j.warn()) << "LoanBroker requires a closed-ended Vault.";
204 return tecNO_PERMISSION;
205 }
206
207 if (auto const ter = canAddHolding(ctx.view, asset))
208 return ter;
209
210 if (auto const ter = checkFrozen(ctx.view, sleVault->at(sfAccount), sleVault->at(sfAsset)))
211 {
212 JLOG(ctx.j.warn()) << "Vault pseudo-account is frozen.";
213 return ter;
214 }
215 }
216
217 if (auto const domainID = tx[~sfDomainID]; domainID && *domainID != beast::kZero)
218 {
219 if (!ctx.view.exists(keylet::permissionedDomain(*domainID)))
220 {
221 JLOG(ctx.j.warn()) << "Domain does not exist.";
222 return tecOBJECT_NOT_FOUND;
223 }
224 }
225
226 // Check that relevant values can be represented as the vault asset
227 // type. This is mostly only relevant for integral (non-IOU) types.
228 // fixCleanup3_5_0 also rejects out-of-range values, e.g. XRP above
229 // STAmount::kMaxNativeN, which would otherwise throw.
230 bool const fix350Enabled = ctx.view.rules().enabled(fixCleanup3_5_0);
231 for (auto const& field : getValueFields())
232 {
233 if (auto const value = tx[field]; value &&
234 ((fix350Enabled && !isRepresentable(asset, *value)) ||
235 STAmount{asset, *value} != *value ||
237 !isOnVaultBaseGrid(asset, *value, getVaultBaseScale(sleVault)))))
238 {
239 JLOG(ctx.j.warn()) << field.f->getName() << " (" << *value
240 << ") can not be represented as a(n) " << to_string(asset) << ".";
241 return tecPRECISION_LOSS;
242 }
243 }
244
245 return tesSUCCESS;
246}
247
248TER
250{
251 auto const& tx = ctx_.tx;
252 auto& view = ctx_.view();
253
254 if (auto const brokerID = tx[~sfLoanBrokerID])
255 {
256 // Modify an existing LoanBroker
257 auto const broker = view.peek(keylet::loanBroker(*brokerID));
258 if (!broker)
259 {
260 // This should be impossible
261 // LCOV_EXCL_START
262 JLOG(j_.fatal()) << "LoanBroker does not exist.";
263 return tefBAD_LEDGER;
264 // LCOV_EXCL_STOP
265 }
266
267 auto const vault = view.read(keylet::vault(broker->at(sfVaultID)));
268 if (!vault)
269 return tecINTERNAL; // LCOV_EXCL_LINE
270
271 auto const vaultAsset = vault->at(sfAsset);
272
273 if (auto const data = tx[~sfData])
274 broker->at(sfData) = *data;
275 if (auto const debtMax = tx[~sfDebtMaximum])
276 broker->at(sfDebtMaximum) = *debtMax;
277
278 if (auto const domainID = tx[~sfDomainID])
279 {
280 if (*domainID != beast::kZero)
281 {
282 broker->setFieldH256(sfDomainID, *domainID);
283 }
284 else if (broker->isFieldPresent(sfDomainID))
285 {
286 broker->makeFieldAbsent(sfDomainID);
287 }
288 }
289
290 view.update(broker);
291
292 associateAsset(*broker, vaultAsset);
293 }
294 else
295 {
296 // Create a new LoanBroker pointing back to the given Vault
297 auto const vaultID = tx[sfVaultID];
298 auto const sleVault = view.read(keylet::vault(vaultID));
299 if (!sleVault)
300 {
301 // This should be impossible
302 // LCOV_EXCL_START
303 JLOG(j_.fatal()) << "Vault does not exist.";
304 return tefBAD_LEDGER;
305 // LCOV_EXCL_STOP
306 }
307 auto const vaultPseudoID = sleVault->at(sfAccount);
308 auto const vaultAsset = sleVault->at(sfAsset);
309 auto const sequence = tx.getSeqProxy();
310
311 auto const owner = view.peek(keylet::account(accountID_));
312 if (!owner)
313 {
314 // This should be impossible
315 // LCOV_EXCL_START
316 JLOG(j_.fatal()) << "Account does not exist.";
317 return tefBAD_LEDGER;
318 // LCOV_EXCL_STOP
319 }
320 auto const broker = std::make_shared<SLE>(keylet::loanBroker(accountID_, sequence));
321
322 if (auto const ter = dirLink(view, accountID_, broker))
323 return ter; // LCOV_EXCL_LINE
324 if (auto const ter = dirLink(view, vaultPseudoID, broker, sfVaultNode))
325 return ter; // LCOV_EXCL_LINE
326
327 // Increases the owner count by two: one for the LoanBroker object, and
328 // one for the pseudo-account.
329 increaseOwnerCount(view, owner, {}, 2, j_);
330 if (preFeeBalance_ < accountReserve(view, owner, j_))
332
333 auto maybePseudo = createPseudoAccount(view, broker->key(), sfLoanBrokerID);
334 if (!maybePseudo)
335 return maybePseudo.error(); // LCOV_EXCL_LINE
336 auto const& pseudo = *maybePseudo;
337 AccountID const pseudoId = pseudo->at(sfAccount);
338
339 if (auto ter = addEmptyHolding(
340 ctx_.getApplyViewContext(), pseudoId, preFeeBalance_, sleVault->at(sfAsset), j_))
341 return ter;
342
343 // Initialize data fields:
344 broker->at(sfSequence) = sequence.value();
345 broker->at(sfVaultID) = vaultID;
346 broker->at(sfOwner) = accountID_;
347 broker->at(sfAccount) = pseudoId;
348 // The LoanSequence indexes loans created by this broker, starting at 1
349 broker->at(sfLoanSequence) = 1;
350 if (auto const data = tx[~sfData])
351 broker->at(sfData) = *data;
352 if (auto const rate = tx[~sfManagementFeeRate])
353 broker->at(sfManagementFeeRate) = *rate;
354 if (auto const debtMax = tx[~sfDebtMaximum])
355 broker->at(sfDebtMaximum) = *debtMax;
356 if (auto const coverMin = tx[~sfCoverRateMinimum])
357 broker->at(sfCoverRateMinimum) = *coverMin;
358 if (auto const coverLiq = tx[~sfCoverRateLiquidation])
359 broker->at(sfCoverRateLiquidation) = *coverLiq;
360
361 if (tx.isFlag(tfLoanBrokerPrivate))
362 {
363 broker->setFlag(lsfLoanBrokerPrivate);
364 if (auto const domainID = tx[~sfDomainID])
365 broker->setFieldH256(sfDomainID, *domainID);
366 }
367
368 view.insert(broker);
369
370 associateAsset(*broker, vaultAsset);
371 }
372
373 return tesSUCCESS;
374}
375
376void
378{
379 // No transaction-specific invariants yet (future work).
380}
381
382bool
384 STTx const&,
385 TER,
386 XRPAmount,
387 ReadView const&,
388 beast::Journal const&)
389{
390 // No transaction-specific invariants yet (future work).
391 return true;
392}
393
394//------------------------------------------------------------------------------
395
396} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream warn() const
Definition Journal.h:356
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.
static std::uint32_t getFlagsMask(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 std::vector< OptionaledField< STNumber > > const & getValueFields()
TER doApply() override
static bool checkExtraFeatures(PreflightContext const &ctx)
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 bool exists(Keylet const &k) const =0
Determine if a state item exists.
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
static bool validDataLength(std::optional< Slice > const &slice, std::size_t maxLength)
ApplyContext & ctx_
Definition Transactor.h:162
static bool validNumericRange(std::optional< T > value, T max, T min=T{})
Definition Transactor.h:693
T make_shared(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:565
Keylet permissionedDomain(AccountID const &account, SeqProxy const &seq) noexcept
Definition Indexes.cpp:583
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
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool isOnVaultBaseGrid(Asset const &asset, Number const &value, int baseScale)
Returns true iff value is exactly representable both as an STAmount of asset and on the base grid at ...
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
@ tefBAD_LEDGER
Definition TER.h:164
std::expected< SLE::pointer, TER > createPseudoAccount(ApplyView &view, UInt256 const &pseudoOwnerKey, SField const &ownerField)
Create pseudo-account, storing pseudoOwnerKey into ownerField.
TER addEmptyHolding(ApplyViewContext ctx, AccountID const &accountID, XRPAmount priorBalance, MPTIssue const &mptIssue, beast::Journal journal)
void increaseOwnerCount(ApplyView &view, SLE::Ref accountSle, SLE::Ref sponsorSle, std::uint32_t count, beast::Journal j)
Increase owner-count fields when the caller supplies the sponsor.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
constexpr std::size_t kMaxDataPayloadLength
The maximum length of Data payload.
Definition Protocol.h:303
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
int getVaultBaseScale(SLE::ConstRef vault)
Return the Vault's base exponent.
VaultKind getVaultKind(SLE::ConstRef vault)
Resolves the VaultKind of a vault SLE.
bool isRepresentable(Asset const &asset, Number const &value)
Check whether an arbitrary precision Number can be converted to an STAmount of a given Asset without ...
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temINVALID
Definition TER.h:98
@ temMALFORMED
Definition TER.h:75
TER dirLink(ApplyView &view, AccountID const &owner, SLE::pointer const &object, SF_UINT64 const &node=sfOwnerNode)
Definition View.cpp:385
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.
@ tecNO_ENTRY
Definition TER.h:317
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecINTERNAL
Definition TER.h:321
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
@ tecLIMIT_EXCEEDED
Definition TER.h:372
@ 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.
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
constexpr FlagValue tfUniversalMask
Definition TxFlags.h:46
@ tesSUCCESS
Definition TER.h:253
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