xrpld
Loading...
Searching...
No Matches
VaultDeposit.cpp
1#include <xrpl/tx/transactors/vault/VaultDeposit.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Journal.h>
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/ledger/ReadView.h>
9#include <xrpl/ledger/helpers/MPTokenHelpers.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/Feature.h>
14#include <xrpl/protocol/Indexes.h>
15#include <xrpl/protocol/Issue.h>
16#include <xrpl/protocol/LedgerFormats.h>
17#include <xrpl/protocol/MPTIssue.h>
18#include <xrpl/protocol/Protocol.h>
19#include <xrpl/protocol/SField.h>
20#include <xrpl/protocol/STAmount.h>
21#include <xrpl/protocol/STLedgerEntry.h>
22#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
23#include <xrpl/protocol/STTakesAsset.h>
24#include <xrpl/protocol/STTx.h>
25#include <xrpl/protocol/TER.h>
26#include <xrpl/protocol/XRPAmount.h>
27#include <xrpl/tx/Transactor.h>
28
29#include <optional>
30#include <stdexcept>
31
32namespace xrpl {
33
34[[nodiscard]]
35static STAmount
37{
38 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::roundToVaultScale : valid vault sle");
39 XRPL_ASSERT(
40 amount.asset() == vault->at(sfAsset), "xrpl::roundToVaultScale : valid vault asset");
41
42 if (amount.integral())
43 return amount;
44
45 int const postScale = [&]() {
47 return scale(vault->at(sfAssetsTotal) + amount, vault->at(sfAsset));
48 }();
49 return roundToScale(amount, postScale, Number::RoundingMode::Downward);
50}
51
52// True if debiting `assets` would leave the depositor's balance where it started, so the deposit
53// would mint shares against a transfer that never happened. Asking the balance directly whether it
54// notices the debit avoids having to infer the rounding step: it has to be the stored balance that
55// answers, because that magnitude is what governs the rounding, and it is not the same as the
56// spendable amount, which also counts what the counterparty's limit allows.
57[[nodiscard]]
58static bool
60 ReadView const& view,
61 AccountID const& account,
62 STAmount const& assets,
64{
65 if (assets.integral())
66 return false;
67
68 auto const balance = accountHolds(
69 view,
70 account,
71 assets.asset(),
74 j,
76
77 if (balance - assets != balance)
78 return false;
79
80 JLOG(j.warn()) << "VaultDeposit: amount " << assets.getFullText()
81 << " leaves the depositor's balance " << balance.getFullText() << " unchanged";
82 return true;
83}
84
87{
88 if (ctx.tx[sfVaultID] == beast::kZero)
89 {
90 JLOG(ctx.j.debug()) << "VaultDeposit: zero/empty vault ID.";
91 return temMALFORMED;
92 }
93
94 if (ctx.tx[sfAmount] <= beast::kZero)
95 return temBAD_AMOUNT;
96
97 return tesSUCCESS;
98}
99
100TER
102{
103 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
104 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
105
106 auto const vault = ctx.view.read(keylet::vault(ctx.tx[sfVaultID]));
107 if (!vault)
108 return tecNO_ENTRY;
109
110 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
111 {
112 auto const phase = getVaultPhase(ctx.view, vault);
113 if (phase == VaultPhase::Investment || phase == VaultPhase::Redemption)
114 {
115 JLOG(ctx.j.debug()) << "VaultDeposit: vault deposit is not allowed in the investment "
116 "or redemption phase.";
117 return tecEXPIRED;
118 }
119 }
120
121 auto const& account = ctx.tx[sfAccount];
122 auto const amount = ctx.tx[sfAmount];
123 auto const vaultAsset = vault->at(sfAsset);
124 if (amount.asset() != vaultAsset)
125 return tecWRONG_ASSET;
126
127 auto const& vaultAccount = vault->at(sfAccount);
128 if (auto ter = canTransfer(ctx.view, vaultAsset, account, vaultAccount); !isTesSuccess(ter))
129 {
130 JLOG(ctx.j.debug()) << "VaultDeposit: vault assets are non-transferable.";
131 return ter;
132 }
133
134 auto const mptIssuanceID = vault->at(sfShareMPTID);
135 auto const vaultShare = MPTIssue(mptIssuanceID);
136 if (vaultShare == amount.asset())
137 {
138 // LCOV_EXCL_START
139 JLOG(ctx.j.error()) << "VaultDeposit: vault shares and assets cannot be same.";
140 return tefINTERNAL;
141 // LCOV_EXCL_STOP
142 }
143
144 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(mptIssuanceID));
145 if (!sleIssuance)
146 {
147 // LCOV_EXCL_START
148 JLOG(ctx.j.error()) << "VaultDeposit: missing issuance of vault shares.";
149 return tefINTERNAL;
150 // LCOV_EXCL_STOP
151 }
152
153 if (sleIssuance->isFlag(lsfMPTLocked))
154 {
155 // LCOV_EXCL_START
156 JLOG(ctx.j.error()) << "VaultDeposit: issuance of vault shares is locked.";
157 return tefINTERNAL;
158 // LCOV_EXCL_STOP
159 }
160
161 if (fix330Enabled)
162 {
163 if (auto const ret = checkDepositFreeze(ctx.view, account, vaultAccount, vaultAsset))
164 return ret;
165 }
166 else
167 {
168 // Cannot deposit inside Vault an Asset frozen for the depositor
169 if (isFrozen(ctx.view, account, vaultAsset))
170 return vaultAsset.holds<Issue>() ? tecFROZEN : tecLOCKED;
171
172 // Cannot deposit if the shares of the vault are frozen
173 if (isFrozen(ctx.view, account, vaultShare))
174 return tecLOCKED;
175 }
176
177 // The vault owner is authorized to deposit unconditionally. An expired
178 // credential is tolerated here because doApply deletes it.
179 if (vault->isFlag(lsfVaultPrivate) && account != vault->at(sfOwner))
180 {
181 if (auto const err = checkVaultDomain(ctx.view, sleIssuance, account, SuppressExpired::Yes);
182 !isTesSuccess(err))
183 return err;
184 }
185
186 // Source MPToken must exist (if asset is an MPT)
187 if (auto const ter = requireAuth(ctx.view, vaultAsset, account); !isTesSuccess(ter))
188 return ter;
189
190 auto const roundedAmount = fix320Enabled ? roundToVaultScale(amount, vault) : amount;
191
192 if (fix320Enabled && roundedAmount == beast::kZero)
193 {
194 JLOG(ctx.j.warn()) << "VaultDeposit: deposit amount: " << ctx.tx[sfAmount]
195 << " is zero at vault scale";
196 return tecPRECISION_LOSS;
197 }
198
199 auto const accountBalance = accountHolds(
200 ctx.view,
201 account,
202 vaultAsset,
205 ctx.j,
207
208 if (accountBalance < roundedAmount)
210
211 // IOU precision checks
212 if (fix320Enabled && !roundedAmount.integral())
213 {
214 // reject deposits that would canonicalize to a no-op at the depositor's trustline scale.
215 // Skipped for issuer-as-depositor: accountHolds returns (kMaxValue @ kMaxOffset) which
216 // would always trip the predicate.
217 if (account != amount.getIssuer() &&
218 amount.isZeroAtScale(scale(accountBalance, vaultAsset)))
219 {
220 JLOG(ctx.j.warn()) << "VaultDeposit: amount " << amount.getFullText()
221 << " rounds to zero at counterparty trust-line scale";
222 return tecPRECISION_LOSS;
223 }
224 }
225
226 return tesSUCCESS;
227}
228
229TER
231{
232 bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0);
233 bool const fix340Enabled = view().rules().enabled(fixCleanup3_4_0);
234 auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
235 auto applyViewContext = ctx_.getApplyViewContext();
236 if (!vault)
237 return tefINTERNAL; // LCOV_EXCL_LINE
238 auto const vaultAsset = vault->at(sfAsset);
239
240 // Post-amendment IOU only: round Downward to the AssetsTotal precision so
241 // a sub-ULP tail can't be silently absorbed by one rail and not the other.
242 auto const amount =
243 fix320Enabled ? roundToVaultScale(ctx_.tx[sfAmount], vault) : ctx_.tx[sfAmount];
244
245 // We validated zero-amount in preclaim, if we ended up with zero now, fail hard.
246 if (amount == beast::kZero)
247 {
248 // LCOV_EXCL_START
249 JLOG(j_.error()) << "VaultDeposit: deposit amount: " << ctx_.tx[sfAmount] << " is zero";
250 return tecINTERNAL;
251 // LCOV_EXCL_STOP
252 }
253
254 // Make sure the depositor can hold shares.
255 auto const mptIssuanceID = (*vault)[sfShareMPTID];
256 auto const sleIssuance = view().read(keylet::mptokenIssuance(mptIssuanceID));
257 if (!sleIssuance)
258 {
259 // LCOV_EXCL_START
260 JLOG(j_.error()) << "VaultDeposit: missing issuance of vault shares.";
261 return tefINTERNAL;
262 // LCOV_EXCL_STOP
263 }
264
265 auto const& vaultAccount = vault->at(sfAccount);
266 // Note, vault owner is always authorized
267 if (vault->isFlag(lsfVaultPrivate) && accountID_ != vault->at(sfOwner))
268 {
269 if (auto const err = enforceMPTokenAuthorization(
270 applyViewContext, mptIssuanceID, accountID_, preFeeBalance_, j_);
271 !isTesSuccess(err))
272 return err;
273 }
274 else // !vault->isFlag(lsfVaultPrivate) || accountID_ == vault->at(sfOwner)
275 {
276 // No authorization needed, but must ensure there is MPToken
277 if (!view().exists(keylet::mptoken(mptIssuanceID, accountID_)))
278 {
279 if (auto const err = authorizeMPToken(
280 applyViewContext,
282 mptIssuanceID->value(),
284 ctx_.journal);
285 !isTesSuccess(err))
286 return err;
287 }
288
289 // If the vault is private, set the authorized flag for the vault owner
290 if (vault->isFlag(lsfVaultPrivate))
291 {
292 // This follows from the reverse of the outer enclosing if condition
293 XRPL_ASSERT(
294 accountID_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner");
295 if (auto const err = authorizeMPToken(
296 applyViewContext,
297 preFeeBalance_, // priorBalance
298 mptIssuanceID->value(), // mptIssuanceID
299 sleIssuance->at(sfIssuer), // account
300 ctx_.journal,
301 {}, // flags
302 accountID_ // holderID
303 );
304 !isTesSuccess(err))
305 return err;
306 }
307 }
308
309 STAmount sharesCreated = {vault->at(sfShareMPTID)}, assetsDeposited;
310
311 // Number arithmetic can throw overflow_error when Scale and totals are large. Caught below.
312 try
313 {
314 // Compute exchange before transferring any amounts.
315 {
316 auto const maybeShares = assetsToSharesDeposit(vault, sleIssuance, amount);
317 if (!maybeShares)
318 return tecINTERNAL; // LCOV_EXCL_LINE
319 sharesCreated = *maybeShares;
320 }
321
322 if (sharesCreated == beast::kZero)
323 return tecPRECISION_LOSS;
324
325 // Convert shares back to assets so the depositor is debited for the amount actually minted.
326 // The truncated share count is worth <= amount; without this the difference would be
327 // credited to the vault for free.
328 auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated);
329 if (!maybeAssets)
330 {
331 return tecINTERNAL; // LCOV_EXCL_LINE
332 }
333 // The round-trip must never return more than the original amount. If it does, a conversion
334 // helper is broken. Reject rather than overcharge the depositor.
335 if (*maybeAssets > amount)
336 {
337 // LCOV_EXCL_START
338 JLOG(j_.error()) << "VaultDeposit: would take more than offered.";
339 return tecINTERNAL;
340 // LCOV_EXCL_STOP
341 }
342 assetsDeposited = *maybeAssets;
343
344 // Post-fixCleanup3_4_0: round the deposit to the sfAssetsTotal scale so all accounting
345 // fields (trust line / MPT, sfAssetsAvailable, sfAssetsTotal) change by the same
346 // representable delta.
347 if (fix340Enabled)
348 {
349 // Round down at the posterior sfAssetsTotal scale so the vault is credited by no more
350 // than the depositor paid. Keep the share count from the first round trip: the clamp
351 // only drops a last digit of the new total. Converting the clamped amount back to
352 // shares would mint fewer shares while still charging the N-share debit.
353 auto const maybeClamped = clampToAssetsTotalScale(vault, assetsDeposited);
354 if (!maybeClamped)
355 return maybeClamped.error();
356 assetsDeposited = *maybeClamped;
357
358 // The actual deposit amount is truncated to whole shares, converted back to assets,
359 // and clamped to the sfAssetsTotal scale (post-fixCleanup3_4_0). Check the depositor's
360 // balance here—after clamping—before making any state changes.
361 if (roundsToZeroForDepositor(view(), accountID_, assetsDeposited, j_))
362 return tecPRECISION_LOSS;
363 }
364 }
365 catch (std::overflow_error const&)
366 {
367 // It's easy to hit this exception from Number with large enough Scale
368 // so we avoid spamming the log and only use debug here.
369 JLOG(j_.debug()) //
370 << "VaultDeposit: overflow error with"
371 << " scale=" << (int)vault->at(sfScale).value() //
372 << ", assetsTotal=" << vault->at(sfAssetsTotal).value()
373 << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) << ", amount=" << amount;
374 return tecPATH_DRY;
375 }
376
377 XRPL_ASSERT(
378 sharesCreated.asset() != assetsDeposited.asset(),
379 "xrpl::VaultDeposit::doApply : assets are not shares");
380
381 vault->at(sfAssetsTotal) += assetsDeposited;
382 vault->at(sfAssetsAvailable) += assetsDeposited;
383 view().update(vault);
384
385 // A deposit must not push the vault over its limit.
386 auto const maximum = *vault->at(sfAssetsMaximum);
387 if (maximum != 0 && *vault->at(sfAssetsTotal) > maximum)
388 return tecLIMIT_EXCEEDED;
389
390 // Transfer assets from depositor to vault.
391 if (auto const ter = accountSend(
392 view(), accountID_, vaultAccount, assetsDeposited, j_, {}, WaiveTransferFee::Yes);
393 !isTesSuccess(ter))
394 return ter;
395
396 // This check is wrong. Disable it with fixCleanup3_2_0.
397 // For XRP and MPT the predicate is structurally unsatisfiable: xrpLiquid clamps at zero, and
398 // MPT balances are unsigned. For IOUs it only fires when the deposit drove the depositor's
399 // trust line into debt the exact case preclaim authorizes via SpendableHandling::FullBalance.
400 // The check thus converts a preclaim- authorized deposit into tefINTERNAL after the asset
401 // transfer.
402 if (!fix320Enabled)
403 {
404 // Sanity check
405 if (accountHolds(
406 view(),
408 assetsDeposited.asset(),
411 j_) < beast::kZero)
412 {
413 JLOG(j_.error()) << "VaultDeposit: negative balance of account assets.";
414 return tefINTERNAL;
415 }
416 }
417
418 // Transfer shares from vault to depositor.
419 if (auto const ter = accountSend(
420 view(), vaultAccount, accountID_, sharesCreated, j_, {}, WaiveTransferFee::Yes);
421 !isTesSuccess(ter))
422 return ter;
423
424 associateAsset(*vault, vaultAsset);
425
426 return tesSUCCESS;
427}
428
429void
431{
432 // No transaction-specific invariants yet (future work).
433}
434
435bool
437 STTx const&,
438 TER,
439 XRPAmount,
440 ReadView const&,
441 beast::Journal const&)
442{
443 // No transaction-specific invariants yet (future work).
444 return true;
445}
446
447} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
Stream debug() const
Definition Journal.h:344
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
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::string getFullText() const override
Definition STAmount.cpp:637
bool integral() const noexcept
Definition STAmount.h:465
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry const > const & ConstRef
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
TER doApply() override
static TER preclaim(PreclaimContext 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.
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)
constexpr Zero kZero
Definition Zero.h:30
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:591
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:573
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:567
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
TER enforceMPTokenAuthorization(ApplyViewContext ctx, MPTID const &mptIssuanceID, AccountID const &account, XRPAmount const &priorBalance, beast::Journal j)
Enforce account has MPToken to match its authorization.
TER checkVaultDomain(ReadView const &view, SLE::ConstRef issuance, AccountID const &subject, SuppressExpired suppressExpired)
Checks that subject belongs to the permissioned domain governing a vault's shares.
TER checkDepositFreeze(ReadView const &view, AccountID const &srcAcct, AccountID const &pseudoAcct, Asset const &asset)
Checks freeze compliance for depositing an asset into a pseudo-account (e.g.
std::optional< STAmount > sharesToAssetsDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &shares)
From the perspective of a vault, return the number of assets to take from depositor when they receive...
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:794
@ tefINTERNAL
Definition TER.h:168
static bool roundsToZeroForDepositor(ReadView const &view, AccountID const &account, STAmount const &assets, beast::Journal j)
std::expected< STAmount, TER > clampToAssetsTotalScale(SLE::ConstRef vault, STAmount const &delta)
Adjusts a requested asset change (delta) to match the decimal scale of the updated total vault assets...
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.
STAmount roundToScale(STAmount const &value, std::int32_t scale, Number::RoundingMode rounding=Number::getround())
Round an arbitrary precision Amount to the precision of an STAmount that has a given exponent.
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:614
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::optional< STAmount > assetsToSharesDeposit(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &assets)
From the perspective of a vault, return the number of shares to give depositor when they offer a fixe...
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
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.
static STAmount roundToVaultScale(STAmount const &amount, SLE::ConstRef vault)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ 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 authorizeMPToken(ApplyViewContext ctx, XRPAmount const &priorBalance, MPTID const &mptIssuanceID, AccountID const &account, beast::Journal journal, std::uint32_t flags=0, std::optional< AccountID > holderID=std::nullopt)
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
@ tecLOCKED
Definition TER.h:366
@ tecNO_ENTRY
Definition TER.h:314
@ tecPATH_DRY
Definition TER.h:302
@ tecINTERNAL
Definition TER.h:318
@ tecFROZEN
Definition TER.h:311
@ tecINSUFFICIENT_FUNDS
Definition TER.h:333
@ tecEXPIRED
Definition TER.h:322
@ tecPRECISION_LOSS
Definition TER.h:371
@ tecLIMIT_EXCEEDED
Definition TER.h:369
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
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
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