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/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/ledger/helpers/CredentialHelpers.h>
8#include <xrpl/ledger/helpers/MPTokenHelpers.h>
9#include <xrpl/ledger/helpers/TokenHelpers.h>
10#include <xrpl/ledger/helpers/VaultHelpers.h>
11#include <xrpl/protocol/Feature.h>
12#include <xrpl/protocol/Indexes.h>
13#include <xrpl/protocol/Issue.h>
14#include <xrpl/protocol/LedgerFormats.h>
15#include <xrpl/protocol/MPTIssue.h>
16#include <xrpl/protocol/Protocol.h>
17#include <xrpl/protocol/SField.h>
18#include <xrpl/protocol/STAmount.h>
19#include <xrpl/protocol/STLedgerEntry.h>
20#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
21#include <xrpl/protocol/STTakesAsset.h>
22#include <xrpl/protocol/STTx.h>
23#include <xrpl/protocol/TER.h>
24#include <xrpl/protocol/XRPAmount.h>
25#include <xrpl/tx/Transactor.h>
26
27#include <optional>
28#include <stdexcept>
29
30namespace xrpl {
31
32[[nodiscard]]
33static STAmount
35{
36 XRPL_ASSERT(vault && vault->getType() == ltVAULT, "xrpl::roundToVaultScale : valid vault sle");
37 XRPL_ASSERT(
38 amount.asset() == vault->at(sfAsset), "xrpl::roundToVaultScale : valid vault asset");
39
40 if (amount.integral())
41 return amount;
42
43 int const postScale = [&]() {
45 return scale(vault->at(sfAssetsTotal) + amount, vault->at(sfAsset));
46 }();
47 return roundToScale(amount, postScale, Number::RoundingMode::Downward);
48}
49
52{
53 if (ctx.tx[sfVaultID] == beast::kZero)
54 {
55 JLOG(ctx.j.debug()) << "VaultDeposit: zero/empty vault ID.";
56 return temMALFORMED;
57 }
58
59 if (ctx.tx[sfAmount] <= beast::kZero)
60 return temBAD_AMOUNT;
61
62 return tesSUCCESS;
63}
64
65TER
67{
68 auto const fix320Enabled = ctx.view.rules().enabled(fixCleanup3_2_0);
69 auto const fix330Enabled = ctx.view.rules().enabled(fixCleanup3_3_0);
70
71 auto const vault = ctx.view.read(keylet::vault(ctx.tx[sfVaultID]));
72 if (!vault)
73 return tecNO_ENTRY;
74
75 if (ctx.view.rules().enabled(featureLendingProtocolV1_1))
76 {
77 auto const phase = getVaultPhase(ctx.view, vault);
78 if (phase == VaultPhase::Investment || phase == VaultPhase::Redemption)
79 {
80 JLOG(ctx.j.debug()) << "VaultDeposit: vault deposit is not allowed in the investment "
81 "or redemption phase.";
82 return tecEXPIRED;
83 }
84 }
85
86 auto const& account = ctx.tx[sfAccount];
87 auto const amount = ctx.tx[sfAmount];
88 auto const vaultAsset = vault->at(sfAsset);
89 if (amount.asset() != vaultAsset)
90 return tecWRONG_ASSET;
91
92 auto const& vaultAccount = vault->at(sfAccount);
93 if (auto ter = canTransfer(ctx.view, vaultAsset, account, vaultAccount); !isTesSuccess(ter))
94 {
95 JLOG(ctx.j.debug()) << "VaultDeposit: vault assets are non-transferable.";
96 return ter;
97 }
98
99 auto const mptIssuanceID = vault->at(sfShareMPTID);
100 auto const vaultShare = MPTIssue(mptIssuanceID);
101 if (vaultShare == amount.asset())
102 {
103 // LCOV_EXCL_START
104 JLOG(ctx.j.error()) << "VaultDeposit: vault shares and assets cannot be same.";
105 return tefINTERNAL;
106 // LCOV_EXCL_STOP
107 }
108
109 auto const sleIssuance = ctx.view.read(keylet::mptokenIssuance(mptIssuanceID));
110 if (!sleIssuance)
111 {
112 // LCOV_EXCL_START
113 JLOG(ctx.j.error()) << "VaultDeposit: missing issuance of vault shares.";
114 return tefINTERNAL;
115 // LCOV_EXCL_STOP
116 }
117
118 if (sleIssuance->isFlag(lsfMPTLocked))
119 {
120 // LCOV_EXCL_START
121 JLOG(ctx.j.error()) << "VaultDeposit: issuance of vault shares is locked.";
122 return tefINTERNAL;
123 // LCOV_EXCL_STOP
124 }
125
126 if (fix330Enabled)
127 {
128 if (auto const ret = checkDepositFreeze(ctx.view, account, vaultAccount, vaultAsset))
129 return ret;
130 }
131 else
132 {
133 // Cannot deposit inside Vault an Asset frozen for the depositor
134 if (isFrozen(ctx.view, account, vaultAsset))
135 return vaultAsset.holds<Issue>() ? tecFROZEN : tecLOCKED;
136
137 // Cannot deposit if the shares of the vault are frozen
138 if (isFrozen(ctx.view, account, vaultShare))
139 return tecLOCKED;
140 }
141
142 if (vault->isFlag(lsfVaultPrivate) && account != vault->at(sfOwner))
143 {
144 auto const maybeDomainID = sleIssuance->at(~sfDomainID);
145 // Since this is a private vault and the account is not its owner, we
146 // perform authorization check based on DomainID read from sleIssuance.
147 // Had the vault shares been a regular MPToken, we would allow
148 // authorization granted by the Issuer explicitly, but Vault uses Issuer
149 // pseudo-account, which cannot grant an authorization.
150 if (maybeDomainID)
151 {
152 // As per validDomain documentation, we suppress tecEXPIRED error
153 // here, so we can delete any expired credentials inside doApply.
154 if (auto const err = credentials::validDomain(ctx.view, *maybeDomainID, account);
155 !isTesSuccess(err) && err != tecEXPIRED)
156 return err;
157 }
158 else
159 {
160 return tecNO_AUTH;
161 }
162 }
163
164 // Source MPToken must exist (if asset is an MPT)
165 if (auto const ter = requireAuth(ctx.view, vaultAsset, account); !isTesSuccess(ter))
166 return ter;
167
168 auto const roundedAmount = fix320Enabled ? roundToVaultScale(amount, vault) : amount;
169
170 if (fix320Enabled && roundedAmount == beast::kZero)
171 {
172 JLOG(ctx.j.warn()) << "VaultDeposit: deposit amount: " << ctx.tx[sfAmount]
173 << " is zero at vault scale";
174 return tecPRECISION_LOSS;
175 }
176
177 auto const accountBalance = accountHolds(
178 ctx.view,
179 account,
180 vaultAsset,
183 ctx.j,
185
186 if (accountBalance < roundedAmount)
188
189 // IOU precision checks
190 if (fix320Enabled && !roundedAmount.integral())
191 {
192 // reject deposits that would canonicalize to a no-op at the depositor's trustline scale.
193 // Skipped for issuer-as-depositor: accountHolds returns (kMaxValue @ kMaxOffset) which
194 // would always trip the predicate.
195 if (account != amount.getIssuer() &&
196 amount.isZeroAtScale(scale(accountBalance, vaultAsset)))
197 {
198 JLOG(ctx.j.warn()) << "VaultDeposit: amount " << amount.getFullText()
199 << " rounds to zero at counterparty trust-line scale";
200 return tecPRECISION_LOSS;
201 }
202 }
203
204 return tesSUCCESS;
205}
206
207TER
209{
210 bool const fix320Enabled = view().rules().enabled(fixCleanup3_2_0);
211 auto const vault = view().peek(keylet::vault(ctx_.tx[sfVaultID]));
212 auto applyViewContext = ctx_.getApplyViewContext();
213 if (!vault)
214 return tefINTERNAL; // LCOV_EXCL_LINE
215 auto const vaultAsset = vault->at(sfAsset);
216
217 // Post-amendment IOU only: round Downward to the AssetsTotal precision so
218 // a sub-ULP tail can't be silently absorbed by one rail and not the other.
219 auto const amount =
220 fix320Enabled ? roundToVaultScale(ctx_.tx[sfAmount], vault) : ctx_.tx[sfAmount];
221
222 // We validated zero-amount in preclaim, if we ended up with zero now, fail hard.
223 if (amount == beast::kZero)
224 {
225 // LCOV_EXCL_START
226 JLOG(j_.error()) << "VaultDeposit: deposit amount: " << ctx_.tx[sfAmount] << " is zero";
227 return tecINTERNAL;
228 // LCOV_EXCL_STOP
229 }
230
231 // Make sure the depositor can hold shares.
232 auto const mptIssuanceID = (*vault)[sfShareMPTID];
233 auto const sleIssuance = view().read(keylet::mptokenIssuance(mptIssuanceID));
234 if (!sleIssuance)
235 {
236 // LCOV_EXCL_START
237 JLOG(j_.error()) << "VaultDeposit: missing issuance of vault shares.";
238 return tefINTERNAL;
239 // LCOV_EXCL_STOP
240 }
241
242 auto const& vaultAccount = vault->at(sfAccount);
243 // Note, vault owner is always authorized
244 if (vault->isFlag(lsfVaultPrivate) && accountID_ != vault->at(sfOwner))
245 {
246 if (auto const err = enforceMPTokenAuthorization(
247 applyViewContext, mptIssuanceID, accountID_, preFeeBalance_, j_);
248 !isTesSuccess(err))
249 return err;
250 }
251 else // !vault->isFlag(lsfVaultPrivate) || accountID_ == vault->at(sfOwner)
252 {
253 // No authorization needed, but must ensure there is MPToken
254 if (!view().exists(keylet::mptoken(mptIssuanceID, accountID_)))
255 {
256 if (auto const err = authorizeMPToken(
257 applyViewContext,
259 mptIssuanceID->value(),
261 ctx_.journal);
262 !isTesSuccess(err))
263 return err;
264 }
265
266 // If the vault is private, set the authorized flag for the vault owner
267 if (vault->isFlag(lsfVaultPrivate))
268 {
269 // This follows from the reverse of the outer enclosing if condition
270 XRPL_ASSERT(
271 accountID_ == vault->at(sfOwner), "xrpl::VaultDeposit::doApply : account is owner");
272 if (auto const err = authorizeMPToken(
273 applyViewContext,
274 preFeeBalance_, // priorBalance
275 mptIssuanceID->value(), // mptIssuanceID
276 sleIssuance->at(sfIssuer), // account
277 ctx_.journal,
278 {}, // flags
279 accountID_ // holderID
280 );
281 !isTesSuccess(err))
282 return err;
283 }
284 }
285
286 STAmount sharesCreated = {vault->at(sfShareMPTID)}, assetsDeposited;
287 try
288 {
289 // Compute exchange before transferring any amounts.
290 {
291 auto const maybeShares = assetsToSharesDeposit(vault, sleIssuance, amount);
292 if (!maybeShares)
293 return tecINTERNAL; // LCOV_EXCL_LINE
294 sharesCreated = *maybeShares;
295 }
296 if (sharesCreated == beast::kZero)
297 return tecPRECISION_LOSS;
298
299 auto const maybeAssets = sharesToAssetsDeposit(vault, sleIssuance, sharesCreated);
300 if (!maybeAssets)
301 {
302 return tecINTERNAL; // LCOV_EXCL_LINE
303 }
304 if (*maybeAssets > amount)
305 {
306 // LCOV_EXCL_START
307 JLOG(j_.error()) << "VaultDeposit: would take more than offered.";
308 return tecINTERNAL;
309 // LCOV_EXCL_STOP
310 }
311 assetsDeposited = *maybeAssets;
312 }
313 catch (std::overflow_error const&)
314 {
315 // It's easy to hit this exception from Number with large enough Scale
316 // so we avoid spamming the log and only use debug here.
317 JLOG(j_.debug()) //
318 << "VaultDeposit: overflow error with"
319 << " scale=" << (int)vault->at(sfScale).value() //
320 << ", assetsTotal=" << vault->at(sfAssetsTotal).value()
321 << ", sharesTotal=" << sleIssuance->at(sfOutstandingAmount) << ", amount=" << amount;
322 return tecPATH_DRY;
323 }
324
325 XRPL_ASSERT(
326 sharesCreated.asset() != assetsDeposited.asset(),
327 "xrpl::VaultDeposit::doApply : assets are not shares");
328
329 vault->at(sfAssetsTotal) += assetsDeposited;
330 vault->at(sfAssetsAvailable) += assetsDeposited;
331 view().update(vault);
332
333 // A deposit must not push the vault over its limit.
334 auto const maximum = *vault->at(sfAssetsMaximum);
335 if (maximum != 0 && *vault->at(sfAssetsTotal) > maximum)
336 return tecLIMIT_EXCEEDED;
337
338 // Transfer assets from depositor to vault.
339 if (auto const ter = accountSend(
340 view(), accountID_, vaultAccount, assetsDeposited, j_, {}, WaiveTransferFee::Yes);
341 !isTesSuccess(ter))
342 return ter;
343
344 // This check is wrong. Disable it with fixCleanup3_2_0.
345 // For XRP and MPT the predicate is structurally unsatisfiable: xrpLiquid clamps at zero, and
346 // MPT balances are unsigned. For IOUs it only fires when the deposit drove the depositor's
347 // trust line into debt the exact case preclaim authorizes via SpendableHandling::FullBalance.
348 // The check thus converts a preclaim- authorized deposit into tefINTERNAL after the asset
349 // transfer.
350 if (!fix320Enabled)
351 {
352 // Sanity check
353 if (accountHolds(
354 view(),
356 assetsDeposited.asset(),
359 j_) < beast::kZero)
360 {
361 JLOG(j_.error()) << "VaultDeposit: negative balance of account assets.";
362 return tefINTERNAL;
363 }
364 }
365
366 // Transfer shares from vault to depositor.
367 if (auto const ter = accountSend(
368 view(), vaultAccount, accountID_, sharesCreated, j_, {}, WaiveTransferFee::Yes);
369 !isTesSuccess(ter))
370 return ter;
371
372 associateAsset(*vault, vaultAsset);
373
374 return tesSUCCESS;
375}
376
377void
379{
380 // No transaction-specific invariants yet (future work).
381}
382
383bool
385 STTx const&,
386 TER,
387 XRPAmount,
388 ReadView const&,
389 beast::Journal const&)
390{
391 // No transaction-specific invariants yet (future work).
392 return true;
393}
394
395} // 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:180
bool integral() const noexcept
Definition STAmount.h:465
Asset const & asset() const
Definition STAmount.h:496
std::shared_ptr< STLedgerEntry const > const & const_ref
beast::Journal const j_
Definition Transactor.h:155
ApplyView & view()
Definition Transactor.h:175
AccountID const accountID_
Definition Transactor.h:157
XRPAmount preFeeBalance_
Definition Transactor.h:158
ApplyContext & ctx_
Definition Transactor.h:153
TER doApply() override
static TER preclaim(PreclaimContext const &ctx)
void visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override
Inspect a single ledger entry modified by this transaction.
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)
constexpr Zero kZero
Definition Zero.h:30
TER validDomain(ReadView const &view, uint256 domainID, AccountID const &subject)
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:561
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:543
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:537
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 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.
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.
VaultPhase getVaultPhase(ReadView const &view, SLE::const_ref vault)
Returns the current lifecycle phase of a vault.
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:165
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:607
std::optional< STAmount > sharesToAssetsDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const &shares)
From the perspective of a vault, return the number of assets to take from depositor when they receive...
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
bool isTesSuccess(TER x) noexcept
Definition TER.h:676
TERSubset< CanCvtToTER > TER
Definition TER.h:647
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:363
@ tecLOCKED
Definition TER.h:361
@ tecNO_ENTRY
Definition TER.h:309
@ tecPATH_DRY
Definition TER.h:297
@ tecNO_AUTH
Definition TER.h:303
@ tecINTERNAL
Definition TER.h:313
@ tecFROZEN
Definition TER.h:306
@ tecINSUFFICIENT_FUNDS
Definition TER.h:328
@ tecEXPIRED
Definition TER.h:317
@ tecPRECISION_LOSS
Definition TER.h:366
@ tecLIMIT_EXCEEDED
Definition TER.h:364
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:245
std::optional< STAmount > assetsToSharesDeposit(SLE::const_ref vault, SLE::const_ref issuance, STAmount const &assets)
From the perspective of a vault, return the number of shares to give depositor when they offer a fixe...
static STAmount roundToVaultScale(STAmount const &amount, SLE::const_ref vault)
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:83
ReadView const & view
Definition Transactor.h:86
beast::Journal const j
Definition Transactor.h:91
State information when preflighting a tx.
Definition Transactor.h:38
beast::Journal const j
Definition Transactor.h:45