xrpld
Loading...
Searching...
No Matches
VaultClosedEnded_test.cpp
1#include <test/app/vault/VaultTestBase.h>
2#include <test/jtx/Account.h>
3#include <test/jtx/Env.h>
4#include <test/jtx/TestHelpers.h>
5#include <test/jtx/amount.h>
6#include <test/jtx/fee.h>
7#include <test/jtx/flags.h>
8#include <test/jtx/pay.h>
9#include <test/jtx/sig.h>
10#include <test/jtx/ter.h>
11#include <test/jtx/vault.h>
12
13#include <xrpl/basics/Number.h>
14#include <xrpl/basics/chrono.h>
15#include <xrpl/beast/unit_test/suite.h>
16#include <xrpl/json/json_forwards.h>
17#include <xrpl/json/json_value.h>
18#include <xrpl/ledger/helpers/VaultHelpers.h>
19#include <xrpl/protocol/Asset.h>
20#include <xrpl/protocol/Feature.h>
21#include <xrpl/protocol/Indexes.h>
22#include <xrpl/protocol/Issue.h>
23#include <xrpl/protocol/Keylet.h>
24#include <xrpl/protocol/MPTIssue.h>
25#include <xrpl/protocol/Protocol.h>
26#include <xrpl/protocol/SField.h>
27#include <xrpl/protocol/STAmount.h>
28#include <xrpl/protocol/SeqProxy.h>
29#include <xrpl/protocol/TER.h>
30#include <xrpl/protocol/TxFlags.h>
31#include <xrpl/protocol/Units.h>
32#include <xrpl/protocol/XRPAmount.h>
33
34#include <chrono>
35#include <cstdint>
36#include <limits>
37#include <source_location>
38#include <string>
39#include <utility>
40
41namespace xrpl {
42
44{
45private:
46 // VaultCreate malformation and happy paths for closed-ended vaults, plus the
47 // featureLendingProtocolV1_1 gate.
48 void
50 {
51 testcase("closed-ended VaultCreate");
52 using namespace test::jtx;
53
54 auto const withEnv = [this](FeatureBitset features, auto&& body) {
55 Env env{*this, features};
56 Account const owner{"owner"};
57 env.fund(XRP(1000), owner);
58 env.close();
59 Vault vault{env};
60 body(env, owner, vault);
61 };
62
63 Asset const asset = xrpIssue();
64 auto const minPeriod = kMinInvestmentPeriod;
65 auto const maxPeriod = kMaxInvestmentPeriod;
66 auto const closedEnded = std::to_underlying(VaultKind::ClosedEnded);
67
68 // Gate: the three new fields require featureLendingProtocolV1_1.
69 withEnv(
70 testableAmendments() - featureLendingProtocolV1_1,
71 [&](Env& env, Account const& owner, Vault& vault) {
72 auto const sub = env.now().time_since_epoch().count() + 60;
73 auto [tx, keylet] = vault.create({
74 .owner = owner,
75 .asset = asset,
76 .vaultKind = closedEnded,
77 .subscriptionDate = sub,
78 .redemptionDate = sub + minPeriod,
79 });
80 env(tx, Ter{temDISABLED});
81 });
82
83 /*
84 * Valid closed-ended creation with a comfortably interior gap (well above
85 * kMinInvestmentPeriod and well below kMaxInvestmentPeriod).
86 */
87 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
88 auto const sub = env.now().time_since_epoch().count() + 60;
89 auto const red = sub + 86400;
90 auto [tx, keylet] = vault.create({
91 .owner = owner,
92 .asset = asset,
93 .vaultKind = closedEnded,
94 .subscriptionDate = sub,
95 .redemptionDate = red,
96 });
97 env(tx);
98 env.close();
99 auto const sle = env.le(keylet);
100 if (BEAST_EXPECT(sle))
101 {
102 BEAST_EXPECT(sle->at(sfVaultKind) == closedEnded);
103 BEAST_EXPECT(sle->at(sfSubscriptionDate) == sub);
104 BEAST_EXPECT(sle->at(sfRedemptionDate) == red);
105 }
106 });
107
108 // ClosedEnded missing one of SubscriptionDate / RedemptionDate => temMALFORMED.
109 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
110 auto const sub = env.now().time_since_epoch().count() + 60;
111 auto [tx, keylet] = vault.create({
112 .owner = owner,
113 .asset = asset,
114 .vaultKind = closedEnded,
115 .redemptionDate = sub + minPeriod,
116 });
117 env(tx, Ter{temMALFORMED});
118 });
119 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
120 auto const sub = env.now().time_since_epoch().count() + 60;
121 auto [tx, keylet] = vault.create({
122 .owner = owner,
123 .asset = asset,
124 .vaultKind = closedEnded,
125 .subscriptionDate = sub,
126 });
127 env(tx, Ter{temMALFORMED});
128 });
129
130 /*
131 * SubscriptionDate not strictly after parent close time (preclaim, state-dependent -
132 * returns tecEXPIRED). This is the only reachable path to tecEXPIRED in VaultCreate; see
133 * the note below the next case. Note: there is no separate "expired RedemptionDate" test
134 * case here. preflight enforces red >= sub + kMinInvestmentPeriod, so any past
135 * RedemptionDate implies a strictly-earlier, equally-past SubscriptionDate; the
136 * SubscriptionDate check above short-circuits first. The RedemptionDate arm of the
137 * hasExpired check in VaultCreate::preclaim is defensive and unreachable as the sole cause
138 * of tecEXPIRED.
139 */
140 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
141 auto const nowSec = env.now().time_since_epoch().count();
142 auto [tx, keylet] = vault.create({
143 .owner = owner,
144 .asset = asset,
145 .vaultKind = closedEnded,
146 .subscriptionDate = nowSec,
147 .redemptionDate = nowSec + minPeriod,
148 });
149 env(tx, Ter{tecEXPIRED});
150 });
151
152 /*
153 * Gap smaller than kMinInvestmentPeriod => temMALFORMED. Includes the SubscriptionDate >=
154 * RedemptionDate degenerate cases: the red == sub boundary and the strictly-reversed red <
155 * sub case, the latter yielding a negative signed int64 gap that is caught by the
156 * sub-minimum branch of the gap check.
157 */
158 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
159 auto const sub = env.now().time_since_epoch().count() + 60;
160 auto [tx, keylet] = vault.create({
161 .owner = owner,
162 .asset = asset,
163 .vaultKind = closedEnded,
164 .subscriptionDate = sub,
165 .redemptionDate = sub + minPeriod - 1,
166 });
167 env(tx, Ter{temMALFORMED});
168 });
169 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
170 auto const sub = env.now().time_since_epoch().count() + 60;
171 auto [tx, keylet] = vault.create({
172 .owner = owner,
173 .asset = asset,
174 .vaultKind = closedEnded,
175 .subscriptionDate = sub,
176 .redemptionDate = sub,
177 });
178 env(tx, Ter{temMALFORMED});
179 });
180 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
181 auto const sub = env.now().time_since_epoch().count() + 60;
182 auto [tx, keylet] = vault.create({
183 .owner = owner,
184 .asset = asset,
185 .vaultKind = closedEnded,
186 .subscriptionDate = sub,
187 .redemptionDate = sub - 1,
188 });
189 env(tx, Ter{temMALFORMED});
190 });
191
192 // Gap equal to MAX_INVESTMENT_PERIOD => temMALFORMED (bound is half-open on the right).
193 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
194 auto const sub = env.now().time_since_epoch().count() + 60;
195 auto [tx, keylet] = vault.create({
196 .owner = owner,
197 .asset = asset,
198 .vaultKind = closedEnded,
199 .subscriptionDate = sub,
200 .redemptionDate = sub + maxPeriod,
201 });
202 env(tx, Ter{temMALFORMED});
203 });
204
205 // Gap strictly greater than MAX_INVESTMENT_PERIOD => temMALFORMED. Same code path as
206 // gap == MAX_INVESTMENT_PERIOD above, but covers the "gap >= MAX" bullet fully.
207 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
208 auto const sub = env.now().time_since_epoch().count() + 60;
209 auto [tx, keylet] = vault.create({
210 .owner = owner,
211 .asset = asset,
212 .vaultKind = closedEnded,
213 .subscriptionDate = sub,
214 .redemptionDate = sub + maxPeriod + 1,
215 });
216 env(tx, Ter{temMALFORMED});
217 });
218
219 // Happy path: gap exactly equal to kMinInvestmentPeriod is accepted (lower bound is
220 // inclusive). A min-gap vault can originate a minimum-interval loan; see
221 // LoanSet_test::testLoanSetClosedEnded.
222 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
223 auto const sub = env.now().time_since_epoch().count() + 60;
224 auto const red = sub + minPeriod;
225 auto [tx, keylet] = vault.create({
226 .owner = owner,
227 .asset = asset,
228 .vaultKind = closedEnded,
229 .subscriptionDate = sub,
230 .redemptionDate = red,
231 });
232 env(tx);
233 env.close();
234 auto const sle = env.le(keylet);
235 if (BEAST_EXPECT(sle))
236 {
237 BEAST_EXPECT(sle->at(sfRedemptionDate) == red);
238 }
239 });
240
241 // Happy path: gap one second less than MAX_INVESTMENT_PERIOD is
242 // accepted (upper bound is exclusive).
243 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
244 auto const sub = env.now().time_since_epoch().count() + 60;
245 auto const red = sub + maxPeriod - 1;
246 auto [tx, keylet] = vault.create({
247 .owner = owner,
248 .asset = asset,
249 .vaultKind = closedEnded,
250 .subscriptionDate = sub,
251 .redemptionDate = red,
252 });
253 env(tx);
254 env.close();
255 auto const sle = env.le(keylet);
256 if (BEAST_EXPECT(sle))
257 {
258 BEAST_EXPECT(sle->at(sfRedemptionDate) == red);
259 }
260 });
261
262 // OpenEnded (absent/0) with SubscriptionDate or RedemptionDate present
263 // => temMALFORMED.
264 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
265 auto const sub = env.now().time_since_epoch().count() + 60;
266 auto [tx, keylet] =
267 vault.create({.owner = owner, .asset = asset, .subscriptionDate = sub});
268 env(tx, Ter{temMALFORMED});
269 });
270 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
271 auto const sub = env.now().time_since_epoch().count() + 60;
272 auto [tx, keylet] =
273 vault.create({.owner = owner, .asset = asset, .redemptionDate = sub + minPeriod});
274 env(tx, Ter{temMALFORMED});
275 });
276
277 // Unrecognised VaultKind => temMALFORMED.
278 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
279 auto [tx, keylet] = vault.create({
280 .owner = owner,
281 .asset = asset,
282 .vaultKind = static_cast<std::uint8_t>(closedEnded + 1),
283 });
284 env(tx, Ter{temMALFORMED});
285 });
286
287 // Happy path: open-ended vault (no new fields present) is unaffected.
288 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
289 auto [tx, keylet] = vault.create({.owner = owner, .asset = asset});
290 env(tx);
291 env.close();
292 auto const sle = env.le(keylet);
293 if (BEAST_EXPECT(sle))
294 {
295 BEAST_EXPECT(!sle->isFieldPresent(sfVaultKind));
296 BEAST_EXPECT(!sle->isFieldPresent(sfSubscriptionDate));
297 BEAST_EXPECT(!sle->isFieldPresent(sfRedemptionDate));
298 }
299 });
300
301 // Happy path: explicit `VaultKind = 0` (OpenEnded) behaves the same
302 // as absent. Per spec, absent and OpenEnded are equivalent.
303 withEnv(testableAmendments(), [&](Env& env, Account const& owner, Vault& vault) {
304 auto [tx, keylet] = vault.create({
305 .owner = owner,
306 .asset = asset,
307 .vaultKind = std::to_underlying(VaultKind::OpenEnded),
308 });
309 env(tx);
310 env.close();
311 auto const sle = env.le(keylet);
312 if (BEAST_EXPECT(sle))
313 {
314 // OpenEnded is sfVaultKind's default; SoeDefault fields
315 // aren't serialized when they hold the default value.
316 BEAST_EXPECT(!sle->isFieldPresent(sfVaultKind));
317 BEAST_EXPECT(!sle->isFieldPresent(sfSubscriptionDate));
318 BEAST_EXPECT(!sle->isFieldPresent(sfRedemptionDate));
319 }
320 });
321 }
322
323 // SubscriptionDate boundary cases at the top of the UINT32 range.
324 // (1) The largest legal sub picks red = UINT32_MAX exactly, which hits
325 // the inclusive lower bound of the kMinInvestmentPeriod gap check.
326 // (2) sub = UINT32_MAX must be rejected: sub + kMinInvestmentPeriod is
327 // unrepresentable as the tx's UINT32 sfRedemptionDate, so no red value
328 // can satisfy the gap check.
329 void
331 {
332 testcase("closed-ended VaultCreate SubscriptionDate near UINT32_MAX");
333 using namespace test::jtx;
334
335 auto const closedEnded = std::to_underlying(VaultKind::ClosedEnded);
336 Asset const asset = xrpIssue();
337
338 {
339 Env env{*this, testableAmendments()};
340 Account const owner{"owner"};
341 env.fund(XRP(1000), owner);
342 env.close();
343
344 Vault const vault{env};
347 auto [tx, keylet] = vault.create({
348 .owner = owner,
349 .asset = asset,
350 .vaultKind = closedEnded,
351 .subscriptionDate = sub,
352 .redemptionDate = red,
353 });
354 env(tx);
355 env.close();
356 auto const sle = env.le(keylet);
357 if (BEAST_EXPECT(sle))
358 {
359 BEAST_EXPECT(sle->at(sfSubscriptionDate) == sub);
360 BEAST_EXPECT(sle->at(sfRedemptionDate) == red);
361 }
362 }
363
364 // sub = UINT32_MAX: no legal red exists because sub + kMinInvestmentPeriod
365 // wraps in a UINT32. Every candidate red must fall to temMALFORMED via
366 // the gap check in preflight.
367 auto const rejectAtMax = [&, this](std::uint32_t red) {
368 Env env{*this, testableAmendments()};
369 Account const owner{"owner"};
370 env.fund(XRP(1000), owner);
371 env.close();
372
373 Vault const vault{env};
374 auto [tx, keylet] = vault.create({
375 .owner = owner,
376 .asset = asset,
377 .vaultKind = closedEnded,
378 .subscriptionDate = std::numeric_limits<std::uint32_t>::max(),
379 .redemptionDate = red,
380 });
381 env(tx, Ter{temMALFORMED});
382 };
384 rejectAtMax(0u);
385 rejectAtMax(kMinInvestmentPeriod - 1u);
386 }
387
388 // Phase derivation across the SubscriptionDate / RedemptionDate boundaries, including the now
389 // == SubscriptionDate case (which must still resolve to Subscription).
390 void
392 {
393 testcase("closed-ended phase derivation");
394 using namespace test::jtx;
395
396 Env env{*this, testableAmendments()};
397 Account const owner{"owner"};
398 Account const depositor{"depositor"};
399 env.fund(XRP(1000), owner, depositor);
400 env.close();
401
402 Asset const asset = xrpIssue();
403 auto const [vault, keylet, sub, red] =
404 makeClosedEndedVault(env, owner, asset, 60u, kMinInvestmentPeriod);
405
406 // Pre-seed shares during Subscription so the depositor has capital to
407 // withdraw at the Redemption boundary below.
408 env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = XRP(10).value()}));
409 env.close();
410
411 auto const deposit =
412 [&](TER expected, std::source_location const& loc = std::source_location::current()) {
413 env(
414 WithSourceLocation{
415 vault.deposit(
416 {.depositor = depositor, .id = keylet.key, .amount = XRP(1).value()}),
417 loc},
418 Ter{expected});
419 };
420 auto const withdraw =
421 [&](TER expected, std::source_location const& loc = std::source_location::current()) {
422 env(
423 WithSourceLocation{
424 vault.withdraw(
425 {.depositor = depositor, .id = keylet.key, .amount = XRP(1).value()}),
426 loc},
427 Ter{expected});
428 };
429
430 auto const runTest = [&](TER expectedDeposit,
431 TER expectedWithdraw,
432 std::source_location const& loc =
434 deposit(expectedDeposit, loc);
435 withdraw(expectedWithdraw, loc);
436 };
437
438 // Assert both deposit and withdraw return codes at each point so the
439 // active phase is uniquely identified:
440 // Subscription: deposit tesSUCCESS, withdraw tesSUCCESS
441 // Investment: deposit tecEXPIRED, withdraw tecTOO_SOON
442 // Redemption: deposit tecEXPIRED, withdraw tesSUCCESS
443
444 // Ledger time comfortably before SubscriptionDate: Subscription.
445 runTest(tesSUCCESS, tesSUCCESS);
446
447 // Boundary: parent close time exactly at SubscriptionDate must still
448 // be Subscription.
449 closeToTime(env, Tp{D{sub}});
450 runTest(tesSUCCESS, tesSUCCESS);
451
452 // One second past SubscriptionDate: Investment.
453 closeToTime(env, Tp{D{sub}} + getLedgerTimeResolution(env));
454 runTest(tecEXPIRED, tecTOO_SOON);
455
456 // Any point strictly before RedemptionDate remains Investment.
457 closeToTime(env, Tp{D{red}} - getLedgerTimeResolution(env));
458 runTest(tecEXPIRED, tecTOO_SOON);
459
460 // Boundary: parent close time == RedemptionDate is Redemption (per
461 // spec table: now >= RedemptionDate). Deposits are rejected but
462 // withdrawals succeed.
463 closeToTime(env, Tp{D{red}});
464 runTest(tecEXPIRED, tesSUCCESS);
465 env.close();
466 }
467
468 // Open-ended vaults are always in VaultPhase::NoPhase, regardless of the ledger clock or any
469 // dates present on the vault.
470 void
472 {
473 testcase("open-ended phase derivation");
474 using namespace test::jtx;
475
476 Env env{*this, testableAmendments()};
477 Account const owner{"owner"};
478 env.fund(XRP(1000), owner);
479 env.close();
480
481 Asset const asset = xrpIssue();
482 Vault const vault{env};
483 auto [tx, keylet] = vault.create({.owner = owner, .asset = asset});
484 env(tx);
485 env.close();
486
487 auto const checkPhaseAt = [&](NetClock::time_point at) {
488 closeToTime(env, at);
489 auto const sle = env.le(keylet);
490 if (!BEAST_EXPECT(sle))
491 return;
492 BEAST_EXPECT(getVaultPhase(*env.current(), sle) == VaultPhase::NoPhase);
493 };
494
495 // Advance the clock through a wide range of ledger times: an open-ended vault's phase
496 // must be NoPhase at every one of them, because the derivation short-circuits on
497 // VaultKind::OpenEnded before it looks at any dates.
498 auto const ledgerTime = Tp{D{30}} + env.closed()->header().closeTimeResolution;
499 checkPhaseAt(ledgerTime);
500 checkPhaseAt(ledgerTime + std::chrono::seconds{kMinInvestmentPeriod});
501 checkPhaseAt(
503 env.closed()->header().closeTimeResolution);
504 }
505
506 // VaultDeposit is allowed only during Subscription (or NoPhase). Rejected during Investment and
507 // Redemption.
508 void
510 {
511 testcase("closed-ended VaultDeposit phase gating");
512 using namespace test::jtx;
513
514 Env env{*this, testableAmendments()};
515 Account const owner{"owner"};
516 Account const depositor{"depositor"};
517 env.fund(XRP(1000), owner, depositor);
518 env.close();
519
520 Asset const asset = xrpIssue();
521 auto const [vault, keylet, sub, red] =
522 makeClosedEndedVault(env, owner, asset, 60u, kMinInvestmentPeriod);
523
524 auto const deposit =
525 [&](TER expected, std::source_location const& loc = std::source_location::current()) {
526 env(
527 WithSourceLocation{
528 vault.deposit(
529 {.depositor = depositor, .id = keylet.key, .amount = XRP(1).value()}),
530 loc},
531 Ter{expected});
532 env.close();
533 };
534
535 // Subscription: allowed.
536 deposit(tesSUCCESS);
537
538 // Investment: rejected.
539 env.close(Tp{D{sub + 1}});
540 deposit(tecEXPIRED);
541
542 // Redemption: rejected.
543 env.close(Tp{D{red}});
544 deposit(tecEXPIRED);
545 }
546
547 // VaultWithdraw is allowed in Subscription and Redemption; rejected in Investment. The
548 // AssetsAvailable cap continues to apply and is exercised in Redemption against a vault with
549 // capital deployed as an outstanding loan.
550 void
552 {
553 testcase("closed-ended VaultWithdraw phase gating");
554 using namespace test::jtx;
555 using namespace loan_broker;
556 using namespace loan;
557
558 Env env{*this, testableAmendments()};
559 Account const owner{"owner"};
560 Account const depositor{"depositor"};
561 Account const borrower{"borrower"};
562 env.fund(XRP(10'000), owner, depositor, borrower);
563 env.close();
564
565 Asset const asset = xrpIssue();
566 // Widen the Investment window so a single-payment loan (min payment
567 // interval 60s plus kLoanRedemptionBuffer) fits before RedemptionDate.
568 auto const [vault, keylet, sub, red] =
569 makeClosedEndedVault(env, owner, asset, 60u, kMinInvestmentPeriod + 3600u);
570
571 // Deposit XRP(100) in Subscription so the depositor's shares are
572 // worth XRP(100). The vault holds XRP(100) with
573 // AssetsAvailable == AssetsTotal.
574 env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = XRP(100).value()}));
575 env.close();
576
577 // Create a loan broker backed by this vault. LoanBrokerSet has no
578 // phase gate, so this is fine to do in Subscription.
579 auto const brokerKeylet =
580 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
581 env(loan_broker::set(owner, keylet.key));
582 env.close();
583
584 auto const withdraw = [&](STAmount const& amount,
585 TER expected,
586 std::source_location const& loc =
588 env(
589 WithSourceLocation{
590 vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = amount}),
591 loc},
592 Ter{expected});
593 env.close();
594 };
595
596 // Subscription: allowed (LP cancel).
597 withdraw(XRP(1).value(), tesSUCCESS);
598
599 // Investment: rejected.
600 closeToTime(env, Tp{D{sub}} + getLedgerTimeResolution(env));
601 withdraw(XRP(1).value(), tecTOO_SOON);
602
603 // Deploy capital: borrower takes a loan of XRP(60) against the
604 // vault, dropping AssetsAvailable to ~XRP(39) while AssetsTotal
605 // remains ~XRP(99).
606 env(loan::set(borrower, brokerKeylet.key, XRP(60).value()),
607 loan::kInterestRate(TenthBips32(0)),
608 kGracePeriod(60),
609 kPaymentInterval(60),
610 kPaymentTotal(1),
611 Sig(sfCounterpartySignature, owner),
612 Fee(env.current()->fees().base * 2));
613 env.close();
614
615 // Redemption: withdrawals are allowed but subject to the AssetsAvailable cap. A small
616 // withdrawal within AssetsAvailable succeeds. A withdrawal within the depositor's share
617 // value but exceeding the vault's liquid balance fails with tecINSUFFICIENT_FUNDS from the
618 // vault-shortage guard (not the insufficient-shares guard).
619 closeToTime(env, Tp{D{red}});
620 withdraw(XRP(10).value(), tesSUCCESS);
621 withdraw(XRP(80).value(), tecINSUFFICIENT_FUNDS);
622 }
623
624 // End-to-end lifecycle of a closed-ended vault (Subscription → Investment → Redemption) with
625 // multiple depositors and a real loan originated through the Investment leg. Exercises every
626 // phase transition and verifies the expected deposit, withdrawal, and lending behaviour in each
627 // phase.
628 void
630 {
631 testcase("closed-ended vault lifecycle (subscribe → invest → redeem)");
632 using namespace test::jtx;
633 using namespace loan_broker;
634 using namespace loan;
635
636 Env env{*this, testableAmendments()};
637 Account const owner{"owner"};
638 Account const alice{"alice"};
639 Account const bob{"bob"};
640 Account const borrower{"borrower"};
641 env.fund(XRP(10'000), owner, alice, bob, borrower);
642 env.close();
643
644 auto const closedEnded = std::to_underlying(VaultKind::ClosedEnded);
645 Asset const asset = xrpIssue();
646 // Widen the Investment window so a single-payment loan (min payment interval
647 // 60s plus kLoanRedemptionBuffer) fits before RedemptionDate with headroom.
648 auto const [vault, keylet, sub, red] =
649 makeClosedEndedVault(env, owner, asset, 300u, kMinInvestmentPeriod + 3600u);
650
651 auto const sleCreate = env.le(keylet);
652 BEAST_EXPECT(sleCreate);
653 MPTIssue const shares{sleCreate->at(sfShareMPTID)};
654
655 auto const balancesEq = [&](STAmount const& available, STAmount const& total) {
656 auto const sle = env.le(keylet);
657 BEAST_EXPECT(sle->at(sfAssetsAvailable) == available);
658 BEAST_EXPECT(sle->at(sfAssetsTotal) == total);
659 };
660 auto const availableEq = [&](STAmount const& expected) { balancesEq(expected, expected); };
661
662 // env.balance(account, mptIssue) name-resolves the issuer via Env::lookup, but the share
663 // issuer is the vault's pseudo-account and is never registered with the jtx Env. Read the
664 // MPToken SLE directly to avoid the lookup.
665 auto const sharesEq = [&](Account const& holder, std::uint64_t expected) {
666 auto const sle = env.le(keylet::mptoken(shares.getMptID(), holder.id()));
667 std::uint64_t const actual = sle ? sle->getFieldU64(sfMPTAmount) : 0u;
668 BEAST_EXPECT(actual == expected);
669 };
670
671 // ---- Subscription phase ----
672 // A legitimate VaultSet succeeds (positive control for 3.7).
673 {
674 auto tx = vault.set({.owner = owner, .id = keylet.key});
675 tx[sfData] = "AA";
676 env(tx);
677 env.close();
678 }
679
680 // alice deposits 100 XRP.
681 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(100).value()}));
682 env.close();
683 sharesEq(alice, 100'000'000);
684 availableEq(XRP(100).value());
685
686 // bob deposits 200 XRP.
687 env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = XRP(200).value()}));
688 env.close();
689 sharesEq(bob, 200'000'000);
690 availableEq(XRP(300).value());
691
692 // alice cancels 25 XRP (LP cancel is permitted in Subscription).
693 env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(25).value()}));
694 env.close();
695 sharesEq(alice, 75'000'000);
696 availableEq(XRP(275).value());
697
698 // Create a loan broker backed by this vault. LoanBrokerSet has no phase gate, so it is
699 // fine to do in Subscription.
700 auto const brokerKeylet =
701 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
702 env(loan_broker::set(owner, keylet.key));
703 env.close();
704
705 // ---- Investment phase (now == sub + 1) ----
706 env.close(Tp{D{sub + 1}});
707
708 // Deposits into a closed-ended vault past SubscriptionDate return tecEXPIRED.
709 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(10).value()}),
710 Ter{tecEXPIRED});
711 env.close();
712 // Withdrawals from a closed-ended vault during the Investment phase return tecTOO_SOON.
713 env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(10).value()}),
714 Ter{tecTOO_SOON});
715 env.close();
716
717 // A real loan is originated during Investment (permitted only in this phase). Zero-interest
718 // one-payment schedule keeps AssetsTotal unchanged (both instant interest recognition and
719 // cash-basis accounting recognise no interest at origination); AssetsAvailable drops by
720 // the loan principal.
721 env(loan::set(borrower, brokerKeylet.key, XRP(60).value()),
722 loan::kInterestRate(TenthBips32(0)),
723 kGracePeriod(60),
724 kPaymentInterval(60),
725 kPaymentTotal(1),
726 Sig(sfCounterpartySignature, owner),
727 Fee(env.current()->fees().base * 2));
728 env.close();
729 auto const sleBroker = env.le(keylet::loanBroker(brokerKeylet.key));
730 BEAST_EXPECT(sleBroker);
731 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1u));
732 BEAST_EXPECT(env.le(loanKeylet));
733 balancesEq(XRP(215).value(), XRP(275).value());
734
735 // Non-immutable VaultSet still works in Investment (positive control).
736 {
737 auto tx = vault.set({.owner = owner, .id = keylet.key});
738 tx[sfData] = "BB";
739 env(tx);
740 env.close();
741 }
742
743 // Depositor share balances unchanged by the loan origination; only AssetsAvailable moved.
744 sharesEq(alice, 75'000'000);
745 sharesEq(bob, 200'000'000);
746
747 // ---- Redemption phase (now == red) ----
748 env.close(Tp{D{red}});
749
750 // Deposits into a closed-ended vault past SubscriptionDate return tecEXPIRED, in both
751 // Investment and Redemption.
752 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(10).value()}),
753 Ter{tecEXPIRED});
754 env.close();
755
756 // alice redeems her remaining 75 XRP (fits within AssetsAvailable = 215).
757 env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(75).value()}));
758 env.close();
759 sharesEq(alice, 0);
760 balancesEq(XRP(140).value(), XRP(200).value());
761
762 // bob has 200 XRP-worth of shares but only 140 XRP is available (the remaining 60 XRP
763 // sits in the outstanding loan). Requesting the full 200 XRP is a final withdrawal
764 // (it would burn all of bob's remaining shares), and FixedPrecision refuses to empty
765 // the vault while AssetsDeployed is non-zero, ahead of the ordinary insufficient-funds
766 // guard; bob redeems 140 XRP instead and is left holding 60M shares backed by the loan
767 // receivable — the realistic outcome when capital is still deployed at Redemption.
768 env(vault.withdraw({.depositor = bob, .id = keylet.key, .amount = XRP(200).value()}),
769 Ter{tecHAS_OBLIGATIONS});
770 env.close();
771 env(vault.withdraw({.depositor = bob, .id = keylet.key, .amount = XRP(140).value()}));
772 env.close();
773 sharesEq(bob, 60'000'000);
774 balancesEq(XRP(0).value(), XRP(60).value());
775
776 // Defensive spot-check that the three immutable fields have not changed across the entire
777 // lifecycle. Direct immutability coverage lives with the invariant tests.
778 auto const sleFinal = env.le(keylet);
779 if (BEAST_EXPECT(sleFinal))
780 {
781 BEAST_EXPECT(sleFinal->at(sfVaultKind) == closedEnded);
782 BEAST_EXPECT(sleFinal->at(sfSubscriptionDate) == sub);
783 BEAST_EXPECT(sleFinal->at(sfRedemptionDate) == red);
784 }
785 }
786
787 // A loan whose payment is made after the Investment phase has ended
788 // (well past its next-due-date and grace period, into Redemption) must
789 // still be repayable. The vault phase must not gate LoanPay.
790 void
792 {
793 testcase("closed-ended vault: late loan payment during Redemption succeeds");
794 using namespace test::jtx;
795 using namespace loan_broker;
796 using namespace loan;
797
798 Env env{*this, testableAmendments()};
799 Account const owner{"owner"};
800 Account const alice{"alice"};
801 Account const borrower{"borrower"};
802 env.fund(XRP(10'000), owner, alice, borrower);
803 env.close();
804
805 Asset const asset = xrpIssue();
806 auto const [vault, keylet, sub, red] =
807 makeClosedEndedVault(env, owner, asset, 300u, kMinInvestmentPeriod + 3600u);
808
809 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(100).value()}));
810 env.close();
811
812 auto const brokerKeylet =
813 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
814 env(loan_broker::set(owner, keylet.key));
815 env.close();
816
817 // Investment phase: originate a zero-interest, single-payment loan
818 // with a 300s payment interval and 60s grace. The payment is due
819 // shortly after origination and well before RedemptionDate.
820 env.close(Tp{D{sub + 1}});
821 env(loan::set(borrower, brokerKeylet.key, XRP(60).value()),
822 loan::kInterestRate(TenthBips32(0)),
823 kGracePeriod(60),
824 kPaymentInterval(300),
825 kPaymentTotal(1),
826 Sig(sfCounterpartySignature, owner),
827 Fee(env.current()->fees().base * 2));
828 env.close();
829 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1u));
830 BEAST_EXPECT(env.le(loanKeylet));
831
832 // Advance to Redemption. The payment is now past its due date and
833 // grace, and the vault is no longer in Investment.
834 closeToTime(env, Tp{D{red}});
835
836 env(loan::pay(borrower, loanKeylet.key, XRP(60).value(), tfLoanLatePayment));
837 env.close();
838
839 // Loan principal returned to the vault; assetsAvailable == assetsTotal.
840 auto const sleAfter = env.le(keylet);
841 if (BEAST_EXPECT(sleAfter))
842 {
843 BEAST_EXPECT(sleAfter->at(sfAssetsAvailable) == sleAfter->at(sfAssetsTotal));
844 BEAST_EXPECT(sleAfter->at(sfAssetsAvailable) == XRP(100).value());
845 }
846
847 env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(100).value()}));
848 env.close();
849 }
850
851 // Two concurrent loans against the same closed-ended vault in Investment
852 // must coexist: both loan SLEs are created, AssetsAvailable reflects the
853 // sum of the two outstanding principals, and each can be repaid
854 // independently.
855 void
857 {
858 testcase("closed-ended vault: multiple concurrent loans in Investment");
859 using namespace test::jtx;
860 using namespace loan_broker;
861 using namespace loan;
862
863 Env env{*this, testableAmendments()};
864 Account const owner{"owner"};
865 Account const alice{"alice"};
866 Account const bob{"bob"};
867 Account const borrower1{"borrower1"};
868 Account const borrower2{"borrower2"};
869 env.fund(XRP(10'000), owner, alice, bob, borrower1, borrower2);
870 env.close();
871
872 Asset const asset = xrpIssue();
873 auto const [vault, keylet, sub, red] =
874 makeClosedEndedVault(env, owner, asset, 300u, kMinInvestmentPeriod + 3600u);
875
876 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = XRP(100).value()}));
877 env.close();
878 env(vault.deposit({.depositor = bob, .id = keylet.key, .amount = XRP(100).value()}));
879 env.close();
880
881 auto const brokerKeylet =
882 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
883 env(loan_broker::set(owner, keylet.key));
884 env.close();
885
886 env.close(Tp{D{sub + 1}});
887
888 auto const originate = [&](Account const& b, STAmount const& principal) {
889 env(loan::set(b, brokerKeylet.key, principal),
890 loan::kInterestRate(TenthBips32(0)),
891 kGracePeriod(60),
892 kPaymentInterval(300),
893 kPaymentTotal(1),
894 Sig(sfCounterpartySignature, owner),
895 Fee(env.current()->fees().base * 2));
896 env.close();
897 };
898 originate(borrower1, XRP(50).value());
899 originate(borrower2, XRP(70).value());
900
901 auto const loan1 = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1u));
902 auto const loan2 = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(2u));
903 BEAST_EXPECT(env.le(loan1));
904 BEAST_EXPECT(env.le(loan2));
905
906 // Zero-interest at origination: AssetsTotal unchanged, AssetsAvailable
907 // drops by the sum of the two loan principals.
908 {
909 auto const sle = env.le(keylet);
910 if (BEAST_EXPECT(sle))
911 {
912 BEAST_EXPECT(sle->at(sfAssetsTotal) == XRP(200).value());
913 BEAST_EXPECT(sle->at(sfAssetsAvailable) == XRP(80).value());
914 }
915 }
916
917 // Repay the first loan; the second remains outstanding.
918 env(loan::pay(borrower1, loan1.key, XRP(50).value()));
919 env.close();
920 {
921 auto const sle = env.le(keylet);
922 if (BEAST_EXPECT(sle))
923 {
924 BEAST_EXPECT(sle->at(sfAssetsTotal) == XRP(200).value());
925 BEAST_EXPECT(sle->at(sfAssetsAvailable) == XRP(130).value());
926 }
927 }
928
929 // Repay the second loan; vault is fully liquid again.
930 env(loan::pay(borrower2, loan2.key, XRP(70).value()));
931 env.close();
932 {
933 auto const sle = env.le(keylet);
934 if (BEAST_EXPECT(sle))
935 {
936 BEAST_EXPECT(sle->at(sfAssetsAvailable) == sle->at(sfAssetsTotal));
937 BEAST_EXPECT(sle->at(sfAssetsAvailable) == XRP(200).value());
938 }
939 }
940
941 // Redemption: both depositors withdraw in full.
942 env.close(Tp{D{red}});
943 env(vault.withdraw({.depositor = alice, .id = keylet.key, .amount = XRP(100).value()}));
944 env.close();
945 env(vault.withdraw({.depositor = bob, .id = keylet.key, .amount = XRP(100).value()}));
946 env.close();
947 }
948
949 // VaultClawback has no phase gate: an issuer must be able to reclaim
950 // asset from a depositor in Subscription, Investment and Redemption
951 // alike. Uses an IOU with asfAllowTrustLineClawback so the issuer path
952 // is exercised (XRP clawback with an explicit amount is temMALFORMED).
953 void
955 {
956 testcase("closed-ended vault: VaultClawback succeeds in each phase");
957 using namespace test::jtx;
958
959 Env env{*this, testableAmendments()};
960 Account const issuer{"issuer"};
961 Account const owner{"owner"};
962 Account const alice{"alice"};
963 env.fund(XRP(10'000), issuer, owner, alice);
964 env.close();
965
966 env(fset(issuer, asfAllowTrustLineClawback));
967 env.close();
968
969 PrettyAsset const iou = issuer["IOU"];
970 env.trust(iou(10'000), alice);
971 env(pay(issuer, alice, iou(1'000)));
972 env.close();
973
974 auto const [vault, keylet, sub, red] =
975 makeClosedEndedVault(env, owner, iou, 300u, kMinInvestmentPeriod + 3600u);
976
977 env(vault.deposit({.depositor = alice, .id = keylet.key, .amount = iou(300).value()}));
978 env.close();
979
980 auto const totalsEq = [&](STAmount const& expected) {
981 auto const sle = env.le(keylet);
982 if (BEAST_EXPECT(sle))
983 BEAST_EXPECT(sle->at(sfAssetsTotal) == expected);
984 };
985
986 // Subscription phase clawback.
987 env(vault.clawback(
988 {.issuer = issuer, .id = keylet.key, .holder = alice, .amount = iou(10).value()}));
989 env.close();
990 totalsEq(iou(290).value());
991
992 // Investment phase clawback.
993 env.close(Tp{D{sub + 1}});
994 env(vault.clawback(
995 {.issuer = issuer, .id = keylet.key, .holder = alice, .amount = iou(10).value()}));
996 env.close();
997 totalsEq(iou(280).value());
998
999 // Redemption phase clawback.
1000 env.close(Tp{D{red}});
1001 env(vault.clawback(
1002 {.issuer = issuer, .id = keylet.key, .holder = alice, .amount = iou(10).value()}));
1003 env.close();
1004 totalsEq(iou(270).value());
1005 }
1006
1007public:
1008 void
1022};
1023
1024BEAST_DEFINE_TESTSUITE_PRIO(VaultClosedEnded, app, xrpl, 1);
1025
1026} // namespace xrpl
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
void run() override
Runs the suite.
Shared base for the Vault*_test family under src/test/app/vault/.
NetClock::duration D
NetClock::time_point Tp
static ClosedEndedSetup makeClosedEndedVault(test::jtx::Env &env, test::jtx::Account const &owner, Asset const &asset, std::uint32_t subOffset, std::uint32_t gap)
void closeToTime(test::jtx::Env &env, NetClock::time_point time, std::source_location const &loc=std::source_location::current())
static NetClock::duration getLedgerTimeResolution(test::jtx::Env &env)
Get the current ledger's close time resolution.
test::jtx::PrettyAsset PrettyAsset
T current(T... args)
T max(T... args)
Keylet computation functions.
Definition Indexes.h:39
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet loanBroker(AccountID const &owner, SeqProxy const &seq) noexcept
Definition Indexes.cpp:571
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
constexpr std::uint32_t kMaxInvestmentPeriod
Definition Protocol.h:393
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
BEAST_DEFINE_TESTSUITE_PRIO(NFTokenBaseUtil, app, xrpl, 2)
VaultPhase getVaultPhase(ReadView const &view, SLE::ConstRef vault)
Returns the current lifecycle phase of a vault.
@ temMALFORMED
Definition TER.h:75
@ temDISABLED
Definition TER.h:102
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecTOO_SOON
Definition TER.h:329
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecEXPIRED
Definition TER.h:325
constexpr std::uint32_t kMinInvestmentPeriod
Bounds on the length of a closed-ended vault's Investment phase (RedemptionDate - SubscriptionDate).
Definition Protocol.h:391
@ tesSUCCESS
Definition TER.h:253