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// True if debiting `assets` would leave the depositor's balance where it started, so the deposit
35// would mint shares against a transfer that never happened. Asking the balance directly whether it
36// notices the debit avoids having to infer the rounding step: it has to be the stored balance that
37// answers, because that magnitude is what governs the rounding, and it is not the same as the
38// spendable amount, which also counts what the counterparty's limit allows.
39[[nodiscard]]
40static bool
42 ReadView const& view,
43 AccountID const& account,
44 STAmount const& assets,
46{
47 if (assets.integral())
48 return false;
49
50 auto const balance = accountHolds(
51 view,
52 account,
53 assets.asset(),
56 j,
58
59 if (balance - assets != balance)
60 return false;
61
62 JLOG(j.warn()) << "VaultDeposit: amount " << assets.getFullText()
63 << " leaves the depositor's balance " << balance.getFullText() << " unchanged";
64 return true;
65}
66
69{
70 if (ctx.tx[sfVaultID] == beast::kZero)
71 {
72 JLOG(ctx.j.debug()) << "VaultDeposit: zero/empty vault ID.";
73 return temMALFORMED;
74 }
75
76 if (ctx.tx[sfAmount] <= beast::kZero)
77 return temBAD_AMOUNT;
78
79 return tesSUCCESS;
80}
81
82TER
84{
85 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
86 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
87
88 auto const vault = ctx.view.read(keylet::vault(ctx.tx[sfVaultID]));
89 if (!vault)
90 return tecNO_ENTRY;
91
92 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
93 {
94 auto const phase = getVaultPhase(ctx.view, vault);
95 if (phase == VaultPhase::Investment || phase == VaultPhase::Redemption)
96 {
97 JLOG(ctx.j.debug()) << "VaultDeposit: vault deposit is not allowed in the investment "
98 "or redemption phase.";
99 return tecEXPIRED;
100 }
101 }
102
103 auto const& account = ctx.tx[sfAccount];
104 auto const amount = ctx.tx[sfAmount];
105 auto const vaultAsset = vault->at(sfAsset);
106 if (amount.asset() != vaultAsset)
107 return tecWRONG_ASSET;
108
109 auto const& vaultAccount = vault->at(sfAccount);
110 if (auto ter = canTransfer(ctx.view, vaultAsset, account, vaultAccount); !isTesSuccess(ter))
111 {
112 JLOG(ctx.j.debug()) << "VaultDeposit: vault assets are non-transferable.";
113 return ter;
114 }
115
116 auto const mptIssuanceID = vault->at(sfShareMPTID);
117 auto const vaultShare = MPTIssue(mptIssuanceID);
118 if (vaultShare == amount.asset())
119 {
120 // LCOV_EXCL_START
121 JLOG(ctx.j.error()) << "VaultDeposit: vault shares and assets cannot be same.";
122 return tefINTERNAL;
123 // LCOV_EXCL_STOP
124 }
125
126 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(mptIssuanceID));
127 if (!sleIssuance)
128 {
129 // LCOV_EXCL_START
130 JLOG(ctx.j.error()) << "VaultDeposit: missing issuance of vault shares.";
131 return tefINTERNAL;
132 // LCOV_EXCL_STOP
133 }
134
135 if (sleIssuance->isFlag(lsfMPTLocked))
136 {
137 // LCOV_EXCL_START
138 JLOG(ctx.j.error()) << "VaultDeposit: issuance of vault shares is locked.";
139 return tefINTERNAL;
140 // LCOV_EXCL_STOP
141 }
142
143 if (fix330Enabled)
144 {
145 if (auto const ret = checkDepositFreeze(ctx.view, account, vaultAccount, vaultAsset))
146 return ret;
147 }
148 else
149 {
150 // Cannot deposit inside Vault an Asset frozen for the depositor
151 if (isFrozen(ctx.view, account, vaultAsset))
152 return vaultAsset.holds<Issue>() ? tecFROZEN : tecLOCKED;
153
154 // Cannot deposit if the shares of the vault are frozen
155 if (isFrozen(ctx.view, account, vaultShare))
156 return tecLOCKED;
157 }
158
159 // The vault owner is authorized to deposit unconditionally. An expired
160 // credential is tolerated here because doApply deletes it.
161 if (vault->isFlag(lsfVaultPrivate) && account != vault->at(sfOwner))
162 {
163 if (auto const err = checkVaultDomain(ctx.view, sleIssuance, account, SuppressExpired::Yes);
164 !isTesSuccess(err))
165 return err;
166 }
167
168 // Source MPToken must exist (if asset is an MPT)
169 if (auto const ter = requireAuth(ctx.view, vaultAsset, account); !isTesSuccess(ter))
170 return ter;
171
172 auto const roundedAmount = fix320Enabled
174 : amount;
175
176 if (fix320Enabled && roundedAmount == beast::kZero)
177 {
178 JLOG(ctx.j.warn()) << "VaultDeposit: deposit amount: " << ctx.tx[sfAmount]
179 << " is zero at vault scale";
180 return tecPRECISION_LOSS;
181 }
182
183 auto const accountBalance = accountHolds(
184 ctx.view,
185 account,
186 vaultAsset,
189 ctx.j,
191
192 if (accountBalance < roundedAmount)
194
195 // IOU precision checks
196 if (fix320Enabled && !roundedAmount.integral())
197 {
198 // reject deposits that would canonicalize to a no-op at the depositor's trustline scale.
199 // Skipped for issuer-as-depositor: accountHolds returns (kMaxValue @ kMaxOffset) which
200 // would always trip the predicate.
201 if (account != amount.getIssuer() &&
202 amount.isZeroAtScale(scale(accountBalance, vaultAsset)))
203 {
204 JLOG(ctx.j.warn()) << "VaultDeposit: amount " << amount.getFullText()
205 << " rounds to zero at counterparty trust-line scale";
206 return tecPRECISION_LOSS;
207 }
208 }
209
210 return tesSUCCESS;
211}
212
213TER
215{
216 bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0);
217 bool const fix340Enabled = view().rules().enabled(fixCleanup3_4_0);
218 auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
219 auto const applyViewContext = ctx_.getApplyViewContext();
220 if (!vault)
221 return tefINTERNAL; // LCOV_EXCL_LINE
222 auto const vaultAsset = vault->at(sfAsset);
223
224 // Post-amendment IOU only: round toward zero to the AssetsTotal precision so
225 // a sub-ULP tail can't be silently absorbed by one rail and not the other.
226 auto const amount = fix320Enabled
228 : ctx_.tx[sfAmount];
229
230 // We validated zero-amount in preclaim, if we ended up with zero now, fail hard.
231 if (amount == beast::kZero)
232 {
233 // LCOV_EXCL_START
234 JLOG(j_.error()) << "VaultDeposit: deposit amount: " << ctx_.tx[sfAmount] << " is zero";
235 return tecINTERNAL;
236 // LCOV_EXCL_STOP
237 }
238
239 // Make sure the depositor can hold shares.
240 auto const mptIssuanceID = (*vault)[sfShareMPTID];
241 auto const sleIssuance = view().read(keylet::mptokenIssuance(mptIssuanceID));
242 if (!sleIssuance)
243 {
244 // LCOV_EXCL_START
245 JLOG(j_.error()) << "VaultDeposit: missing issuance of vault shares.";
246 return tefINTERNAL;
247 // LCOV_EXCL_STOP
248 }
249
250 auto const& vaultAccount = vault->at(sfAccount);
251 // Note, vault owner is always authorized
252 if (vault->isFlag(lsfVaultPrivate) && accountID_ != vault->at(sfOwner))
253 {
254 if (auto const err = enforceMPTokenAuthorization(
255 applyViewContext, mptIssuanceID, accountID_, preFeeBalance_, j_);
256 !isTesSuccess(err))
257 return err;
258 }
259 else // !vault->isFlag(lsfVaultPrivate) || accountID_ == vault->at(sfOwner)
260 {
261 // No authorization needed, but must ensure there is MPToken
262 if (!view().exists(keylet::mptoken(mptIssuanceID, accountID_)))
263 {
264 if (auto const err = authorizeMPToken(
265 applyViewContext,
267 mptIssuanceID->value(),
269 ctx_.journal);
270 !isTesSuccess(err))
271 return err;
272 }
273
274 // If the vault is private, set the authorized flag for the vault owner
275 if (vault->isFlag(lsfVaultPrivate))
276 {
277 // This follows from the reverse of the outer enclosing if condition
278 XRPL_ASSERT(
279 accountID_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner");
280 if (auto const err = authorizeMPToken(
281 applyViewContext,
282 preFeeBalance_, // priorBalance
283 mptIssuanceID->value(), // mptIssuanceID
284 sleIssuance->at(sfIssuer), // account
285 ctx_.journal,
286 {}, // flags
287 accountID_ // holderID
288 );
289 !isTesSuccess(err))
290 return err;
291 }
292 }
293
294 STAmount sharesCreated = {vault->at(sfShareMPTID)}, assetsDeposited;
295
296 // Number arithmetic can throw overflow_error when Scale and totals are large. Caught below.
297 try
298 {
299 // Compute exchange before transferring any amounts.
300 {
301 auto const maybeShares = assetsToSharesDeposit(vault, sleIssuance, amount);
302 if (!maybeShares)
303 return tecINTERNAL; // LCOV_EXCL_LINE
304 sharesCreated = *maybeShares;
305 }
306
307 if (sharesCreated == beast::kZero)
308 return tecPRECISION_LOSS;
309
310 // Convert shares back to assets so the depositor is debited for the amount actually minted.
311 // The truncated share count is worth <= amount; without this the difference would be
312 // credited to the vault for free.
313 auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated);
314 if (!maybeAssets)
315 {
316 return tecINTERNAL; // LCOV_EXCL_LINE
317 }
318 // The round-trip must never return more than the original amount. If it does, a conversion
319 // helper is broken. Reject rather than overcharge the depositor.
320 if (*maybeAssets > amount)
321 {
322 // LCOV_EXCL_START
323 JLOG(j_.error()) << "VaultDeposit: would take more than offered.";
324 return tecINTERNAL;
325 // LCOV_EXCL_STOP
326 }
327 assetsDeposited = *maybeAssets;
328
329 // Post-fixCleanup3_4_0: round the deposit to the sfAssetsTotal scale so all accounting
330 // fields (trust line / MPT, sfAssetsAvailable, sfAssetsTotal) change by the same
331 // representable delta.
332 if (fix340Enabled)
333 {
334 // Round down at the posterior sfAssetsTotal scale so the vault is credited by no more
335 // than the depositor paid. Keep the share count from the first round trip: the clamp
336 // only drops a last digit of the new total. Converting the clamped amount back to
337 // shares would mint fewer shares while still charging the N-share debit.
338 auto const maybeClamped = clampToAssetsTotalScale(vault, assetsDeposited);
339 if (!maybeClamped)
340 return maybeClamped.error();
341 assetsDeposited = *maybeClamped;
342
343 // The actual deposit amount is truncated to whole shares, converted back to assets,
344 // and clamped to the sfAssetsTotal scale (post-fixCleanup3_4_0). Check the depositor's
345 // balance here—after clamping—before making any state changes.
346 if (roundsToZeroForDepositor(view(), accountID_, assetsDeposited, j_))
347 return tecPRECISION_LOSS;
348 }
349 }
350 catch (std::overflow_error const&)
351 {
352 // It's easy to hit this exception from Number with large enough Scale
353 // so we avoid spamming the log and only use debug here.
354 JLOG(j_.debug()) //
355 << "VaultDeposit: overflow error with"
356 << " scale=" << (int)vault->at(sfScale).value() //
357 << ", assetsTotal=" << vault->at(sfAssetsTotal).value()
358 << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) << ", amount=" << amount;
359 return tecPATH_DRY;
360 }
361
362 if (auto const ter = checkOptionalVaultInflow(vault, assetsDeposited); !isTesSuccess(ter))
363 return ter;
364
365 XRPL_ASSERT(
366 sharesCreated.asset() != assetsDeposited.asset(),
367 "xrpl::VaultDeposit::doApply : assets are not shares");
368
369 if (auto const ter = adjustVaultCash(vault, assetsDeposited, j_); !isTesSuccess(ter))
370 return ter; // LCOV_EXCL_LINE
371 view().update(vault);
372
373 // A deposit must not push the vault over its limit.
374 auto const maximum = *vault->at(sfAssetsMaximum);
375 if (maximum != 0 && getAssetsTotal(vault) > maximum)
376 return tecLIMIT_EXCEEDED;
377
378 // Transfer assets from depositor to vault.
379 if (auto const ter = accountSend(
380 view(), accountID_, vaultAccount, assetsDeposited, j_, {}, WaiveTransferFee::Yes);
381 !isTesSuccess(ter))
382 return ter;
383
384 // This check is wrong. Disable it with fixCleanup3_2_0.
385 // For XRP and MPT the predicate is structurally unsatisfiable: xrpLiquid clamps at zero, and
386 // MPT balances are unsigned. For IOUs it only fires when the deposit drove the depositor's
387 // trust line into debt the exact case preclaim authorizes via SpendableHandling::FullBalance.
388 // The check thus converts a preclaim- authorized deposit into tefINTERNAL after the asset
389 // transfer.
390 if (!fix320Enabled)
391 {
392 // Sanity check
393 if (accountHolds(
394 view(),
396 assetsDeposited.asset(),
399 j_) < beast::kZero)
400 {
401 JLOG(j_.error()) << "VaultDeposit: negative balance of account assets.";
402 return tefINTERNAL;
403 }
404 }
405
406 // Transfer shares from vault to depositor.
407 if (auto const ter = accountSend(
408 view(), vaultAccount, accountID_, sharesCreated, j_, {}, WaiveTransferFee::Yes);
409 !isTesSuccess(ter))
410 return ter;
411
412 associateAsset(*vault, vaultAsset);
413
414 return tesSUCCESS;
415}
416
417void
419{
420 // No transaction-specific invariants yet (future work).
421}
422
423bool
425 STTx const&,
426 TER,
427 XRPAmount,
428 ReadView const&,
429 beast::Journal const&)
430{
431 // No transaction-specific invariants yet (future work).
432 return true;
433}
434
435} // 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
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:565
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
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
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:819
@ tefINTERNAL
Definition TER.h:167
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.
TER adjustVaultCash(SLE::Ref vault, STAmount const &delta, beast::Journal j)
Apply a signed cash movement to a Vault of any version.
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::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...
STAmount roundToPosteriorVaultScale(SLE::ConstRef vault, STAmount const &amount, Number::RoundingMode roundingMode)
Round an amount at the Vault's posterior live exponent.
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.
TER checkOptionalVaultInflow(SLE::ConstRef vault, STAmount const &amount)
Check whether amount is an admissible optional inflow.
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:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
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:371
@ tecLOCKED
Definition TER.h:369
@ tecNO_ENTRY
Definition TER.h:317
@ tecPATH_DRY
Definition TER.h:305
@ tecINTERNAL
Definition TER.h:321
@ tecFROZEN
Definition TER.h:314
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecEXPIRED
Definition TER.h:325
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecLIMIT_EXCEEDED
Definition TER.h:372
Number getAssetsTotal(SLE::ConstRef vault)
Return the Vault's current assets total.
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:253
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