xrpld
Loading...
Searching...
No Matches
VaultCreate.cpp
1#include <xrpl/tx/transactors/vault/VaultCreate.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/View.h>
9#include <xrpl/ledger/helpers/AccountRootHelpers.h>
10#include <xrpl/ledger/helpers/MPTokenHelpers.h>
11#include <xrpl/ledger/helpers/TokenHelpers.h>
12#include <xrpl/ledger/helpers/VaultHelpers.h>
13#include <xrpl/protocol/AccountID.h>
14#include <xrpl/protocol/Asset.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/STNumber.h> // IWYU pragma: keep
25#include <xrpl/protocol/STTakesAsset.h>
26#include <xrpl/protocol/STTx.h>
27#include <xrpl/protocol/TER.h>
28#include <xrpl/protocol/TxFlags.h>
29#include <xrpl/protocol/XRPAmount.h>
30#include <xrpl/tx/Transactor.h>
31#include <xrpl/tx/transactors/token/MPTokenIssuanceCreate.h>
32
33#include <cstdint>
34#include <memory>
35#include <optional>
36#include <utility>
37
38namespace xrpl {
39
40bool
42{
43 if (!ctx.rules.enabled(featureMPTokensV1))
44 return false;
45
46 if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDomains))
47 return false;
48
49 if (!ctx.rules.enabled(featureLendingProtocolV1_1) &&
50 (ctx.tx.isFieldPresent(sfVaultKind) || ctx.tx.isFieldPresent(sfSubscriptionDate) ||
51 ctx.tx.isFieldPresent(sfRedemptionDate)))
52 return false;
53
54 return true;
55}
56
59{
60 return tfVaultCreateMask;
61}
62
65{
66 if (!validDataLength(ctx.tx[~sfData], kMaxDataPayloadLength))
67 return temMALFORMED;
68
69 if (auto const withdrawalPolicy = ctx.tx[~sfWithdrawalPolicy])
70 {
71 // Enforce valid withdrawal policy
72 if (*withdrawalPolicy != kVaultStrategyFirstComeFirstServe)
73 return temMALFORMED;
74 }
75
76 if (auto const domain = ctx.tx[~sfDomainID])
77 {
78 if (*domain == beast::kZero)
79 {
80 return temMALFORMED;
81 }
82 if (!ctx.tx.isFlag(tfVaultPrivate))
83 {
84 return temMALFORMED; // DomainID only allowed on private vaults
85 }
86 }
87
88 if (auto const assetMax = ctx.tx[~sfAssetsMaximum])
89 {
90 if (*assetMax < beast::kZero)
91 return temMALFORMED;
92
93 // An AssetsMaximum out of range for the asset, e.g. XRP above
94 // STAmount::kMaxNativeN, would throw when rounded to the asset.
95 if (ctx.rules.enabled(fixCleanup3_5_0) && !isRepresentable(ctx.tx[sfAsset], *assetMax))
96 return temMALFORMED;
97 }
98
99 if (auto const metadata = ctx.tx[~sfMPTokenMetadata])
100 {
101 if (metadata->empty() || metadata->length() > kMaxMpTokenMetadataLength)
102 return temMALFORMED;
103 }
104
105 if (auto const scale = ctx.tx[~sfScale])
106 {
107 auto const vaultAsset = ctx.tx[sfAsset];
108 if (vaultAsset.holds<MPTIssue>() || vaultAsset.native())
109 return temMALFORMED;
110
111 auto const maximumScale = getVaultDefaultVersion(ctx.rules) == VaultVersion::FixedPrecision
114 if (scale > maximumScale)
115 return temMALFORMED;
116 }
117
118 if (!isValidVaultKind(ctx.tx))
119 return temMALFORMED;
120 auto const kind = getVaultKind(ctx.tx);
121 auto const hasSubscription = ctx.tx.isFieldPresent(sfSubscriptionDate);
122 auto const hasRedemption = ctx.tx.isFieldPresent(sfRedemptionDate);
123 auto const isClosedEnded = kind == VaultKind::ClosedEnded;
124 if (!isClosedEnded && (hasSubscription || hasRedemption))
125 return temMALFORMED;
126 if (isClosedEnded)
127 {
128 if (!hasSubscription || !hasRedemption)
129 return temMALFORMED;
130 if (!isValidClosedEndedGap(ctx.tx[sfSubscriptionDate], ctx.tx[sfRedemptionDate]))
131 return temMALFORMED;
132 }
133
134 return tesSUCCESS;
135}
136
137TER
139{
140 auto const vaultAsset = ctx.tx[sfAsset];
141 auto const account = ctx.tx[sfAccount];
142
143 if (auto const ter = canAddHolding(ctx.view, vaultAsset))
144 return ter;
145
146 // Check for pseudo-account issuers - we do not want a vault to hold such
147 // assets (e.g. MPT shares to other vaults or AMM LPTokens) as they would be
148 // impossible to clawback (should the need arise)
149 if (!vaultAsset.native())
150 {
151 if (isPseudoAccount(ctx.view, vaultAsset.getIssuer()))
152 return tecWRONG_ASSET;
153 }
154
155 // Cannot create Vault for an Asset frozen for the vault owner
156 if (isFrozen(ctx.view, account, vaultAsset))
157 return vaultAsset.holds<Issue>() ? tecFROZEN : tecLOCKED;
158
159 if (auto const domain = ctx.tx[~sfDomainID])
160 {
161 auto const sleDomain = ctx.view.read(keylet::permissionedDomain(*domain));
162 if (!sleDomain)
163 return tecOBJECT_NOT_FOUND;
164 }
165
166 auto const sequence = ctx.tx.getSeqProxy();
167 if (auto const accountId = pseudoAccountAddress(ctx.view, keylet::vault(account, sequence).key);
168 accountId == beast::kZero)
170
171 // preflight enforces red >= sub + kMinInvestmentPeriod for closed-ended
172 // vaults, so a past RedemptionDate always implies a strictly-earlier,
173 // equally-past SubscriptionDate. The RedemptionDate arm below is therefore
174 // defensive: it cannot be the sole cause of tecEXPIRED. It is kept to
175 // preserve the invariant locally in case the preflight gap check is ever
176 // weakened.
177 if (hasExpired(ctx.view, ctx.tx[~sfSubscriptionDate]) ||
178 hasExpired(ctx.view, ctx.tx[~sfRedemptionDate]))
179 return tecEXPIRED;
180
181 // FixedPrecision: AssetsMaximum must be exactly representable on the Vault's base grid,
182 // otherwise associateAsset would silently round the cap the owner asked for. Legacy and
183 // CashBasis Vaults keep their existing behavior.
184 if (auto const assetMax = ctx.tx[~sfAssetsMaximum];
186 {
187 int const baseScale =
188 vaultBaseScale(vaultAsset, ctx.tx[~sfScale].value_or(kVaultDefaultIouScale));
189 if (!isOnVaultBaseGrid(vaultAsset, *assetMax, baseScale))
190 {
191 JLOG(ctx.j.debug()) << "VaultCreate: AssetsMaximum " << *assetMax
192 << " is not representable at the Vault scale.";
193 return tecPRECISION_LOSS;
194 }
195 }
196
197 return tesSUCCESS;
198}
199
200TER
202{
203 // All return codes in `doApply` must be `tec`, `ter`, or `tes`.
204 // As we move checks into `preflight` and `preclaim`,
205 // we can consider downgrading them to `tef` or `tem`.
206
207 auto const& tx = ctx_.tx;
208 auto const applyViewContext = ctx_.getApplyViewContext();
209 auto const sequence = tx.getSeqProxy();
210 auto const owner = view().peek(keylet::account(accountID_));
211 if (owner == nullptr)
212 return tefINTERNAL; // LCOV_EXCL_LINE
213
214 auto const vault = std::make_shared<SLE>(keylet::vault(accountID_, sequence));
215
216 if (auto ter = dirLink(view(), accountID_, vault))
217 return ter;
218 // We will create Vault and PseudoAccount, hence increase OwnerCount by 2
219 increaseOwnerCount(view(), owner, {}, 2, j_);
220 if (preFeeBalance_ < accountReserve(view(), owner, j_))
222
223 auto maybePseudo = createPseudoAccount(view(), vault->key(), sfVaultID);
224 if (!maybePseudo)
225 return maybePseudo.error(); // LCOV_EXCL_LINE
226 auto const& pseudo = *maybePseudo;
227 AccountID const pseudoId = pseudo->at(sfAccount);
228 auto const asset = tx[sfAsset];
229
230 if (auto ter = addEmptyHolding(applyViewContext, pseudoId, preFeeBalance_, asset, j_);
231 !isTesSuccess(ter))
232 return ter;
233
234 std::uint8_t const scale = (asset.holds<MPTIssue>() || asset.native())
235 ? 0
236 : ctx_.tx[~sfScale].value_or(kVaultDefaultIouScale);
237
238 std::uint32_t mptFlags = 0;
239 if (!tx.isFlag(tfVaultShareNonTransferable))
240 mptFlags |= (lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer);
241 if (tx.isFlag(tfVaultPrivate))
242 mptFlags |= lsfMPTRequireAuth;
243
244 // Note, here we are **not** creating an MPToken for the assets held in
245 // the vault. That MPToken or TrustLine/RippleState is created above, in
246 // addEmptyHolding. Here we are creating MPTokenIssuance for the shares
247 // in the vault.
248 //
249 // Post-fixCleanup3_2_0: surface the vault pseudo's holding (MPToken
250 // for MPT, RippleState for IOU) on the share via sfReferenceHolding.
251 // XRP underlyings leave it unset.
252 auto const referenceHolding = [&] -> std::optional<UInt256> {
253 if (!view().rules().enabled(fixCleanup3_2_0) || asset.native())
254 return std::nullopt;
255 return asset.holds<MPTIssue>()
256 ? keylet::mptoken(asset.get<MPTIssue>().getMptID(), pseudoId).key
257 : keylet::trustLine(pseudoId, asset.get<Issue>()).key;
258 }();
259 auto const maybeShare = MPTokenIssuanceCreate::create(
260 applyViewContext,
261 j_,
262 {
263 .priorBalance = std::nullopt,
264 .account = pseudoId,
265 .sequence = 1,
266 .flags = mptFlags,
267 .assetScale = scale,
268 .transferFee = std::nullopt,
269 .metadata = tx[~sfMPTokenMetadata],
270 .domainId = tx[~sfDomainID],
271 .referenceHolding = referenceHolding,
272 });
273 if (!maybeShare)
274 return maybeShare.error(); // LCOV_EXCL_LINE
275 auto const& mptIssuanceID = *maybeShare;
276
277 vault->setFieldIssue(sfAsset, STIssue{sfAsset, asset});
278 vault->at(sfFlags) = tx.getFlags() & tfVaultPrivate;
279 vault->at(sfSequence) = sequence.value();
280 vault->at(sfOwner) = accountID_;
281 vault->at(sfAccount) = pseudoId;
282 vault->at(sfAssetsTotal) = Number(0);
283 vault->at(sfAssetsAvailable) = Number(0);
284 vault->at(sfLossUnrealized) = Number(0);
285 // Leave default values for AssetTotal and AssetAvailable, both zero.
286 if (auto value = tx[~sfAssetsMaximum])
287 vault->at(sfAssetsMaximum) = *value;
288 vault->at(sfShareMPTID) = mptIssuanceID;
289 if (auto value = tx[~sfData])
290 vault->at(sfData) = *value;
291 // Required field, default to vaultStrategyFirstComeFirstServe
292 if (auto value = tx[~sfWithdrawalPolicy])
293 {
294 vault->at(sfWithdrawalPolicy) = *value;
295 }
296 else
297 {
298 vault->at(sfWithdrawalPolicy) = kVaultStrategyFirstComeFirstServe;
299 }
300 if (scale != 0u)
301 vault->at(sfScale) = scale;
302 VaultVersion const version = getVaultDefaultVersion(view().rules());
303 if (version == VaultVersion::FixedPrecision)
304 {
305 vault->at(sfLEVersion) = std::to_underlying(VaultVersion::FixedPrecision);
306 vault->at(sfYieldUnrealized) = Number(0);
307 vault->at(sfAssetsDeployed) = Number(0);
308 }
309 else if (version == VaultVersion::CashBasis)
310 {
311 vault->at(sfLEVersion) = std::to_underlying(VaultVersion::CashBasis);
312 }
313
314 if (version != VaultVersion::Legacy)
315 {
316 auto const kind = getVaultKind(tx);
317 vault->at(sfVaultKind) = std::to_underlying(kind);
318 if (kind == VaultKind::ClosedEnded)
319 {
320 vault->at(sfSubscriptionDate) = tx[sfSubscriptionDate];
321 vault->at(sfRedemptionDate) = tx[sfRedemptionDate];
322 }
323 }
324 view().insert(vault);
325
326 // Explicitly create MPToken for the vault owner
327 if (auto const err = authorizeMPToken(
328 applyViewContext, preFeeBalance_, mptIssuanceID, accountID_, ctx_.journal);
329 !isTesSuccess(err))
330 return err;
331
332 // If the vault is private, set the authorized flag for the vault owner
333 if (tx.isFlag(tfVaultPrivate))
334 {
335 if (auto const err = authorizeMPToken(
336 applyViewContext,
338 mptIssuanceID,
339 pseudoId,
340 ctx_.journal,
341 {},
342 accountID_);
343 !isTesSuccess(err))
344 return err;
345 }
346
347 associateAsset(*vault, asset);
348
349 return tesSUCCESS;
350}
351
352void
354{
355 // No transaction-specific invariants yet (future work).
356}
357
358bool
360{
361 // No transaction-specific invariants yet (future work).
362 return true;
363}
364
365} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
virtual SLE::pointer peek(Keylet const &k)=0
Prepare to modify the SLE associated with key.
virtual void insert(SLE::Ref sle)=0
Insert a new state SLE.
A currency issued by an account.
Definition Issue.h:18
static bool native()
Definition MPTIssue.h:61
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
static std::expected< MPTID, TER > create(ApplyViewContext ctx, beast::Journal journal, MPTCreateArgs const &args)
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.
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 isFlag(std::uint32_t) const
Definition STObject.cpp:511
bool isFieldPresent(SField const &field) const
Definition STObject.cpp:464
SeqProxy getSeqProxy() const
Definition STTx.cpp:198
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 std::uint32_t getFlagsMask(PreflightContext const &ctx)
TER doApply() override
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef 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 bool checkExtraFeatures(PreflightContext const &ctx)
static TER preclaim(PreclaimContext const &ctx)
static NotTEC preflight(PreflightContext const &ctx)
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 mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ terADDRESS_COLLISION
Definition TER.h:230
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 ...
bool hasExpired(ReadView const &view, std::optional< std::uint32_t > const &exp, ExpiryComparison comparison=ExpiryComparison::Inclusive)
Determines whether the given expiration time has passed.
Definition View.cpp:52
bool isValidClosedEndedGap(std::uint32_t sub, std::uint32_t red)
Returns true iff the (SubscriptionDate, RedemptionDate) gap of a closed-ended vault satisfies kMinInv...
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
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.
VaultVersion getVaultDefaultVersion(Rules const &rules)
Resolves which LEVersion a newly-created Vault should get under the currently active amendments.
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
constexpr std::uint8_t kVaultDefaultIouScale
Default IOU scale factor for a Vault.
Definition Protocol.h:313
VaultVersion
Vault ledger-entry schema versions, persisted as sfLEVersion.
Definition Protocol.h:342
constexpr std::uint8_t kFixedPrecisionVaultMaximumIouScale
Maximum Scale for a Vault created under featureLendingProtocolV1_2.
Definition Protocol.h:325
constexpr std::size_t kMaxMpTokenMetadataLength
The maximum length of MPTokenMetadata.
Definition Protocol.h:292
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.
AccountID pseudoAccountAddress(ReadView const &view, UInt256 const &pseudoOwnerKey)
Generate a pseudo-account address from a pseudo owner key.
constexpr std::uint8_t kLegacyVaultMaximumIouScale
Maximum Scale for a Vault created before featureLendingProtocolV1_2.
Definition Protocol.h:320
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 ...
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temMALFORMED
Definition TER.h:75
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
constexpr std::uint8_t kVaultStrategyFirstComeFirstServe
Vault withdrawal policies.
Definition Protocol.h:308
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.
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)
int vaultBaseScale(Asset const &asset, std::uint8_t scale)
Returns the Vault's base exponent for asset at scale, before a Vault object exists to read it from: 0...
@ tecWRONG_ASSET
Definition TER.h:371
@ tecLOCKED
Definition TER.h:369
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecFROZEN
Definition TER.h:314
@ tecEXPIRED
Definition TER.h:325
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
void associateAsset(STLedgerEntry &sle, Asset const &asset)
Associate an Asset with all sMD_NeedsAsset fields in a ledger entry.
bool isValidVaultKind(STTx const &tx)
Returns true iff sfVaultKind is either absent from tx or is present and equal to a recognised VaultKi...
@ tesSUCCESS
Definition TER.h:253
UInt256 key
Definition Keylet.h:21
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