xrpld
Loading...
Searching...
No Matches
VaultCreate.cpp
1#include <xrpl/tx/transactors/vault/VaultCreate.h>
2
3#include <xrpl/basics/Number.h>
4#include <xrpl/basics/base_uint.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/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/Asset.h>
14#include <xrpl/protocol/Feature.h>
15#include <xrpl/protocol/Indexes.h>
16#include <xrpl/protocol/Issue.h>
17#include <xrpl/protocol/LedgerFormats.h>
18#include <xrpl/protocol/MPTIssue.h>
19#include <xrpl/protocol/Protocol.h>
20#include <xrpl/protocol/SField.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/TxFlags.h>
27#include <xrpl/protocol/XRPAmount.h>
28#include <xrpl/tx/Transactor.h>
29#include <xrpl/tx/transactors/token/MPTokenIssuanceCreate.h>
30
31#include <cstdint>
32#include <memory>
33#include <optional>
34#include <utility>
35
36namespace xrpl {
37
38bool
40{
41 if (!ctx.rules.enabled(featureMPTokensV1))
42 return false;
43
44 if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDomains))
45 return false;
46
47 if (!ctx.rules.enabled(featureLendingProtocolV1_1) &&
48 (ctx.tx.isFieldPresent(sfVaultKind) || ctx.tx.isFieldPresent(sfSubscriptionDate) ||
49 ctx.tx.isFieldPresent(sfRedemptionDate)))
50 return false;
51
52 return true;
53}
54
57{
58 return tfVaultCreateMask;
59}
60
63{
64 if (!validDataLength(ctx.tx[~sfData], kMaxDataPayloadLength))
65 return temMALFORMED;
66
67 if (auto const withdrawalPolicy = ctx.tx[~sfWithdrawalPolicy])
68 {
69 // Enforce valid withdrawal policy
70 if (*withdrawalPolicy != kVaultStrategyFirstComeFirstServe)
71 return temMALFORMED;
72 }
73
74 if (auto const domain = ctx.tx[~sfDomainID])
75 {
76 if (*domain == beast::kZero)
77 {
78 return temMALFORMED;
79 }
80 if (!ctx.tx.isFlag(tfVaultPrivate))
81 {
82 return temMALFORMED; // DomainID only allowed on private vaults
83 }
84 }
85
86 if (auto const assetMax = ctx.tx[~sfAssetsMaximum])
87 {
88 if (*assetMax < beast::kZero)
89 return temMALFORMED;
90 }
91
92 if (auto const metadata = ctx.tx[~sfMPTokenMetadata])
93 {
94 if (metadata->empty() || metadata->length() > kMaxMpTokenMetadataLength)
95 return temMALFORMED;
96 }
97
98 if (auto const scale = ctx.tx[~sfScale])
99 {
100 auto const vaultAsset = ctx.tx[sfAsset];
101 if (vaultAsset.holds<MPTIssue>() || vaultAsset.native())
102 return temMALFORMED;
103
105 return temMALFORMED;
106 }
107
108 if (!isValidVaultKind(ctx.tx))
109 return temMALFORMED;
110 auto const kind = getVaultKind(ctx.tx);
111 auto const hasSubscription = ctx.tx.isFieldPresent(sfSubscriptionDate);
112 auto const hasRedemption = ctx.tx.isFieldPresent(sfRedemptionDate);
113 auto const isClosedEnded = kind == VaultKind::ClosedEnded;
114 if (!isClosedEnded && (hasSubscription || hasRedemption))
115 return temMALFORMED;
116 if (isClosedEnded)
117 {
118 if (!hasSubscription || !hasRedemption)
119 return temMALFORMED;
120 if (!isValidClosedEndedGap(ctx.tx[sfSubscriptionDate], ctx.tx[sfRedemptionDate]))
121 return temMALFORMED;
122 }
123
124 return tesSUCCESS;
125}
126
127TER
129{
130 auto const vaultAsset = ctx.tx[sfAsset];
131 auto const account = ctx.tx[sfAccount];
132
133 if (auto const ter = canAddHolding(ctx.view, vaultAsset))
134 return ter;
135
136 // Check for pseudo-account issuers - we do not want a vault to hold such
137 // assets (e.g. MPT shares to other vaults or AMM LPTokens) as they would be
138 // impossible to clawback (should the need arise)
139 if (!vaultAsset.native())
140 {
141 if (isPseudoAccount(ctx.view, vaultAsset.getIssuer()))
142 return tecWRONG_ASSET;
143 }
144
145 // Cannot create Vault for an Asset frozen for the vault owner
146 if (isFrozen(ctx.view, account, vaultAsset))
147 return vaultAsset.holds<Issue>() ? tecFROZEN : tecLOCKED;
148
149 if (auto const domain = ctx.tx[~sfDomainID])
150 {
151 auto const sleDomain = ctx.view.read(keylet::permissionedDomain(*domain));
152 if (!sleDomain)
153 return tecOBJECT_NOT_FOUND;
154 }
155
156 auto const sequence = ctx.tx.getSeqProxy();
157 if (auto const accountId = pseudoAccountAddress(ctx.view, keylet::vault(account, sequence).key);
158 accountId == beast::kZero)
160
161 // preflight enforces red >= sub + kMinInvestmentPeriod for closed-ended
162 // vaults, so a past RedemptionDate always implies a strictly-earlier,
163 // equally-past SubscriptionDate. The RedemptionDate arm below is therefore
164 // defensive: it cannot be the sole cause of tecEXPIRED. It is kept to
165 // preserve the invariant locally in case the preflight gap check is ever
166 // weakened.
167 if (hasExpired(ctx.view, ctx.tx[~sfSubscriptionDate]) ||
168 hasExpired(ctx.view, ctx.tx[~sfRedemptionDate]))
169 return tecEXPIRED;
170
171 return tesSUCCESS;
172}
173
174TER
176{
177 // All return codes in `doApply` must be `tec`, `ter`, or `tes`.
178 // As we move checks into `preflight` and `preclaim`,
179 // we can consider downgrading them to `tef` or `tem`.
180
181 auto const& tx = ctx_.tx;
182 auto applyViewContext = ctx_.getApplyViewContext();
183 auto const sequence = tx.getSeqProxy();
184 auto const owner = view().peek(keylet::account(accountID_));
185 if (owner == nullptr)
186 return tefINTERNAL; // LCOV_EXCL_LINE
187
188 auto vault = std::make_shared<SLE>(keylet::vault(accountID_, sequence));
189
190 if (auto ter = dirLink(view(), accountID_, vault))
191 return ter;
192 // We will create Vault and PseudoAccount, hence increase OwnerCount by 2
193 increaseOwnerCount(view(), owner, {}, 2, j_);
194 if (preFeeBalance_ < accountReserve(view(), owner, j_))
196
197 auto maybePseudo = createPseudoAccount(view(), vault->key(), sfVaultID);
198 if (!maybePseudo)
199 return maybePseudo.error(); // LCOV_EXCL_LINE
200 auto const& pseudo = *maybePseudo;
201 AccountID const pseudoId = pseudo->at(sfAccount);
202 auto const asset = tx[sfAsset];
203
204 if (auto ter = addEmptyHolding(applyViewContext, pseudoId, preFeeBalance_, asset, j_);
205 !isTesSuccess(ter))
206 return ter;
207
208 std::uint8_t const scale = (asset.holds<MPTIssue>() || asset.native())
209 ? 0
210 : ctx_.tx[~sfScale].value_or(kVaultDefaultIouScale);
211
212 std::uint32_t mptFlags = 0;
213 if (!tx.isFlag(tfVaultShareNonTransferable))
214 mptFlags |= (lsfMPTCanEscrow | lsfMPTCanTrade | lsfMPTCanTransfer);
215 if (tx.isFlag(tfVaultPrivate))
216 mptFlags |= lsfMPTRequireAuth;
217
218 // Note, here we are **not** creating an MPToken for the assets held in
219 // the vault. That MPToken or TrustLine/RippleState is created above, in
220 // addEmptyHolding. Here we are creating MPTokenIssuance for the shares
221 // in the vault.
222 //
223 // Post-fixCleanup3_2_0: surface the vault pseudo's holding (MPToken
224 // for MPT, RippleState for IOU) on the share via sfReferenceHolding.
225 // XRP underlyings leave it unset.
226 auto const referenceHolding = [&]() -> std::optional<uint256> {
227 if (!view().rules().enabled(fixCleanup3_2_0) || asset.native())
228 return std::nullopt;
229 return asset.holds<MPTIssue>()
230 ? keylet::mptoken(asset.get<MPTIssue>().getMptID(), pseudoId).key
231 : keylet::trustLine(pseudoId, asset.get<Issue>()).key;
232 }();
233 auto const maybeShare = MPTokenIssuanceCreate::create(
234 applyViewContext,
235 j_,
236 {
237 .priorBalance = std::nullopt,
238 .account = pseudoId,
239 .sequence = 1,
240 .flags = mptFlags,
241 .assetScale = scale,
242 .transferFee = std::nullopt,
243 .metadata = tx[~sfMPTokenMetadata],
244 .domainId = tx[~sfDomainID],
245 .referenceHolding = referenceHolding,
246 });
247 if (!maybeShare)
248 return maybeShare.error(); // LCOV_EXCL_LINE
249 auto const& mptIssuanceID = *maybeShare;
250
251 vault->setFieldIssue(sfAsset, STIssue{sfAsset, asset});
252 vault->at(sfFlags) = tx.getFlags() & tfVaultPrivate;
253 vault->at(sfSequence) = sequence.value();
254 vault->at(sfOwner) = accountID_;
255 vault->at(sfAccount) = pseudoId;
256 vault->at(sfAssetsTotal) = Number(0);
257 vault->at(sfAssetsAvailable) = Number(0);
258 vault->at(sfLossUnrealized) = Number(0);
259 // Leave default values for AssetTotal and AssetAvailable, both zero.
260 if (auto value = tx[~sfAssetsMaximum])
261 vault->at(sfAssetsMaximum) = *value;
262 vault->at(sfShareMPTID) = mptIssuanceID;
263 if (auto value = tx[~sfData])
264 vault->at(sfData) = *value;
265 // Required field, default to vaultStrategyFirstComeFirstServe
266 if (auto value = tx[~sfWithdrawalPolicy])
267 {
268 vault->at(sfWithdrawalPolicy) = *value;
269 }
270 else
271 {
272 vault->at(sfWithdrawalPolicy) = kVaultStrategyFirstComeFirstServe;
273 }
274 if (scale != 0u)
275 vault->at(sfScale) = scale;
276 if (view().rules().enabled(featureLendingProtocolV1_1))
277 {
278 vault->at(sfLEVersion) = std::to_underlying(VaultVersion::CashBasis);
279
280 auto const kind = getVaultKind(tx);
281 vault->at(sfVaultKind) = std::to_underlying(kind);
282 if (kind == VaultKind::ClosedEnded)
283 {
284 vault->at(sfSubscriptionDate) = tx[sfSubscriptionDate];
285 vault->at(sfRedemptionDate) = tx[sfRedemptionDate];
286 }
287 }
288 view().insert(vault);
289
290 // Explicitly create MPToken for the vault owner
291 if (auto const err = authorizeMPToken(
292 applyViewContext, preFeeBalance_, mptIssuanceID, accountID_, ctx_.journal);
293 !isTesSuccess(err))
294 return err;
295
296 // If the vault is private, set the authorized flag for the vault owner
297 if (tx.isFlag(tfVaultPrivate))
298 {
299 if (auto const err = authorizeMPToken(
300 applyViewContext,
302 mptIssuanceID,
303 pseudoId,
304 ctx_.journal,
305 {},
306 accountID_);
307 !isTesSuccess(err))
308 return err;
309 }
310
311 associateAsset(*vault, asset);
312
313 return tesSUCCESS;
314}
315
316void
318{
319 // No transaction-specific invariants yet (future work).
320}
321
322bool
324{
325 // No transaction-specific invariants yet (future work).
326 return true;
327}
328
329} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
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 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
std::shared_ptr< STLedgerEntry const > const & const_ref
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:199
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
static bool validDataLength(std::optional< Slice > const &slice, std::size_t maxLength)
ApplyContext & ctx_
Definition Transactor.h:153
static std::uint32_t getFlagsMask(PreflightContext const &ctx)
TER doApply() override
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)
void visitInvariantEntry(bool isDelete, SLE::const_ref before, SLE::const_ref after) override
Inspect a single ledger entry modified by this transaction.
T make_shared(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet vault(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:561
Keylet permissionedDomain(AccountID const &account, SeqProxy const &seq) noexcept
Definition Indexes.cpp:579
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:543
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:198
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:253
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
@ terADDRESS_COLLISION
Definition TER.h:224
VaultKind getVaultKind(SLE::const_ref vault)
Resolves the VaultKind of a vault SLE.
AccountID pseudoAccountAddress(ReadView const &view, uint256 const &pseudoOwnerKey)
Generate a pseudo-account address from a pseudo owner key.
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:48
bool isValidClosedEndedGap(std::uint32_t sub, std::uint32_t red)
Returns true iff the (SubscriptionDate, RedemptionDate) gap of a closed-ended vault satisfies kMinInv...
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.
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
constexpr std::uint8_t kVaultMaximumIouScale
Maximum scale factor for a Vault.
Definition Protocol.h:318
TER addEmptyHolding(ApplyViewContext ctx, AccountID const &accountID, XRPAmount priorBalance, MPTIssue const &mptIssue, beast::Journal journal)
std::expected< SLE::pointer, TER > createPseudoAccount(ApplyView &view, uint256 const &pseudoOwnerKey, SField const &ownerField)
Create pseudo-account, storing pseudoOwnerKey into ownerField.
constexpr std::size_t kMaxDataPayloadLength
The maximum length of Data payload.
Definition Protocol.h:302
TER canAddHolding(ReadView const &view, MPTIssue const &mptIssue)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:607
constexpr std::uint8_t kVaultDefaultIouScale
Default IOU scale factor for a Vault.
Definition Protocol.h:312
TER dirLink(ApplyView &view, AccountID const &owner, SLE::pointer &object, SF_UINT64 const &node=sfOwnerNode)
Definition View.cpp:343
constexpr std::size_t kMaxMpTokenMetadataLength
The maximum length of MPTokenMetadata.
Definition Protocol.h:291
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
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:676
constexpr std::uint8_t kVaultStrategyFirstComeFirstServe
Vault withdrawal policies.
Definition Protocol.h:307
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)
@ tecWRONG_ASSET
Definition TER.h:363
@ tecLOCKED
Definition TER.h:361
@ tecOBJECT_NOT_FOUND
Definition TER.h:329
@ tecFROZEN
Definition TER.h:306
@ tecEXPIRED
Definition TER.h:317
@ tecINSUFFICIENT_RESERVE
Definition TER.h:310
bool isPseudoAccount(SLE::const_pointer sleAcct, std::set< SField const * > const &pseudoFieldFilter={})
Returns true if and only if sleAcct is a pseudo-account or specific pseudo-accounts in pseudoFieldFil...
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...
XRPAmount accountReserve(ReadView const &view, SLE::const_ref sle, beast::Journal j, Adjustment adj={})
Returns the account reserve, in drops.
@ tesSUCCESS
Definition TER.h:245
uint256 key
Definition Keylet.h:21
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:83
ReadView const & view
Definition Transactor.h:86
State information when preflighting a tx.
Definition Transactor.h:38