xrpld
Loading...
Searching...
No Matches
VaultBugs_test.cpp
1#include <test/app/vault/VaultTestBase.h>
2#include <test/jtx/Account.h>
3#include <test/jtx/CaptureLogs.h>
4#include <test/jtx/Env.h>
5#include <test/jtx/TestHelpers.h>
6#include <test/jtx/amount.h>
7#include <test/jtx/credentials.h>
8#include <test/jtx/fee.h>
9#include <test/jtx/flags.h>
10#include <test/jtx/mpt.h>
11#include <test/jtx/pay.h>
12#include <test/jtx/permissioned_domains.h>
13#include <test/jtx/sig.h>
14#include <test/jtx/sponsor.h>
15#include <test/jtx/ter.h>
16#include <test/jtx/trust.h>
17#include <test/jtx/vault.h>
18
19#include <xrpl/basics/Number.h>
20#include <xrpl/basics/base_uint.h>
21#include <xrpl/basics/chrono.h>
22#include <xrpl/beast/unit_test/suite.h>
23#include <xrpl/json/json_forwards.h>
24#include <xrpl/json/json_value.h>
25#include <xrpl/ledger/helpers/VaultHelpers.h>
26#include <xrpl/protocol/Asset.h>
27#include <xrpl/protocol/Feature.h>
28#include <xrpl/protocol/Indexes.h>
29#include <xrpl/protocol/Issue.h>
30#include <xrpl/protocol/Keylet.h>
31#include <xrpl/protocol/MPTIssue.h>
32#include <xrpl/protocol/Protocol.h>
33#include <xrpl/protocol/SField.h>
34#include <xrpl/protocol/STAmount.h>
35#include <xrpl/protocol/STNumber.h> // IWYU pragma: keep
36#include <xrpl/protocol/SeqProxy.h>
37#include <xrpl/protocol/TER.h>
38#include <xrpl/protocol/TxFlags.h>
39#include <xrpl/protocol/UintTypes.h>
40
41#include <chrono>
42#include <cstdint>
43#include <memory>
44#include <optional>
45#include <string>
46#include <tuple>
47#include <utility>
48
49namespace xrpl {
50
52{
53 // The IOU precision-boundary bugs in this suite probe the STAmount
54 // 16-digit mantissa cliff (~1e16). FixedPrecision's Open-zone cap
55 // (9e(15-Scale)) makes that value unreachable at any Scale, so these
56 // scenarios cannot be reproduced under V1.2 by construction.
57 FeatureBitset const cashBasisAll_{all_ - featureLendingProtocolV1_2};
58
59private:
60 // Bug: the equality check (vault outflow == destination inflow) was
61 // skipped whenever the destination delta rounded to zero at localMinScale,
62 // including cases where the vault outflow rounded to a non-zero value and
63 // a representable amount of value was genuinely destroyed.
64 //
65 // Scenario: Bob's IOU balance sits 5 units below the 10^16 STAmount
66 // precision boundary (atEdge2 = 9,999,999,999,999,995). A withdrawal of
67 // 6 USD shifts his balance across that boundary: the exponent increments
68 // (0 → 1), so his effective inflow in Number space is only +5 — 1 USD is
69 // consumed by the precision-boundary rounding and cannot be credited.
70 //
71 // The destroyed amount (1 USD) is sub-ULP at destinationScale=1 (step=10),
72 // so the check treats it as an unavoidable IOU-precision artefact and
73 // lets the transaction succeed.
74 //
75 // Contrast: if 15 USD were destroyed at the same scale (destroyed ≥ step),
76 // floor(15/10)=1 ≠ 0 and the invariant would fire — that discrepancy IS
77 // representable and indicates a real accounting bug.
78 //
79 // Pre-fixCleanup3_2_0: the "must increase destination balance" check fires
80 // because roundedDestinationDelta = 0 ≤ 0.
81 void
83 {
84 using namespace test::jtx;
85
86 auto const runScenario = [this](FeatureBitset features, TER expected) {
87 std::string logs;
88 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
89
90 Account const issuer{"issuer"};
91 Account const alice{"alice"};
92 Account const bob{"bob"};
93
94 env.fund(XRP(100'000), issuer, alice, bob);
95 env.close();
96 env(fset(issuer, asfDefaultRipple));
97 env.close();
98
99 PrettyAsset const usd{issuer["USD"]};
100 STAmount const aliceLimit{usd.raw(), 2, 16};
101 STAmount const bobLimit{usd.raw(), 2, 16};
102 // Bob's balance sits 5 units below the 10^16 STAmount precision
103 // boundary. Receiving 6 USD shifts his exponent 0 → 1; the
104 // STAmount records +5, not +6 (1 USD is lost to rounding).
105 STAmount const atEdge2{usd.raw(), Number{9'999'999'999'999'995LL}};
106
107 env(trust(alice, aliceLimit));
108 env(trust(bob, bobLimit));
109 env.close();
110
111 env(pay(issuer, alice, usd(1'000)));
112 env(pay(issuer, bob, atEdge2));
113 env.close();
114
115 Vault const vault{env};
116 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
117 vaultTx[sfScale] = 0;
118 env(vaultTx);
119 env.close();
120
121 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1'000)}));
122 env.close();
123
124 // Withdraw 6 USD to Bob: vault loses 6, Bob gains only 5.
125 // Destroyed amount = 1 USD, which is sub-ULP at destinationScale=1.
126 auto tx = vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(6)});
127 tx[sfDestination] = bob.human();
128 env(tx, Ter(expected));
129 env.close();
130 };
131
132 {
133 testcase(
134 "bug: VaultWithdraw to destination at IOU precision boundary fires "
135 "invariant (pre-fixCleanup3_2_0)");
136 runScenario(cashBasisAll_ - fixCleanup3_2_0, tecINVARIANT_FAILED);
137 }
138 {
139 testcase(
140 "bug: VaultWithdraw to destination at IOU precision boundary succeeds "
141 "when destroyed amount is sub-ULP (post-fixCleanup3_2_0)");
142 runScenario(cashBasisAll_, tesSUCCESS);
143 }
144 }
145
146 // VaultDeposit by issuer with the vault parked at the IOU 16-digit
147 // edge (9.999e15). Issuer mints 2 more USD; the vault trust line
148 // goes 9.999e15 → 10^16, gaining 1 unit instead of 2 (canonicalization).
149 //
150 // Pre-fixCleanup3_2_0: the proactive check is absent; the deposit
151 // applies, then VaultInvariant's "deposit must increase vault
152 // balance" assertion fires at finalize time on the rounded vault
153 // delta of zero, returning tecINVARIANT_FAILED.
154 // Post-amendment: reject deposit that is not representable at Vault scale.
155 void
157 {
158 using namespace test::jtx;
159
160 auto const runScenario = [this](FeatureBitset features, TER expected) {
161 std::string logs;
162 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
163
164 Account const issuer{"issuer"};
165 Account const owner{"owner"};
166
167 env.fund(XRP(100'000), issuer, owner);
168 env.close();
169 env(fset(issuer, asfDefaultRipple));
170 env.close();
171
172 PrettyAsset const usd{issuer["USD"]};
173 STAmount const trustLimit{usd.raw(), 2, 16};
174 STAmount const ownerFund{usd.raw(), Number{9'999'999'999'999'999LL}};
175
176 env(trust(owner, trustLimit));
177 env.close();
178 env(pay(issuer, owner, ownerFund));
179 env.close();
180
181 Vault const vault{env};
182 auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = usd});
183 vaultTx[sfScale] = 0;
184 env(vaultTx);
185 env.close();
186 env(vault.deposit({.depositor = owner, .id = vaultKeylet.key, .amount = ownerFund}));
187 env.close();
188
189 // Vault pseudo-account is now at 9.999e15. Issuer mints 2
190 // more USD. Pre: tecINVARIANT_FAILED at finalize. Post:
191 // tecPRECISION_LOSS proactively. Either way, no value moves.
192 env(vault.deposit({.depositor = issuer, .id = vaultKeylet.key, .amount = usd(2)}),
193 Ter(expected));
194 env.close();
195 };
196
197 {
198 testcase(
199 "bug: VaultDeposit by issuer at IOU edge fires "
200 "tecINVARIANT_FAILED at finalize (pre-fixCleanup3_2_0)");
201 runScenario(cashBasisAll_ - fixCleanup3_2_0, tecINVARIANT_FAILED);
202 }
203 {
204 testcase(
205 "bug: VaultDeposit by issuer at IOU edge rejects with "
206 "tecPRECISION_LOSS proactively (post-fixCleanup3_2_0)");
207 runScenario(cashBasisAll_, tecPRECISION_LOSS);
208 }
209 }
210
211 // Bug: DeltaInfo::makeDelta uses max(scale(after), scale(before)) for
212 // sfAssetsTotal/Available deltas. This is symmetric to
213 // testBugMakeDeltaAnteriorScale but in the opposite direction: a deposit
214 // pushes assetsTotal from just below 1e16 (IOU exponent 0, ULP = 1) to just
215 // above it (exponent 1, ULP = 10). makeDelta picks the coarser *posterior*
216 // scale 1. The trust line balance rounds from atEdge + 2 = 10,000,000,000,000,001
217 // → 1e16, so the pseudo-account delta is only +1 in IOU space.
218 // roundToAsset(+1, scale=1) = 0 fires "deposit must increase vault balance"
219 // even though the state change is consistent at every precision boundary.
220 //
221 // Fix (fixCleanup3_2_0): computeVaultMinScale uses the posterior Number-space
222 // scale of sfAssetsTotal (which retains the full value 10,000,000,000,000,001,
223 // exponent 0), giving minScale = 0. roundToAsset(+1, scale=0) = 1 > 0 and
224 // the invariant passes. However the transactor's own precision guard fires
225 // first (bob pays 2 USD, vault receives only 1 due to IOU rounding), so the
226 // post-amendment result is tecPRECISION_LOSS rather than tesSUCCESS —
227 // the depositor is protected from silently losing 1 USD to rounding.
228 void
230 {
231 using namespace test::jtx;
232
233 auto const runScenario = [this](FeatureBitset features, TER expected) {
234 std::string logs;
235 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
236
237 Account const issuer{"issuer"};
238 Account const alice{"alice"};
239 Account const bob{"bob"};
240
241 env.fund(XRP(100'000), issuer, alice, bob);
242 env.close();
243 env(fset(issuer, asfDefaultRipple));
244 env.close();
245
246 PrettyAsset const usd{issuer["USD"]};
247 // atEdge is the largest IOU value with exponent 0 (ULP = 1).
248 // A deposit of 2 USD brings assetsTotal to 10,000,000,000,000,001
249 // in Number space, crossing the 1e16 boundary in IOU space.
250 STAmount const atEdge{usd.raw(), Number{9'999'999'999'999'999LL}};
251
252 env(trust(alice, STAmount{usd.raw(), 2, 16}));
253 env(trust(bob, usd(100)));
254 env.close();
255 env(pay(issuer, alice, atEdge));
256 env(pay(issuer, bob, usd(2)));
257 env.close();
258
259 Vault const vault{env};
260 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
261 vaultTx[sfScale] = 0;
262 env(vaultTx);
263 env.close();
264
265 // sfAssetsTotal = sfAssetsAvailable = atEdge (exponent 0, ULP = 1)
266 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = atEdge}));
267 env.close();
268
269 // Deposit 2 USD: +2 is sub-ULP at the posterior IOU scale (ULP = 10)
270 // but exact at the Number scale retained by sfAssetsTotal.
271 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = usd(2)}),
272 Ter(expected));
273 env.close();
274 };
275
276 {
277 testcase(
278 "bug: VaultDeposit across IOU scale boundary fires invariant "
279 "(pre-fixCleanup3_2_0)");
280 runScenario(cashBasisAll_ - fixCleanup3_2_0, tecINVARIANT_FAILED);
281 }
282 {
283 testcase(
284 "bug: VaultDeposit across IOU scale boundary succeeds "
285 "(post-fixCleanup3_2_0)");
286 runScenario(cashBasisAll_, tecPRECISION_LOSS);
287 }
288 }
289
290 // Bug: DeltaInfo::makeDelta uses max(scale(after), scale(before)) for the
291 // sfAssetsTotal and sfAssetsAvailable deltas, and visitEntry applies the
292 // same max() for the vault pseudo-account RippleState. When
293 // sfAssetsTotal sits exactly at 1e16 (IOU exponent 1, ULP = 10) and a
294 // withdrawal of 5 USD brings it to 9.999...995e15 (IOU exponent 0,
295 // ULP = 1), all three computations pick the anterior coarser scale 1.
296 // roundToAsset(-5, scale=1) collapses to 0, so the invariant check
297 // vaultPseudoDeltaAssets >= kZero fires even though the state change is
298 // valid and fully consistent at IOU precision.
299 //
300 // Fix (fixCleanup3_2_0): finalize compares the vault pseudo-account and
301 // sfAssetsTotal/Available deltas directly in Number space, bypassing
302 // scale-coarsened rounding.
303 void
305 {
306 using namespace test::jtx;
307
308 auto const runScenario = [this](FeatureBitset features, TER expected) {
309 std::string logs;
310 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
311
312 Account const issuer{"issuer"};
313 Account const alice{"alice"};
314
315 env.fund(XRP(100'000), issuer, alice);
316 env.close();
317 env(fset(issuer, asfDefaultRipple));
318 env.close();
319
320 PrettyAsset const usd{issuer["USD"]};
321 // Trust limit of 2e16, fund exactly 1e16 so deposit lands at the
322 // IOU scale-1 boundary (exponent 1, ULP = 10).
323 STAmount const fundAndDeposit{usd.raw(), Number{1, 16}};
324
325 env(trust(alice, STAmount{usd.raw(), 2, 16}));
326 env.close();
327 env(pay(issuer, alice, fundAndDeposit));
328 env.close();
329
330 Vault const vault{env};
331 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
332 vaultTx[sfScale] = 0;
333 env(vaultTx);
334 env.close();
335
336 // sfAssetsTotal = sfAssetsAvailable = 1e16 (exponent 1, ULP = 10).
337 env(vault.deposit(
338 {.depositor = alice, .id = vaultKeylet.key, .amount = fundAndDeposit}));
339 env.close();
340
341 // Withdraw 5 USD: -5 is sub-ULP at the anterior scale (ULP = 10)
342 // but exact at the posterior scale (ULP = 1). The state change is
343 // consistent; only the invariant's scale selection is wrong.
344 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(5)}),
345 Ter(expected));
346 env.close();
347 };
348
349 {
350 testcase(
351 "bug: VaultWithdraw across IOU scale boundary fires invariant "
352 "(pre-fixCleanup3_2_0)");
353 runScenario(cashBasisAll_ - fixCleanup3_2_0, tecINVARIANT_FAILED);
354 }
355 {
356 testcase(
357 "bug: VaultWithdraw across IOU scale boundary succeeds "
358 "(post-fixCleanup3_2_0)");
359 runScenario(cashBasisAll_, tesSUCCESS);
360 }
361 }
362
363 // Bug: when a depositor's IOU trustline balance is very large (e.g.
364 // ~1e17), adding a small deposit (e.g. 1 USD) leaves sfAssetsTotal
365 // unchanged at IOU precision because the increment is sub-ULP at the
366 // vault's current asset scale. The vault records the deposit, mints
367 // shares, and decrements the depositor's trustline, but sfAssetsTotal
368 // does not change — the conservation invariant fires because the rail
369 // delta is zero.
370 //
371 // Two sub-cases are exercised:
372 // 1. First-ever deposit into an empty vault: the depositor's own
373 // trustline has a large balance so 1 USD canonicalizes to zero
374 // when written back through the IOU rail.
375 // 2. Subsequent deposit after the vault already holds a large
376 // sfAssetsTotal: a different depositor (bob, with a small balance)
377 // sends 1 USD, which again rounds to zero at the vault's coarse
378 // asset scale.
379 //
380 // Fix (fixCleanup3_2_0): the deposit transactor checks whether
381 // roundToAsset(amount, vault_scale) == 0 and rejects early with
382 // tecPRECISION_LOSS before any state is modified.
383 void
385 {
386 using namespace test::jtx;
387 auto const runScenario = [this](FeatureBitset features, TER expected) {
388 std::string logs;
389 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
390
391 Account const issuer{"issuer"};
392 Account const alice{"alice"};
393 Account const bob{"bob"};
394
395 env.fund(XRP(100'000), issuer, alice, bob);
396 env.close();
397
398 env(fset(issuer, asfDefaultRipple));
399 env.close();
400
401 PrettyAsset const usd{issuer["USD"]};
402
403 STAmount const trustLimit{usd.raw(), Number{99'999'999'999'999'999LL}};
404 STAmount const aliceFund{usd.raw(), Number{99'999'999'999'999'999LL}};
405
406 env(trust(alice, trustLimit));
407 env(trust(bob, trustLimit));
408 env.close();
409
410 env(pay(issuer, alice, aliceFund));
411 env(pay(issuer, bob, usd(1000)));
412 env.close();
413
414 Vault const vault{env};
415
416 // Scale=0 so sfAssetsTotal stores whole USD
417 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
418 vaultTx[sfScale] = 0;
419 env(vaultTx);
420 env.close();
421
422 // Alice's deposit canonicalizes to zero at her own trustline scale
423 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1)}),
424 Ter(expected));
425
426 // Increase vault-scale
427 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = aliceFund}));
428 env.close();
429
430 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = usd(1)}),
431 Ter(expected));
432 env.close();
433 };
434
435 {
436 // fixCleanup3_4_0 has to be off as well: its depositor-side check
437 // rejects alice's deposit for the same reason, so the invariant is
438 // only reachable with neither guard in place.
439 testcase(
440 "bug: VaultDeposit below Vault precision canonicalized to zero "
441 "(pre-fixCleanup3_2_0)");
442 // Also remove fixCleanup3_4_0 so the VaultDeposit clamp
443 // introduced by that amendment does not short-circuit this
444 // pre-fixCleanup3_2_0 scenario with tecPRECISION_LOSS.
445 runScenario(cashBasisAll_ - fixCleanup3_2_0 - fixCleanup3_4_0, tecINVARIANT_FAILED);
446 }
447 {
448 testcase(
449 "bug: VaultDeposit below Vault precision canonicalized to zero "
450 "(post-fixCleanup3_2_0)");
451 runScenario(cashBasisAll_, tecPRECISION_LOSS);
452 }
453 }
454
455 // A deposit does not transfer the requested amount. It transfers the
456 // request truncated to a whole number of shares and converted back, which
457 // can be strictly smaller. When that smaller value is below half a ULP at
458 // the depositor's own trust-line scale, the debit rounds away to nothing:
459 // the depositor pays nothing, while the vault books the assets and mints
460 // shares. ValidVault catches the desync at finalize time.
461 //
462 // Only a non-power-of-ten assets-to-shares ratio is needed, and that
463 // happens through ordinary use: LoanPay books accrued interest into
464 // sfAssetsTotal without minting shares.
465 //
466 // The fixCleanup3_2_0 guard in preclaim does not help, because it tests the
467 // raw requested amount, which is large enough to survive the rounding.
468 // Post-fixCleanup3_4_0 the post-truncation value is checked as well and the
469 // deposit is rejected with tecPRECISION_LOSS before anything moves.
470 void
472 {
473 using namespace test::jtx;
474 using namespace loan_broker;
475 using namespace loan;
476
477 // How bob's trust line is set up before he deposits. Holding is the plain case: a large
478 // positive balance whose ULP swallows the debit. InDebt is the case where the stored
479 // balance and the spendable amount diverge: bob owes the issuer 1e16, and the issuer's
480 // limit on the same line lets him spend 1000 anyway. Reading the spendable amount there
481 // reports a small, finely scaled number, while the rounding of the debit is still governed
482 // by the 1e16 he actually holds.
483 enum class Line { Holding, InDebt };
484
485 auto const runScenario = [this](FeatureBitset features, Line line, TER expected) {
486 std::string logs;
487 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
488
489 Account const issuer{"issuer"};
490 Account const alice{"alice"};
491 Account const carol{"carol"};
492 Account const bob{"bob"};
493
494 env.fund(XRP(100'000), issuer, alice, carol, bob);
495 env.close();
496 env(fset(issuer, asfDefaultRipple));
497 env.close();
498
499 PrettyAsset const usd{issuer["USD"]};
500 PrettyAsset const bobUsd{bob["USD"]};
501 STAmount const trustLimit{usd.raw(), Number{99'999'999'999'999'999LL}};
502 // Bob's balance sits exactly on a multiple-of-10 boundary at the
503 // 1e16 IOU precision cusp, where one ULP is 10.
504 STAmount const bobEdge{usd.raw(), Number{10'000'000'000'000'010LL}};
505 STAmount const bobDebt{bobUsd.raw(), Number{10'000'000'000'000'000LL}};
506 STAmount const oppositeLimit{bobUsd.raw(), Number{10'000'000'000'001'000LL}};
507
508 env(trust(alice, trustLimit));
509 env(trust(carol, trustLimit));
510 env(trust(bob, trustLimit));
511 env.close();
512
513 env(pay(issuer, alice, usd(1'000)));
514 env(pay(issuer, carol, usd(1'000)));
515 if (line == Line::Holding)
516 {
517 env(pay(issuer, bob, bobEdge));
518 }
519 else
520 {
521 // The issuer trusts bob's own USD, so bob can issue 1e16 back and still have
522 // 1000 of spendable room left on the same line.
523 env(trust(issuer, oppositeLimit));
524 env.close();
525 env(pay(bob, issuer, bobDebt));
526 }
527 env.close();
528
529 Vault const vault{env};
530 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
531 vaultTx[sfScale] = 0;
532 env(vaultTx);
533 env.close();
534
535 // Alice deposits 1000 USD, minting 1000 shares 1:1.
536 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1'000)}));
537 env.close();
538
539 // A loan broker on the vault, then a bullet loan at 24% interest:
540 // a single payment, one year out.
541 auto const brokerKeylet =
542 keylet::loanBroker(alice.id(), SeqProxy::rawSequence(env.seq(alice)));
543 env(set(alice, vaultKeylet.key));
544 env.close();
545
546 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
547 env(set(carol, brokerKeylet.key, usd(1'000).value()),
548 loan::kInterestRate(percentageToTenthBips(24)),
549 kGracePeriod(60),
550 kPaymentInterval(365 * 24 * 60 * 60),
551 kPaymentTotal(1),
552 Sig(sfCounterpartySignature, alice),
553 Fee(env.current()->fees().base * 2),
554 Ter(tesSUCCESS));
555 env.close();
556
557 // Advance to just before the single payment falls due and let carol
558 // repay principal plus interest. LoanPay is what books the accrued
559 // interest into sfAssetsTotal; under cash-basis accounting LoanSet
560 // alone does not. Share supply stays at 1000, so
561 // assetsTotal/sharesTotal becomes 1240/1000.
562 env.close(std::chrono::seconds{(365 * 24 * 60 * 60) - 3600});
563 env(pay(carol, loanKeylet.key, usd(2'000).value()), Ter(tesSUCCESS));
564 env.close();
565
566 // Pin the ratio the rest of the scenario reasons about, so the test cannot quietly
567 // stop exercising the bug if the setup drifts.
568 auto const sleVault = env.le(vaultKeylet);
569 BEAST_EXPECT(sleVault && sleVault->at(sfAssetsTotal) == Number{1'240});
570 auto const sleIssuance = env.le(keylet::mptokenIssuance(sleVault->at(sfShareMPTID)));
571 BEAST_EXPECT(sleIssuance && sleIssuance->at(sfOutstandingAmount) == 1'000);
572
573 // Bob deposits 6 USD, which rounds to 10 at his own trust-line
574 // scale and so clears the fixCleanup3_2_0 guard. But
575 // floor(1000 * 6 / 1240) is 4 shares, worth 4 * 1240 / 1000 = 4.96,
576 // and that is below half a ULP of his balance, so it rounds away to
577 // nothing when subtracted.
578 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = usd(6)}),
579 Ter(expected));
580 env.close();
581 };
582
583 // Strip featureLendingProtocolV1_1: this scenario runs an
584 // open-ended vault through deposit/broker/loan/repay/deposit,
585 // which spans both Subscription and post-loan lifetime — a phase
586 // pattern that only makes sense on open-ended vaults. The gate
587 // added by LP V1.1 is unrelated to the truncation bug asserted
588 // here.
589 auto const legacy = cashBasisAll_ - featureLendingProtocolV1_1;
590 {
591 testcase(
592 "bug: VaultDeposit share truncation lets depositor debit "
593 "round away to zero (pre-fixCleanup3_4_0)");
594 runScenario(legacy - fixCleanup3_4_0, Line::Holding, tecINVARIANT_FAILED);
595 }
596 {
597 testcase(
598 "bug: VaultDeposit share truncation lets depositor debit "
599 "round away to zero (pre-fixCleanup3_2_0 and pre-fixCleanup3_4_0)");
600 runScenario(
601 legacy - fixCleanup3_2_0 - fixCleanup3_4_0, Line::Holding, tecINVARIANT_FAILED);
602 }
603 {
604 testcase(
605 "bug: VaultDeposit share truncation rejected with "
606 "tecPRECISION_LOSS (post-fixCleanup3_4_0)");
607 runScenario(legacy, Line::Holding, tecPRECISION_LOSS);
608 }
609 {
610 testcase(
611 "bug: VaultDeposit share truncation rejected with "
612 "tecPRECISION_LOSS (post-fixCleanup3_4_0, pre-fixCleanup3_2_0)");
613 runScenario(legacy - fixCleanup3_2_0, Line::Holding, tecPRECISION_LOSS);
614 }
615 {
616 testcase(
617 "bug: VaultDeposit share truncation against a debt balance "
618 "round away to zero (pre-fixCleanup3_4_0)");
619 runScenario(legacy - fixCleanup3_4_0, Line::InDebt, tecINVARIANT_FAILED);
620 }
621 {
622 testcase(
623 "bug: VaultDeposit share truncation against a debt balance rejected with "
624 "tecPRECISION_LOSS (post-fixCleanup3_4_0)");
625 runScenario(legacy, Line::InDebt, tecPRECISION_LOSS);
626 }
627 }
628
629 // Bug: ValidVault::visitEntry computes destinationDelta.scale as
630 // max(before_exponent, after_exponent) for RippleState entries. When a
631 // withdrawal credits a destination whose IOU balance sits just below a
632 // power-of-10 boundary (atEdge = 9'999'999'999'999'999), the post-credit
633 // STAmount rounds up one exponent (exponent 0 → 1), making
634 // destinationDelta.scale = 1. The invariant then calls
635 // roundToAsset(+2 USD, scale=1) = 0 and incorrectly fires
636 // "withdrawal must increase destination balance".
637 //
638 // Fix (fixCleanup3_2_0): finalize compares destination delta directly in
639 // Number space, bypassing scale-coarsened rounding. The transaction
640 // itself succeeds because the effective IOU credit is non-trivial at
641 // Number precision even though the STAmount exponent shifted.
642 void
644 {
645 using namespace test::jtx;
646
647 enum class DestKind : bool { ThirdParty = false, Self = true };
648
649 auto const runScenario = [this](FeatureBitset features, DestKind destKind, TER expected) {
650 std::string logs;
651 Env env(*this, features, std::make_unique<test::CaptureLogs>(&logs));
652
653 Account const issuer{"issuer"};
654 Account const alice{"alice"};
655 Account const bob{"bob"};
656
657 env.fund(XRP(100'000), issuer, alice, bob);
658 env.close();
659 env(fset(issuer, asfDefaultRipple));
660 env.close();
661
662 PrettyAsset const usd{issuer["USD"]};
663 STAmount const aliceLimit{usd.raw(), 2, 16};
664 STAmount const bobLimit{usd.raw(), 2, 16};
665 STAmount const atEdge{usd.raw(), Number{9'999'999'999'999'999LL}};
666
667 env(trust(alice, aliceLimit));
668 if (destKind == DestKind::ThirdParty)
669 env(trust(bob, bobLimit));
670 env.close();
671
672 env(pay(issuer, alice, usd(1'000)));
673 if (destKind == DestKind::ThirdParty)
674 env(pay(issuer, bob, atEdge));
675 env.close();
676
677 Vault const vault{env};
678 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
679 vaultTx[sfScale] = 0;
680 env(vaultTx);
681 env.close();
682
683 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(1'000)}));
684 env.close();
685
686 // For the self-destination case, push alice's own trust line to
687 // the IOU edge so the next withdraw inflow crosses the boundary.
688 if (destKind == DestKind::Self)
689 {
690 env(pay(issuer, alice, atEdge));
691 env.close();
692 }
693
694 auto tx = vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(2)});
695 if (destKind == DestKind::ThirdParty)
696 tx[sfDestination] = bob.human();
697 env(tx, Ter(expected));
698 env.close();
699 };
700
701 {
702 testcase(
703 "bug: VaultWithdraw to third-party at IOU edge fires invariant "
704 "(pre-fixCleanup3_2_0)");
705 runScenario(cashBasisAll_ - fixCleanup3_2_0, DestKind::ThirdParty, tecINVARIANT_FAILED);
706 }
707 {
708 testcase(
709 "bug: VaultWithdraw to third-party at IOU edge succeeds "
710 "(post-fixCleanup3_2_0)");
711 runScenario(cashBasisAll_, DestKind::ThirdParty, tesSUCCESS);
712 }
713 {
714 testcase(
715 "bug: VaultWithdraw to self at IOU edge fires invariant "
716 "(pre-fixCleanup3_2_0)");
717 runScenario(cashBasisAll_ - fixCleanup3_2_0, DestKind::Self, tecINVARIANT_FAILED);
718 }
719 {
720 testcase(
721 "bug: VaultWithdraw to self at IOU edge succeeds "
722 "(post-fixCleanup3_2_0)");
723 runScenario(cashBasisAll_, DestKind::Self, tesSUCCESS);
724 }
725 }
726
727 // Bug: a debit can be genuinely non-zero yet still be dust relative to a
728 // sfAssetsTotal/sfAssetsAvailable large enough to exceed STAmount's precision, e.g.
729 // AssetsTotal 2e12 minus a 1e-6 debit needs 19 significant digits and rounds straight
730 // back to 2e12. The shares still move, so ValidVault later fails with "must decrease
731 // vault balance" instead of a clean upfront rejection.
732 //
733 // Fix (fixCleanup3_4_0): reject upfront with tecPRECISION_LOSS if the debit would
734 // canonicalize back to the prior stored value.
735 //
736 // With a single depositor AssetsTotal == AssetsAvailable, so both
737 // debitIsNonZeroDust operands trip together here. LoanRounding_test's
738 // "dust debit vs AssetsTotal only" case isolates the AssetsTotal operand
739 // via a heavily-loaned vault.
740 void
742 {
743 using namespace test::jtx;
744
745 // Fund a single depositor and have them deposit `total` USD in one shot (default
746 // scale 6, so shares mint at exactly total*1e6).
747 auto const seedVault = [](Env& env, Number const& total) {
748 Account const issuer{"issuer"};
749 Account const owner{"owner"};
750 Account const holder{"holder"};
751
752 env.fund(XRP(1'000'000), issuer, owner, holder);
753 env.close();
754 env(fset(issuer, asfAllowTrustLineClawback));
755 env.close();
756
757 PrettyAsset const usd{issuer["USD"]};
758 env(trust(holder, usd(100'000'000'000'000LL)));
759 env.close();
760 env(pay(issuer, holder, usd(total)));
761 env.close();
762
763 Vault const vault{env};
764 auto const [tx, keylet] = vault.create({.owner = owner, .asset = usd.raw()});
765 env(tx);
766 env.close();
767 env(vault.deposit({.depositor = holder, .id = keylet.key, .amount = usd(total)}),
768 Ter(tesSUCCESS));
769 env.close();
770
771 return keylet;
772 };
773
774 {
775 auto const runScenario = [&](FeatureBitset features, TER expected) {
776 Env env(*this, features);
777 Number const total{2, 12};
778 auto const keylet = seedVault(env, total);
779
780 Account const issuer{"issuer"};
781 PrettyAsset const usd{issuer["USD"]};
782
783 // 1 share's worth of assets: 1e-6, below AssetsTotal's storage precision.
784 env(Vault::clawback({
785 .issuer = issuer,
786 .id = keylet.key,
787 .holder = Account{"holder"},
788 .amount = usd(Number{1, -6}).value(),
789 }),
790 Ter(expected));
791 env.close();
792 };
793
794 testcase("bug: VaultClawback dust debit fires invariant (pre-fixCleanup3_4_0)");
795 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
796 testcase("bug: VaultClawback dust debit rejected cleanly (post-fixCleanup3_4_0)");
797 runScenario(cashBasisAll_, tecPRECISION_LOSS);
798 }
799
800 {
801 auto const runScenario = [&](FeatureBitset features, TER expected) {
802 Env env(*this, features);
803 Number const total{2, 12};
804 auto const keylet = seedVault(env, total);
805
806 MPTIssue const share{env.le(keylet)->at(sfShareMPTID)};
807
808 // Redeem 1 share, worth 1e-6 assets, below AssetsTotal's storage precision.
809 env(Vault::withdraw({
810 .depositor = Account{"holder"},
811 .id = keylet.key,
812 .amount = STAmount{share, 1},
813 }),
814 Ter(expected));
815 env.close();
816 };
817
818 testcase("bug: VaultWithdraw dust debit fires invariant (pre-fixCleanup3_4_0)");
819 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
820 testcase("bug: VaultWithdraw dust debit rejected cleanly (post-fixCleanup3_4_0)");
821 runScenario(cashBasisAll_, tecPRECISION_LOSS);
822 }
823 }
824
825 // Scale 15 seed + deposit 5: pre-fix credited > paid; post-fix credited <= paid.
826 // fixCleanup3_2_0 is off so the deposit is not rounded down to the live scale first.
827 void
829 {
830 using namespace test::jtx;
831
832 auto const runScenario = [this](FeatureBitset features, bool expectOvercredit) {
833 Env env(*this, features);
834 Account const owner{"owner"};
835 Account const issuer{"issuer"};
836 Account const depositor{"depositor"};
837 env.fund(XRP(1'000'000), owner, issuer, depositor);
838 env.close();
839
840 PrettyAsset const usd{issuer["USD"]};
841 Number const seed{9'999'999'999'999'999LL, -15};
842 Number const deposit{5};
843
844 env(trust(depositor, usd(1'000'000'000)));
845 env.close();
846 env(pay(issuer, depositor, usd(deposit)));
847 env.close();
848
849 Vault const vault{env};
850 auto [tx, keylet] = vault.create({.owner = owner, .asset = usd.raw()});
851 tx[sfScale] = 15;
852 env(tx);
853 env.close();
854 env(vault.deposit({.depositor = issuer, .id = keylet.key, .amount = usd(seed)}));
855 env.close();
856
857 Number const totalBefore = env.le(keylet)->at(sfAssetsTotal);
858 Number const depositorBefore = env.balance(depositor, usd.raw()).number();
859
860 env(vault.deposit({.depositor = depositor, .id = keylet.key, .amount = usd(deposit)}));
861 env.close();
862
863 Number const totalAfter = env.le(keylet)->at(sfAssetsTotal);
864 Number const depositorAfter = env.balance(depositor, usd.raw()).number();
865 Number const paid = depositorBefore - depositorAfter;
866 Number const credited = totalAfter - totalBefore;
867
868 if (expectOvercredit)
869 {
870 BEAST_EXPECTS(
871 credited > paid,
872 "AssetsTotal credited " + to_string(credited) + " for a payment of " +
873 to_string(paid) + ", expected an overcredit");
874 }
875 else
876 {
877 BEAST_EXPECTS(
878 credited <= paid,
879 "AssetsTotal credited " + to_string(credited) + " for a payment of " +
880 to_string(paid));
881 }
882 };
883
884 testcase(
885 "bug: VaultDeposit overcredits across an IOU scale boundary "
886 "(pre-fixCleanup3_4_0)");
887 runScenario(cashBasisAll_ - fixCleanup3_2_0 - fixCleanup3_4_0, true);
888
889 testcase(
890 "bug: VaultDeposit no longer overcredits across an IOU scale boundary "
891 "(post-fixCleanup3_4_0)");
892 runScenario(cashBasisAll_, false);
893 }
894
895 // 1e17 IOU at scale 0. Withdraw all-but-one, then the last share:
896 // pre-fix tecINVARIANT_FAILED, post-fix tesSUCCESS.
897 void
899 {
900 using namespace test::jtx;
901
902 auto const runScenario = [this](FeatureBitset features, TER expected) {
903 Env env(*this, features);
904 Account const owner{"owner"};
905 Account const issuer{"issuer"};
906 Account const holder{"holder"};
907 env.fund(XRP(1'000'000), owner, issuer, holder);
908 env.close();
909
910 PrettyAsset const usd{issuer["USD"]};
911 env(trust(holder, usd(Number{1, 18})));
912 env.close();
913 env(pay(issuer, holder, usd(Number{1, 17})));
914 env.close();
915
916 Vault const vault{env};
917 auto [tx, keylet] = vault.create({.owner = owner, .asset = usd.raw()});
918 tx[sfScale] = 0;
919 env(tx);
920 env.close();
921 env(vault.deposit(
922 {.depositor = holder, .id = keylet.key, .amount = usd(Number{1, 17})}));
923 env.close();
924
925 MPTIssue const share{env.le(keylet)->at(sfShareMPTID)};
926 std::int64_t const allButOne = 100'000'000'000'000'000LL - 1;
927 env(vault.withdraw(
928 {.depositor = holder, .id = keylet.key, .amount = STAmount{share, allButOne}}));
929 env.close();
930
931 env(vault.withdraw(
932 {.depositor = holder, .id = keylet.key, .amount = STAmount{share, 1}}),
933 Ter(expected));
934 env.close();
935 };
936
937 testcase(
938 "bug: VaultWithdraw permanently locks a large IOU vault "
939 "(pre-fixCleanup3_4_0)");
940 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
941 testcase(
942 "bug: VaultWithdraw no longer locks a large IOU vault "
943 "(post-fixCleanup3_4_0)");
944 runScenario(cashBasisAll_, tesSUCCESS);
945 }
946
947 // VaultDeposit::preclaim uses accountHolds(..., SpendableHandling::
948 // shFULL_BALANCE), which for an IOU asset adds the counterparty's
949 // LowLimit/HighLimit to the depositor's raw balance (TokenHelpers.cpp:
950 // getTrustLineBalance with includeOppositeLimit=true). When the
951 // depositor's raw balance < deposit amount but raw + opposite limit >=
952 // amount, preclaim is satisfied. doApply then calls
953 // directSendNoFeeIOU, which unconditionally subtracts saAmount from
954 // saBalance — driving the trust line negative — and returns tesSUCCESS.
955 // The post-send sanity check uses the default shSIMPLE_BALANCE (no
956 // opposite-limit add), sees a negative balance, and returns tefINTERNAL.
957 void
959 {
960 auto const runTest = [&](FeatureBitset f, TER expected) {
961 using namespace test::jtx;
962 using namespace std::literals;
963
964 Env env{*this, f};
965 Account const gw{"gateway"};
966 Account const owner{"owner"};
967 Account const depositor{"depositor"};
968
969 env.fund(XRP(10000), gw, owner, depositor);
970 env.close();
971
972 // Gateway with DefaultRipple so vault creation on its IOU works.
973 env(fset(gw, asfDefaultRipple));
974 env.close();
975
976 // Depositor opens a trust line to gateway and receives a small
977 // balance.
978 PrettyAsset const usd = gw["USD"];
979 env.trust(usd(1000), depositor);
980 env(pay(gw, depositor, usd(100))); // raw trust-line balance: 100
981 env.close();
982
983 // Key precondition: gateway sets a non-zero limit on the same
984 // RippleState — the "opposite field" from depositor's perspective.
985 // This is what inflates shFULL_BALANCE in preclaim above the raw
986 // balance.
987 env(trust(gw, depositor["USD"](1000)));
988 env.close();
989
990 // Create the IOU vault.
991 Vault const vault{env};
992 auto [vaultTx, keylet] = vault.create({.owner = owner, .asset = usd});
993 env(vaultTx);
994 env.close();
995
996 // Submit a deposit of 500 USD:
997 // - raw balance: 100 USD
998 // - opposite limit (gw's side): 1000 USD
999 // - preclaim sees 100 + 1000 = 1100, passes (>= 500)
1000 // - doApply transfers 500, depositor's trust-line balance
1001 // becomes -400
1002 // - sanity check at VaultDeposit.cpp:256 fires
1003 // - tx returns tefINTERNAL (BUG — should be tesSUCCESS.
1004 auto const depositTx =
1005 vault.deposit({.depositor = depositor, .id = keylet.key, .amount = usd(500)});
1006 env(depositTx, Ter(expected));
1007 env.close();
1008 };
1009
1010 {
1011 testcase(
1012 "IOU vault deposit exceeding depositor's balance but "
1013 "within counterparty's trust limit, pre-fixCleanup3_2_0 "
1014 "(tefINTERNAL)");
1015 runTest(cashBasisAll_ - fixCleanup3_2_0, tefINTERNAL);
1016 }
1017 {
1018 testcase(
1019 "IOU vault deposit exceeding depositor's balance but "
1020 "within counterparty's trust limit, post-fixCleanup3_2_0 "
1021 "(tesSUCCESS)");
1022 runTest(cashBasisAll_, tesSUCCESS);
1023 }
1024 }
1025
1026 // Reproduction: canWithdraw IOU limit check bypassed when
1027 // withdrawal amount is specified in shares (MPT) rather than in assets.
1028 void
1030 {
1031 using namespace test::jtx;
1032 testcase("Bug6 - limit bypass with share-denominated withdrawal");
1033
1034 auto const allAmendments = cashBasisAll_ | featureSingleAssetVault;
1035
1036 for (auto const& features : {allAmendments, allAmendments - fixCleanup3_1_3})
1037 {
1038 bool const withFix = features[fixCleanup3_1_3];
1039
1040 Env env{*this, features};
1041 Account const owner{"owner"};
1042 Account const issuer{"issuer"};
1043 Account const depositor{"depositor"};
1044 Account const charlie{"charlie"};
1045 Vault const vault{env};
1046
1047 env.fund(XRP(1000), issuer, owner, depositor, charlie);
1048 env(fset(issuer, asfAllowTrustLineClawback));
1049 env.close();
1050
1051 PrettyAsset const asset = issuer["IOU"];
1052 env.trust(asset(1000), owner);
1053 env.trust(asset(1000), depositor);
1054 env(pay(issuer, owner, asset(200)));
1055 env(pay(issuer, depositor, asset(200)));
1056 env.close();
1057
1058 // Charlie gets a LOW trustline limit of 5
1059 env.trust(asset(5), charlie);
1060 env.close();
1061
1062 auto const [tx, keylet] = vault.create({.owner = owner, .asset = asset});
1063 env(tx);
1064 env.close();
1065
1066 auto const depositTx =
1067 vault.deposit({.depositor = depositor, .id = keylet.key, .amount = asset(100)});
1068 env(depositTx);
1069 env.close();
1070
1071 // Get the share MPT info
1072 auto const vaultSle = env.le(keylet);
1073 if (!BEAST_EXPECT(vaultSle))
1074 return;
1075 auto const mptIssuanceID = vaultSle->at(sfShareMPTID);
1076 MPTIssue const shares(mptIssuanceID);
1077 PrettyAsset const share(shares);
1078
1079 // CONTROL: Withdraw 10 IOU (asset-denominated) to charlie.
1080 // Charlie's limit is 5, so this should be rejected with tecNO_LINE
1081 // regardless of the amendment.
1082 {
1083 auto withdrawTx =
1084 vault.withdraw({.depositor = depositor, .id = keylet.key, .amount = asset(10)});
1085 withdrawTx[sfDestination] = charlie.human();
1086 env(withdrawTx, Ter{tecNO_LINE});
1087 env.close();
1088 }
1089 auto const charlieBalanceBefore = env.balance(charlie, asset.raw().get<Issue>());
1090
1091 // Withdraw the equivalent amount in shares to charlie.
1092 // Post-fix: rejected (tecNO_LINE) because the share amount is
1093 // converted to assets and the trustline limit is checked.
1094 // Pre-fix: succeeds (tesSUCCESS) because the limit check was
1095 // skipped for share-denominated withdrawals.
1096 {
1097 auto withdrawTx = vault.withdraw({
1098 .depositor = depositor,
1099 .id = keylet.key,
1100 .amount = STAmount(share, 10'000'000),
1101 });
1102 withdrawTx[sfDestination] = charlie.human();
1103 env(withdrawTx, Ter{withFix ? TER{tecNO_LINE} : TER{tesSUCCESS}});
1104 env.close();
1105
1106 auto const charlieBalanceAfter = env.balance(charlie, asset.raw().get<Issue>());
1107 if (withFix)
1108 {
1109 // Post-fix: charlie's balance is unchanged — the withdrawal
1110 // was correctly rejected despite being share-denominated.
1111 BEAST_EXPECT(charlieBalanceAfter == charlieBalanceBefore);
1112 }
1113 else
1114 {
1115 // Pre-fix: charlie received the assets, bypassing the
1116 // trustline limit.
1117 BEAST_EXPECT(charlieBalanceAfter > charlieBalanceBefore);
1118 }
1119 }
1120 }
1121 }
1122
1123 // Shared setup for testBugClawbackRoundTripOvershoot and
1124 // testBugWithdrawRoundTripOvershoot, which both need a vault at
1125 // assetsTotal=7, sharesTotal=5 and differ only in what they do once
1126 // that state is reached.
1127 //
1128 // The (7, 5) state is reached through ordinary transactions: a 5 USD
1129 // deposit mints 5 shares 1:1, then a loan broker on the vault issues a
1130 // single-payment bullet loan for the full 5 USD at 40% interest. When
1131 // the borrower repays a year later, LoanPay books the 2 USD of accrued
1132 // interest into sfAssetsTotal without minting shares, leaving
1133 // assetsTotal=7 against sharesTotal=5 (see
1134 // testBugDepositShareTruncationSubUlp for the same technique in more
1135 // detail).
1146
1149 {
1150 using namespace test::jtx;
1151 using namespace loan_broker;
1152 using namespace loan;
1153
1154 Account const issuer{"issuer"};
1155 Account const owner{"owner"};
1156 Account const holder{"holder"};
1157 Account const borrower{"borrower"};
1158
1159 env.fund(XRP(10'000), issuer, owner, holder, borrower);
1160 env.close();
1161
1162 env(fset(issuer, asfAllowTrustLineClawback));
1163 env.close();
1164
1165 PrettyAsset const usd = issuer["USD"];
1166 env.trust(usd(1'000), owner);
1167 env.trust(usd(1'000), holder);
1168 env.trust(usd(1'000), borrower);
1169 env.close();
1170
1171 env(pay(issuer, holder, usd(100)));
1172 env(pay(issuer, borrower, usd(100)));
1173 env.close();
1174
1175 Vault const vault{env};
1176 auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = usd});
1177 vaultTx[sfScale] = 0;
1178 env(vaultTx);
1179 env.close();
1180
1181 // Holder deposits 5 USD, minting 5 shares 1:1.
1182 env(vault.deposit({.depositor = holder, .id = vaultKeylet.key, .amount = usd(5)}));
1183 env.close();
1184
1185 // A loan broker on the vault, then a single bullet loan for the
1186 // entire deposit at 40% interest, one payment, one year out.
1187 auto const brokerKeylet =
1188 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
1189 env(set(owner, vaultKeylet.key));
1190 env.close();
1191
1192 auto const loanKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
1193 env(set(borrower, brokerKeylet.key, usd(5).value()),
1194 loan::kInterestRate(percentageToTenthBips(40)),
1195 kGracePeriod(60),
1196 kPaymentInterval(365 * 24 * 60 * 60),
1197 kPaymentTotal(1),
1198 Sig(sfCounterpartySignature, owner),
1199 Fee(env.current()->fees().base * 2),
1200 Ter(tesSUCCESS));
1201 env.close();
1202
1203 // Advance to just before the single payment falls due and let the
1204 // borrower repay principal plus interest. Share supply stays at 5,
1205 // so assetsTotal/sharesTotal becomes 7/5.
1206 env.close(std::chrono::seconds{(365 * 24 * 60 * 60) - 3600});
1207 env(pay(borrower, loanKeylet.key, usd(10).value()), Ter(tesSUCCESS));
1208 env.close();
1209
1210 auto const vaultSle = env.le(vaultKeylet);
1211 if (!BEAST_EXPECT(vaultSle))
1212 return std::nullopt;
1213 auto const mptIssuanceID = vaultSle->at(sfShareMPTID);
1214
1215 Number const initialAssetsTotal = vaultSle->at(sfAssetsTotal);
1216 Number const initialAssetsAvailable = vaultSle->at(sfAssetsAvailable);
1217 BEAST_EXPECT(initialAssetsTotal == usd(7).number());
1218 BEAST_EXPECT(initialAssetsAvailable == usd(7).number());
1219 {
1220 auto const sleIssuance = env.le(keylet::mptokenIssuance(mptIssuanceID));
1221 if (!BEAST_EXPECT(sleIssuance))
1222 return std::nullopt;
1223 BEAST_EXPECT(sleIssuance->getFieldU64(sfOutstandingAmount) == 5);
1224 }
1225
1227 .issuer = issuer,
1228 .holder = holder,
1229 .usd = usd,
1230 .vault = vault,
1231 .vaultKeylet = vaultKeylet,
1232 .initialAssetsTotal = initialAssetsTotal,
1233 .initialAssetsAvailable = initialAssetsAvailable,
1234 };
1235 }
1236
1237 // VaultClawback::assetsToClawback converts clawbackAmount to shares
1238 // with round-to-nearest, then round-trips back to assets. When shares
1239 // round up, assetsRecovered can exceed clawbackAmount.
1240 //
1241 // Repro: assetsTotal=7, sharesTotal=5, request 4:
1242 // shares = round(20/7) = 3, assets = 7*3/5 = 4.2 > 4.
1243 //
1244 // Post-fixCleanup3_4_0: truncate shares so assetsRecovered <=
1245 // clawbackAmount by construction.
1246 void
1248 {
1249 using namespace test::jtx;
1250
1251 auto const runScenario = [this](FeatureBitset features, bool withFix) {
1252 // This regression requires the open-ended vault lifecycle: deposit,
1253 // originate and repay a loan, then claw back shares. LP V1.1
1254 // independently rejects attaching a broker to an open-ended vault.
1255 Env env{*this, features - featureLendingProtocolV1_1};
1256
1257 auto const setup = makeRoundTripOvershootVault(env);
1258 if (!BEAST_EXPECT(setup))
1259 return;
1260
1261 auto const clawbackAmount = setup->usd(4);
1262 env(setup->vault.clawback({
1263 .issuer = setup->issuer,
1264 .id = setup->vaultKeylet.key,
1265 .holder = setup->holder,
1266 .amount = clawbackAmount.value(),
1267 }));
1268
1269 auto const vaultSleAfter = env.current()->read(setup->vaultKeylet);
1270 if (!BEAST_EXPECT(vaultSleAfter))
1271 return;
1272 Number const finalAssetsTotal = vaultSleAfter->at(sfAssetsTotal);
1273 Number const assetsRecovered = setup->initialAssetsTotal - finalAssetsTotal;
1274 Number const clawbackNum = clawbackAmount.number();
1275
1276 Number const expectedPost{28LL, -1};
1277 Number const expectedPre{42LL, -1};
1278 if (withFix)
1279 {
1280 BEAST_EXPECT(assetsRecovered <= clawbackNum);
1281 BEAST_EXPECT(assetsRecovered == expectedPost);
1282 }
1283 else
1284 {
1285 BEAST_EXPECT(assetsRecovered > clawbackNum);
1286 BEAST_EXPECT(assetsRecovered == expectedPre);
1287 }
1288 };
1289
1290 {
1291 testcase(
1292 "bug: VaultClawback round-trip overshoot lets issuer recover "
1293 "more than requested (pre-fixCleanup3_4_0)");
1294 runScenario(cashBasisAll_ - fixCleanup3_4_0, false);
1295 }
1296 {
1297 testcase(
1298 "bug: VaultClawback round-trip overshoot is clamped so "
1299 "assetsRecovered <= clawbackAmount (post-fixCleanup3_4_0)");
1300 runScenario(cashBasisAll_, true);
1301 }
1302 }
1303
1304 // Same root cause as testBugClawbackRoundTripOvershoot on the
1305 // withdraw path. Also bypasses the preclaim canWithdraw check, which
1306 // validates destination limits against the requested amount only.
1307 //
1308 // Repro: assetsTotal=7, sharesTotal=5, request 4:
1309 // pre-fix : shares = round(20/7) = 3, assets = 7*3/5 = 4.2 > 4.
1310 // post-fix: shares = floor(20/7) = 2, assets = 7*2/5 = 2.8 <= 4.
1311 void
1313 {
1314 using namespace test::jtx;
1315
1316 auto const runScenario = [this](FeatureBitset features, bool withFix) {
1317 // This regression requires the open-ended vault lifecycle: deposit,
1318 // originate and repay a loan, then withdraw shares. LP V1.1
1319 // independently rejects attaching a broker to an open-ended vault.
1320 Env env{*this, features - featureLendingProtocolV1_1};
1321
1322 auto const setup = makeRoundTripOvershootVault(env);
1323 if (!BEAST_EXPECT(setup))
1324 return;
1325
1326 auto const requested = setup->usd(4);
1327 env(setup->vault.withdraw({
1328 .depositor = setup->holder,
1329 .id = setup->vaultKeylet.key,
1330 .amount = requested.value(),
1331 }));
1332
1333 auto const vaultSleAfter = env.current()->read(setup->vaultKeylet);
1334 if (!BEAST_EXPECT(vaultSleAfter))
1335 return;
1336 Number const finalAssetsTotal = vaultSleAfter->at(sfAssetsTotal);
1337 Number const assetsWithdrawn = setup->initialAssetsTotal - finalAssetsTotal;
1338 Number const requestedNum = requested.number();
1339
1340 Number const expectedPost{28LL, -1};
1341 Number const expectedPre{42LL, -1};
1342 if (withFix)
1343 {
1344 BEAST_EXPECT(assetsWithdrawn <= requestedNum);
1345 BEAST_EXPECT(assetsWithdrawn == expectedPost);
1346 }
1347 else
1348 {
1349 BEAST_EXPECT(assetsWithdrawn > requestedNum);
1350 BEAST_EXPECT(assetsWithdrawn == expectedPre);
1351 }
1352 };
1353
1354 {
1355 testcase(
1356 "bug: VaultWithdraw round-trip overshoot delivers more than "
1357 "requested (pre-fixCleanup3_4_0)");
1358 runScenario(cashBasisAll_ - fixCleanup3_4_0, false);
1359 }
1360 {
1361 testcase(
1362 "bug: VaultWithdraw round-trip overshoot is clamped so "
1363 "assetsWithdrawn <= requested (post-fixCleanup3_4_0)");
1364 runScenario(cashBasisAll_, true);
1365 }
1366 }
1367
1377
1378 // Impairing a 1,000 loan in a 10,000 vault leaves AssetsAvailable=9,000
1379 // and AssetsTotal=10,000. otherDeposit > 0 splits the shares, 0 leaves
1380 // holder as the sole shareholder.
1383 {
1384 using namespace test::jtx;
1385 using namespace loan_broker;
1386 using namespace loan;
1387
1388 Account const issuer{"issuer"};
1389 Account const owner{"owner"};
1390 Account const holder{"holder"};
1391 Account const other{"other"};
1392 Account const borrower{"borrower"};
1393
1394 env.fund(XRP(100'000), issuer, owner, holder, other, borrower);
1395 env.close();
1396
1397 env(fset(issuer, asfAllowTrustLineClawback));
1398 env(fset(issuer, asfDefaultRipple));
1399 env.close();
1400
1401 PrettyAsset const usd = issuer["USD"];
1402 env.trust(usd(100'000), owner);
1403 env.trust(usd(100'000), holder);
1404 env.trust(usd(100'000), other);
1405 env.trust(usd(100'000), borrower);
1406 env.close();
1407
1408 int const holderDeposit = 10'000 - otherDeposit;
1409 env(pay(issuer, holder, usd(holderDeposit)));
1410 if (otherDeposit != 0)
1411 {
1412 env(pay(issuer, other, usd(otherDeposit)));
1413 }
1414 env.close();
1415
1416 Vault const vault{env};
1417 auto const [createTx, vaultKeylet, subscriptionDate] = vault.createClosedEnded(
1418 {.owner = owner, .asset = usd, .subscriptionOffset = std::chrono::seconds{60}});
1419 env(createTx);
1420 env.close();
1421
1422 auto const vaultSle = env.le(vaultKeylet);
1423 if (!BEAST_EXPECT(vaultSle))
1424 return std::nullopt;
1425 MPTID const shareId = vaultSle->at(sfShareMPTID);
1426
1427 env(vault.deposit(
1428 {.depositor = holder, .id = vaultKeylet.key, .amount = usd(holderDeposit)}));
1429 if (otherDeposit != 0)
1430 {
1431 env(vault.deposit(
1432 {.depositor = other, .id = vaultKeylet.key, .amount = usd(otherDeposit)}));
1433 }
1434 env.close();
1435
1436 vault.closePastSubscription(subscriptionDate);
1437
1438 auto const brokerKeylet =
1439 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
1440 env(set(owner, vaultKeylet.key));
1441 env.close();
1442
1443 auto const sleBroker = env.le(brokerKeylet);
1444 if (!BEAST_EXPECT(sleBroker))
1445 return std::nullopt;
1446 auto const loanKeylet =
1447 keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(sleBroker->at(sfLoanSequence)));
1448
1449 env(set(borrower, brokerKeylet.key, usd(1'000).value()),
1450 loan::kInterestRate(percentageToTenthBips(0)),
1451 kGracePeriod(60),
1452 kPaymentInterval(120),
1453 kPaymentTotal(10),
1454 Sig(sfCounterpartySignature, owner),
1455 Fee(env.current()->fees().base * 2),
1456 Ter(tesSUCCESS));
1457 env.close();
1458
1459 // Under fixCleanup3_4_0, LoanManage rejects tfLoanImpair with
1460 // tecTOO_SOON unless the payment is already late; advance the ledger
1461 // past sfNextPaymentDueDate so impairment succeeds. No-op otherwise.
1462 if (env.current()->rules().enabled(fixCleanup3_4_0))
1463 {
1464 auto const loanBefore = env.le(loanKeylet);
1465 if (!BEAST_EXPECT(loanBefore))
1466 return std::nullopt;
1467 std::uint32_t const dueDate = loanBefore->at(sfNextPaymentDueDate);
1469 }
1470
1471 env(manage(owner, loanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
1472 env.close();
1473
1474 auto const vaultAfter = env.le(vaultKeylet);
1475 if (!BEAST_EXPECT(vaultAfter))
1476 return std::nullopt;
1477 BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == usd(9'000).value());
1478 BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == usd(1'000).value());
1479
1480 return ImpairedLoanVault{
1481 .issuer = issuer,
1482 .holder = holder,
1483 .usd = usd,
1484 .vault = vault,
1485 .vaultKeylet = vaultKeylet,
1486 .shareId = shareId,
1487 };
1488 }
1489
1490 // Legacy clawback pricing burns every share; fixCleanup3_4_0 leaves 10%
1491 // outstanding, backed by the impaired receivable.
1492 void
1494 {
1495 using namespace test::jtx;
1496
1497 auto clawbackHolder = [](ImpairedLoanVault const& setup, STAmount const& amount) {
1498 return setup.vault.clawback({
1499 .issuer = setup.issuer,
1500 .id = setup.vaultKeylet.key,
1501 .holder = setup.holder,
1502 .amount = amount,
1503 });
1504 };
1505
1506 auto const runSole = [this, &clawbackHolder](FeatureBitset features, TER expected) {
1507 testcase(
1508 features[fixCleanup3_4_0]
1509 ? "VaultClawback after impaired loan (post-fixCleanup3_4_0)"
1510 : "VaultClawback after impaired loan (pre-fixCleanup3_4_0)");
1511
1512 Env env(*this, features);
1513 auto const maybeSetup = makeImpairedLoanVault(env, 0);
1514 if (!maybeSetup)
1515 {
1516 BEAST_EXPECT(false);
1517 return;
1518 }
1519 ImpairedLoanVault const& setup = *maybeSetup;
1520
1521 auto const tokenBefore = env.le(keylet::mptoken(setup.shareId, setup.holder.id()));
1522 auto const vaultBefore = env.le(setup.vaultKeylet);
1523 auto const issuanceBefore = env.le(keylet::mptokenIssuance(setup.shareId));
1524 if (!BEAST_EXPECT(tokenBefore) || !BEAST_EXPECT(vaultBefore) ||
1525 !BEAST_EXPECT(issuanceBefore))
1526 return;
1527 std::uint64_t const sharesBefore = tokenBefore->getFieldU64(sfMPTAmount);
1528
1529 // The clawback of 19,000 exceeds AssetsAvailable (9,000), so
1530 // VaultClawback clamps sharesDestroyed to whatever redeems
1531 // exactly AssetsAvailable; compute that expected value using the
1532 // same conversion helper VaultClawback itself uses, rather than
1533 // assuming an exact 90/10 split holds under truncation.
1534 auto const maybeSharesDestroyed = assetsToSharesWithdraw(
1535 vaultBefore,
1536 issuanceBefore,
1537 setup.usd(9'000).value(),
1540 if (!BEAST_EXPECT(maybeSharesDestroyed))
1541 return;
1542 std::uint64_t const expectedSharesAfter =
1543 sharesBefore - maybeSharesDestroyed->mpt().value();
1544
1545 env(clawbackHolder(setup, setup.usd(19'000).value()), Ter(expected));
1546 env.close();
1547 if (expected != tesSUCCESS)
1548 return;
1549
1550 auto const vaultAfter = env.le(setup.vaultKeylet);
1551 if (!BEAST_EXPECT(vaultAfter))
1552 return;
1553 BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == setup.usd(0).value());
1554 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == setup.usd(1'000).value());
1555 BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == setup.usd(1'000).value());
1556 auto const tokenAfter = env.le(keylet::mptoken(setup.shareId, setup.holder.id()));
1557 if (!BEAST_EXPECT(tokenAfter))
1558 return;
1559 BEAST_EXPECT(tokenAfter->getFieldU64(sfMPTAmount) == expectedSharesAfter);
1560 };
1561
1562 runSole(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
1563 runSole(cashBasisAll_, tesSUCCESS);
1564
1565 testcase("VaultClawback after impaired loan, non-sole holder");
1566 {
1567 Env env(*this, cashBasisAll_);
1568 auto const maybeSetup = makeImpairedLoanVault(env, 1'000);
1569 if (!maybeSetup)
1570 {
1571 BEAST_EXPECT(false);
1572 return;
1573 }
1574 ImpairedLoanVault const& setup = *maybeSetup;
1575 // The waiver does not apply, so the holder's 9,000 shares are
1576 // still priced at the discounted rate and cannot cover 9,000.
1577 env(clawbackHolder(setup, setup.usd(9'000).value()), Ter(tecINSUFFICIENT_FUNDS));
1578 }
1579 }
1580
1581 // Bug: a fully impaired vault may pay zero assets for a share burn.
1582 // Sending zero MPT is a no-op, so the vault pseudo-account's asset
1583 // MPToken is never written and ValidVault, which only records deltas for
1584 // created, modified or deleted entries, sees no vault delta at all.
1585 //
1586 // Pre-fixCleanup3_4_0 that alone makes the withdrawal impossible:
1587 // zeroDeltaIsLegitimate is gated on the amendment, so the absent vault
1588 // delta fails "withdrawal must change vault balance". Every pre-amendment
1589 // arm below dies there, before any destination-side check runs.
1590 //
1591 // The destination side differs per arm, and only the vault-delta return
1592 // hides that pre-amendment. With Alice's asset MPToken already present
1593 // nothing touches it, so she has no delta either. With it missing,
1594 // doWithdraw still called addEmptyHolding for a self-destination on a
1595 // zero payout and created her MPToken at amount 0; a created MPToken is
1596 // recorded even at zero, so she arrives with a present-and-zero delta,
1597 // which for an integral MPT asset the destination check would reject if
1598 // it were reached.
1599 //
1600 // ValidMPTIssuance: pre-fixCleanup3_4_0, a VaultWithdraw that both
1601 // creates and deletes an MPToken fails. Post-fixCleanup3_4_0 that is
1602 // allowed.
1603
1604 //
1605 // Post-fixCleanup3_4_0, doWithdraw skips addEmptyHolding on a zero
1606 // payout and zeroDeltaIsLegitimate lets the vault-delta and
1607 // missing-recipient-delta checks accept the transfer. A present
1608 // destination delta of zero is still rejected.
1609 void
1611 {
1612 using namespace test::jtx;
1613 using namespace loan_broker;
1614 using namespace loan;
1615 using namespace std::chrono_literals;
1616
1617 auto const runScenario = [this](
1618 FeatureBitset features,
1619 bool removeAssetToken,
1620 bool withdrawAllAliceShares,
1621 TER expected) {
1622 testcase(
1623 std::string{"bug: MPT vault zero-value withdraw "} +
1624 (removeAssetToken ? "without asset MPToken" : "with asset MPToken") +
1625 (withdrawAllAliceShares ? ", Alice's last share" : ", Alice has leftover shares") +
1626 (features[fixCleanup3_4_0] ? " (post-fixCleanup3_4_0)" : " (pre-fixCleanup3_4_0)"));
1627
1628 Env env(*this, features);
1629
1630 Account const issuer{"issuer"};
1631 Account const owner{"owner"};
1632 Account const alice{"alice"};
1633 Account const bob{"bob"};
1634 Account const borrower{"borrower"};
1635
1636 env.fund(XRP(100'000), issuer, owner, alice, bob, borrower);
1637 env.close();
1638
1639 MPTTester mptt{env, issuer, kMptInitNoFund};
1640 mptt.create({.flags = tfMPTCanTransfer});
1641 PrettyAsset const asset = mptt.issuanceID();
1642 mptt.authorize({.account = owner});
1643 mptt.authorize({.account = alice});
1644 mptt.authorize({.account = bob});
1645 mptt.authorize({.account = borrower});
1646 env.close();
1647
1648 env(pay(issuer, alice, asset(2)));
1649 env(pay(issuer, bob, asset(8)));
1650 env.close();
1651
1652 Vault const vault{env};
1653 auto const [createTx, vaultKeylet, subscriptionDate] = vault.createClosedEnded(
1654 {.owner = owner, .asset = asset, .subscriptionOffset = 60s});
1655 env(createTx);
1656 env.close();
1657
1658 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(2)}));
1659 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = asset(8)}));
1660 env.close();
1661
1662 vault.closePastSubscription(subscriptionDate);
1663
1664 auto const brokerKeylet =
1665 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
1666 env(set(owner, vaultKeylet.key));
1667 env.close();
1668
1669 auto const sleBroker = env.le(brokerKeylet);
1670 if (!BEAST_EXPECT(sleBroker))
1671 return;
1672 auto const loanKeylet = keylet::loan(
1673 brokerKeylet.key, SeqProxy::rawSequence(sleBroker->at(sfLoanSequence)));
1674
1675 env(set(borrower, brokerKeylet.key, asset(10).value()),
1676 kInterestRate(percentageToTenthBips(0)),
1677 kGracePeriod(60),
1678 kPaymentInterval(120),
1679 kPaymentTotal(10),
1680 Sig(sfCounterpartySignature, owner),
1681 Fee(env.current()->fees().base * 2),
1682 Ter(tesSUCCESS));
1683 env.close();
1684
1685 auto const loanBefore = env.le(loanKeylet);
1686 if (!BEAST_EXPECT(loanBefore))
1687 return;
1688 std::uint32_t const dueDate = loanBefore->at(sfNextPaymentDueDate);
1689 env.close(NetClock::time_point{NetClock::duration{dueDate}} + 1s);
1690
1691 env(manage(owner, loanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
1692 env.close();
1693
1694 auto const vaultImpaired = env.le(vaultKeylet);
1695 if (!BEAST_EXPECT(vaultImpaired))
1696 return;
1697 BEAST_EXPECT(vaultImpaired->at(sfAssetsAvailable) == asset(0).value());
1698 BEAST_EXPECT(vaultImpaired->at(sfAssetsTotal) == vaultImpaired->at(sfLossUnrealized));
1699 Number const totalBefore = vaultImpaired->at(sfAssetsTotal);
1700 Number const lossBefore = vaultImpaired->at(sfLossUnrealized);
1701
1702 MPTID const shareId = vaultImpaired->at(sfShareMPTID);
1703 auto const issuanceBefore = env.le(keylet::mptokenIssuance(shareId));
1704 if (!BEAST_EXPECT(issuanceBefore))
1705 return;
1706 std::uint64_t const outstandingBefore =
1707 issuanceBefore->getFieldU64(sfOutstandingAmount);
1708
1709 auto const tokenAlice = env.le(keylet::mptoken(shareId, alice.id()));
1710 if (!BEAST_EXPECT(tokenAlice))
1711 return;
1712 std::uint64_t const sharesBefore = tokenAlice->getFieldU64(sfMPTAmount);
1713 BEAST_EXPECT(sharesBefore == 2);
1714 std::uint64_t const sharesToRedeem = withdrawAllAliceShares ? sharesBefore : 1;
1715 STAmount const redeemShares{MPTIssue{shareId}, Number(sharesToRedeem)};
1716
1717 auto const assetTokenKeylet = keylet::mptoken(mptt.issuanceID(), alice.id());
1718 if (removeAssetToken)
1719 {
1720 mptt.authorize({.account = alice, .flags = tfMPTUnauthorize});
1721 env.close();
1722 BEAST_EXPECT(!env.le(assetTokenKeylet));
1723 }
1724 else
1725 {
1726 auto const existing = env.le(assetTokenKeylet);
1727 if (!BEAST_EXPECT(existing))
1728 return;
1729 BEAST_EXPECT(existing->getFieldU64(sfMPTAmount) == 0);
1730 }
1731
1732 std::uint32_t const redemptionDate = vaultImpaired->at(sfRedemptionDate);
1733 env.close(NetClock::time_point{NetClock::duration{redemptionDate}} + 1s);
1734
1735 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = redeemShares}),
1736 Ter(expected));
1737 env.close();
1738 if (expected != tesSUCCESS)
1739 return;
1740
1741 if (removeAssetToken)
1742 {
1743 BEAST_EXPECT(!env.le(assetTokenKeylet));
1744 }
1745 else
1746 {
1747 auto const assetAfter = env.le(assetTokenKeylet);
1748 if (!BEAST_EXPECT(assetAfter))
1749 return;
1750 BEAST_EXPECT(assetAfter->getFieldU64(sfMPTAmount) == 0);
1751 }
1752
1753 auto const shareAfter = env.le(keylet::mptoken(shareId, alice.id()));
1754 if (withdrawAllAliceShares)
1755 {
1756 BEAST_EXPECT(!shareAfter);
1757 }
1758 else if (BEAST_EXPECT(shareAfter))
1759 {
1760 BEAST_EXPECT(shareAfter->getFieldU64(sfMPTAmount) == sharesBefore - sharesToRedeem);
1761 }
1762
1763 auto const vaultAfter = env.le(vaultKeylet);
1764 if (!BEAST_EXPECT(vaultAfter))
1765 return;
1766 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == totalBefore);
1767 BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == lossBefore);
1768 BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == asset(0).value());
1769
1770 auto const issuanceAfter = env.le(keylet::mptokenIssuance(shareId));
1771 if (!BEAST_EXPECT(issuanceAfter))
1772 return;
1773 BEAST_EXPECT(
1774 issuanceAfter->getFieldU64(sfOutstandingAmount) ==
1775 outstandingBefore - sharesToRedeem);
1776 };
1777
1778 runScenario(
1780 false /* removeAssetToken */,
1781 false /* withdrawAllAliceShares */,
1782 tesSUCCESS);
1783 runScenario(
1785 false /* removeAssetToken */,
1786 true /* withdrawAllAliceShares */,
1787 tesSUCCESS);
1788 runScenario(
1790 true /* removeAssetToken */,
1791 false /* withdrawAllAliceShares */,
1792 tesSUCCESS);
1793 runScenario(
1795 true /* removeAssetToken */,
1796 true /* withdrawAllAliceShares */,
1797 tesSUCCESS);
1798 runScenario(
1799 cashBasisAll_ - fixCleanup3_4_0,
1800 false /* removeAssetToken */,
1801 false /* withdrawAllAliceShares */,
1803 runScenario(
1804 cashBasisAll_ - fixCleanup3_4_0,
1805 false /* removeAssetToken */,
1806 true /* withdrawAllAliceShares */,
1808 runScenario(
1809 cashBasisAll_ - fixCleanup3_4_0,
1810 true /* removeAssetToken */,
1811 false /* withdrawAllAliceShares */,
1813 runScenario(
1814 cashBasisAll_ - fixCleanup3_4_0,
1815 true /* removeAssetToken */,
1816 true /* withdrawAllAliceShares */,
1818 }
1819
1820 // IOU analogue of the missing-MPToken case above. Alice removes her
1821 // zero-balance trust line after depositing, then burns one unit from her
1822 // scaled share balance after the vault is fully impaired. Bob's share
1823 // balance keeps this out of the sole-shareholder loss-waiver and
1824 // final-outstanding-share paths. A zero payout must not recreate Alice's
1825 // unsolicited trust line.
1826 void
1828 {
1829 using namespace test::jtx;
1830 using namespace loan_broker;
1831 using namespace loan;
1832 using namespace std::chrono_literals;
1833
1834 Env env(*this, cashBasisAll_);
1835
1836 Account const issuer{"issuer"};
1837 Account const owner{"owner"};
1838 Account const alice{"alice"};
1839 Account const bob{"bob"};
1840 Account const borrower{"borrower"};
1841
1842 env.fund(XRP(100'000), issuer, owner, alice, bob, borrower);
1843 env.close();
1844 env(fset(issuer, asfDefaultRipple));
1845 env.close();
1846
1847 PrettyAsset const asset = issuer["USD"];
1848 env.trust(asset(100), owner);
1849 env.trust(asset(100), alice);
1850 env.trust(asset(100), bob);
1851 env.trust(asset(100), borrower);
1852 env.close();
1853
1854 env(pay(issuer, alice, asset(2)));
1855 env(pay(issuer, bob, asset(8)));
1856 env.close();
1857
1858 Vault const vault{env};
1859 auto const [createTx, vaultKeylet, subscriptionDate] =
1860 vault.createClosedEnded({.owner = owner, .asset = asset, .subscriptionOffset = 60s});
1861 env(createTx);
1862 env.close();
1863
1864 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(2)}));
1865 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = asset(8)}));
1866 env.close();
1867
1868 auto const assetLine = keylet::trustLine(alice, asset.raw().get<Issue>());
1869 if (!BEAST_EXPECT(env.le(assetLine)))
1870 return;
1871 env.trust(asset(0), alice);
1872 env.close();
1873 BEAST_EXPECT(!env.le(assetLine));
1874
1875 vault.closePastSubscription(subscriptionDate);
1876
1877 auto const brokerKeylet =
1878 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
1879 env(set(owner, vaultKeylet.key));
1880 env.close();
1881
1882 auto const sleBroker = env.le(brokerKeylet);
1883 if (!BEAST_EXPECT(sleBroker))
1884 return;
1885 auto const loanKeylet =
1886 keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(sleBroker->at(sfLoanSequence)));
1887
1888 env(set(borrower, brokerKeylet.key, asset(10).value()),
1889 kInterestRate(percentageToTenthBips(0)),
1890 kGracePeriod(60),
1891 kPaymentInterval(120),
1892 kPaymentTotal(10),
1893 Sig(sfCounterpartySignature, owner),
1894 Fee(env.current()->fees().base * 2),
1895 Ter(tesSUCCESS));
1896 env.close();
1897
1898 auto const loanBefore = env.le(loanKeylet);
1899 if (!BEAST_EXPECT(loanBefore))
1900 return;
1901 std::uint32_t const dueDate = loanBefore->at(sfNextPaymentDueDate);
1902 env.close(NetClock::time_point{NetClock::duration{dueDate}} + 1s);
1903
1904 env(manage(owner, loanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
1905 env.close();
1906
1907 auto const vaultImpaired = env.le(vaultKeylet);
1908 if (!BEAST_EXPECT(vaultImpaired))
1909 return;
1910 BEAST_EXPECT(vaultImpaired->at(sfAssetsAvailable) == asset(0).value());
1911 BEAST_EXPECT(vaultImpaired->at(sfAssetsTotal) == vaultImpaired->at(sfLossUnrealized));
1912 Number const totalBefore = vaultImpaired->at(sfAssetsTotal);
1913 Number const lossBefore = vaultImpaired->at(sfLossUnrealized);
1914
1915 MPTID const shareId = vaultImpaired->at(sfShareMPTID);
1916 auto const tokenAlice = env.le(keylet::mptoken(shareId, alice.id()));
1917 if (!BEAST_EXPECT(tokenAlice))
1918 return;
1919 std::uint64_t const sharesBefore = tokenAlice->getFieldU64(sfMPTAmount);
1920 // Default IOU vault scale is 6, so 2 USD mints 2e6 shares. Redeem one
1921 // leftover share; do not require 1:1 like the MPT case.
1922 BEAST_EXPECT(sharesBefore > 1);
1923 STAmount const redeemShares{MPTIssue{shareId}, Number(1)};
1924
1925 std::uint32_t const redemptionDate = vaultImpaired->at(sfRedemptionDate);
1926 env.close(NetClock::time_point{NetClock::duration{redemptionDate}} + 1s);
1927
1928 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = redeemShares}),
1929 Ter(tesSUCCESS));
1930 env.close();
1931
1932 // A regression in the View guard would recreate this line even though
1933 // no asset value was paid.
1934 BEAST_EXPECT(!env.le(assetLine));
1935
1936 auto const shareAfter = env.le(keylet::mptoken(shareId, alice.id()));
1937 if (!BEAST_EXPECT(shareAfter))
1938 return;
1939 BEAST_EXPECT(shareAfter->getFieldU64(sfMPTAmount) == sharesBefore - 1);
1940
1941 auto const vaultAfter = env.le(vaultKeylet);
1942 if (!BEAST_EXPECT(vaultAfter))
1943 return;
1944 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == totalBefore);
1945 BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == lossBefore);
1946 BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == asset(0).value());
1947 }
1948
1949 // Same zero-payout withdrawal as testBugMptZeroWithdrawMissingHolding, but
1950 // the vault asset is XRP. addEmptyHolding is a no-op for native assets.
1951 // Sequence processing still touches the sender AccountRoot; a sponsored
1952 // fee leaves that XRP balance economically unchanged. After the
1953 // sponsored-withdraw fee-payer fix, deltaAssetsForParty collapses that
1954 // economically-zero XRP delta to absence, so tesSUCCESS takes the
1955 // missing-recipient-delta arm gated by zeroDeltaIsLegitimate. This test
1956 // covers that live SUCCESS path. Pre-fixCleanup3_4_0 still fails the
1957 // invariant.
1958 void
1960 {
1961 using namespace test::jtx;
1962 using namespace loan_broker;
1963 using namespace loan;
1964 using namespace std::chrono_literals;
1965
1966 auto const runScenario = [this](FeatureBitset features, TER expected) {
1967 testcase(
1968 std::string{"bug: XRP vault zero-value withdraw with sponsored fee"} +
1969 (features[fixCleanup3_4_0] ? " (post-fixCleanup3_4_0)" : " (pre-fixCleanup3_4_0)"));
1970
1971 Env env(*this, features);
1972
1973 Account const owner{"owner"};
1974 Account const alice{"alice"};
1975 Account const bob{"bob"};
1976 Account const borrower{"borrower"};
1977 Account const sponsor{"sponsor"};
1978
1979 env.fund(XRP(100'000), owner, alice, bob, borrower, sponsor);
1980 env.close();
1981
1982 PrettyAsset const asset{xrpIssue()};
1983 Vault const vault{env};
1984 auto const [createTx, vaultKeylet, subscriptionDate] = vault.createClosedEnded(
1985 {.owner = owner, .asset = asset, .subscriptionOffset = 60s});
1986 env(createTx);
1987 env.close();
1988
1989 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = asset(2)}));
1990 env(vault.deposit({.depositor = bob, .id = vaultKeylet.key, .amount = asset(8)}));
1991 env.close();
1992
1993 vault.closePastSubscription(subscriptionDate);
1994
1995 auto const brokerKeylet =
1996 keylet::loanBroker(owner.id(), SeqProxy::rawSequence(env.seq(owner)));
1997 env(set(owner, vaultKeylet.key));
1998 env.close();
1999
2000 auto const sleBroker = env.le(brokerKeylet);
2001 if (!BEAST_EXPECT(sleBroker))
2002 return;
2003 auto const loanKeylet = keylet::loan(
2004 brokerKeylet.key, SeqProxy::rawSequence(sleBroker->at(sfLoanSequence)));
2005
2006 env(set(borrower, brokerKeylet.key, asset(10).value()),
2007 kInterestRate(percentageToTenthBips(0)),
2008 kGracePeriod(60),
2009 kPaymentInterval(120),
2010 kPaymentTotal(10),
2011 Sig(sfCounterpartySignature, owner),
2012 Fee(env.current()->fees().base * 2),
2013 Ter(tesSUCCESS));
2014 env.close();
2015
2016 auto const loanBefore = env.le(loanKeylet);
2017 if (!BEAST_EXPECT(loanBefore))
2018 return;
2019 std::uint32_t const dueDate = loanBefore->at(sfNextPaymentDueDate);
2020 env.close(NetClock::time_point{NetClock::duration{dueDate}} + 1s);
2021
2022 env(manage(owner, loanKeylet.key, tfLoanImpair), Ter(tesSUCCESS));
2023 env.close();
2024
2025 auto const vaultImpaired = env.le(vaultKeylet);
2026 if (!BEAST_EXPECT(vaultImpaired))
2027 return;
2028 BEAST_EXPECT(vaultImpaired->at(sfAssetsAvailable) == asset(0).value());
2029 BEAST_EXPECT(vaultImpaired->at(sfAssetsTotal) == vaultImpaired->at(sfLossUnrealized));
2030 Number const totalBefore = vaultImpaired->at(sfAssetsTotal);
2031 Number const lossBefore = vaultImpaired->at(sfLossUnrealized);
2032
2033 MPTID const shareId = vaultImpaired->at(sfShareMPTID);
2034 auto const tokenAlice = env.le(keylet::mptoken(shareId, alice.id()));
2035 if (!BEAST_EXPECT(tokenAlice))
2036 return;
2037 std::uint64_t const sharesBefore = tokenAlice->getFieldU64(sfMPTAmount);
2038 BEAST_EXPECT(sharesBefore == 2);
2039 STAmount const redeemShares{MPTIssue{shareId}, Number(1)};
2040
2041 std::uint32_t const redemptionDate = vaultImpaired->at(sfRedemptionDate);
2042 env.close(NetClock::time_point{NetClock::duration{redemptionDate}} + 1s);
2043
2044 auto const aliceBalanceBefore = env.balance(alice);
2045 auto const sponsorBalanceBefore = env.balance(sponsor);
2046 auto const fee = env.current()->fees().base;
2047
2048 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = redeemShares}),
2049 Fee(fee),
2050 sponsor::As(sponsor, spfSponsorFee),
2051 Sig(sfSponsorSignature, sponsor),
2052 Ter(expected));
2053 env.close();
2054
2055 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore - fee);
2056 BEAST_EXPECT(env.balance(alice) == aliceBalanceBefore);
2057
2058 if (expected != tesSUCCESS)
2059 return;
2060
2061 auto const shareAfter = env.le(keylet::mptoken(shareId, alice.id()));
2062 if (!BEAST_EXPECT(shareAfter))
2063 return;
2064 BEAST_EXPECT(shareAfter->getFieldU64(sfMPTAmount) == sharesBefore - 1);
2065
2066 auto const vaultAfter = env.le(vaultKeylet);
2067 if (!BEAST_EXPECT(vaultAfter))
2068 return;
2069 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == totalBefore);
2070 BEAST_EXPECT(vaultAfter->at(sfLossUnrealized) == lossBefore);
2071 BEAST_EXPECT(vaultAfter->at(sfAssetsAvailable) == asset(0).value());
2072 };
2073
2074 runScenario(cashBasisAll_, tesSUCCESS);
2075 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
2076 }
2077
2078 // addEmptyHolding() used to check isGlobalFrozen(issuer) and
2079 // !lsfDefaultRipple before the "line already exists" tecDUPLICATE
2080 // short circuit. doWithdraw() calls addEmptyHolding() for a
2081 // self-destination payout and only tolerates tecDUPLICATE, so
2082 // tecINTERNAL from a missing DefaultRipple flag aborted the
2083 // withdrawal. fixCleanup3_4_0 checks existence first and maps the
2084 // create-path DefaultRipple miss to terNO_RIPPLE. Global freeze on an
2085 // existing line is still rejected later by checkWithdrawFreeze.
2086 void
2088 {
2089 using namespace test::jtx;
2090
2091 auto const runExistingLine = [this](
2092 FeatureBitset features,
2093 TER selfExpected,
2094 bool issuerGlobalFreeze = false) {
2095 Env env(*this, features);
2096 Account const issuer{"issuer"};
2097 Account const alice{"alice"};
2098 Account const bob{"bob"};
2099
2100 env.fund(XRP(10'000), issuer, alice, bob);
2101 env.close();
2102 env(fset(issuer, asfDefaultRipple));
2103 env.close();
2104
2105 PrettyAsset const usd{issuer["USD"]};
2106 Issue const usdIssue = usd.raw().get<Issue>();
2107 env(trust(alice, usd(10'000)));
2108 env(trust(bob, usd(10'000)));
2109 env.close();
2110 env(pay(issuer, alice, usd(1'000)));
2111 env.close();
2112
2113 Vault const vault{env};
2114 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
2115 env(vaultTx);
2116 env.close();
2117
2118 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(500)}));
2119 env.close();
2120
2121 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(50)}));
2122 env.close();
2123
2124 env(fclear(issuer, asfDefaultRipple));
2125 env.close();
2126 if (issuerGlobalFreeze)
2127 {
2128 env(fset(issuer, asfGlobalFreeze));
2129 env.close();
2130 }
2131
2132 BEAST_EXPECT(env.le(keylet::trustLine(alice.id(), usdIssue)));
2133
2134 // Alice's USD line is unchanged; a later deposit still succeeds
2135 // unless the issuer is globally frozen.
2136 if (!issuerGlobalFreeze)
2137 {
2138 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(10)}));
2139 env.close();
2140 }
2141
2142 Number const destBefore = env.balance(alice, usd.raw()).number();
2143 Number const vaultBefore = env.le(vaultKeylet)->at(sfAssetsTotal);
2144 Number const withdrawAmt{50};
2145
2146 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(50)}),
2147 Ter(selfExpected));
2148 env.close();
2149
2150 Number const destAfter = env.balance(alice, usd.raw()).number();
2151 Number const vaultAfter = env.le(vaultKeylet)->at(sfAssetsTotal);
2152 if (isTesSuccess(selfExpected))
2153 {
2154 BEAST_EXPECT(destAfter == destBefore + withdrawAmt);
2155 BEAST_EXPECT(vaultAfter == vaultBefore - withdrawAmt);
2156 }
2157 else
2158 {
2159 BEAST_EXPECT(destAfter == destBefore);
2160 BEAST_EXPECT(vaultAfter == vaultBefore);
2161 }
2162
2163 if (!issuerGlobalFreeze)
2164 {
2165 auto destTx =
2166 vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(50)});
2167 destTx[sfDestination] = bob.human();
2168 env(destTx);
2169 env.close();
2170 }
2171 };
2172
2173 auto const runDeletedLine = [this](FeatureBitset features, TER selfExpected) {
2174 Env env(*this, features);
2175 Account const issuer{"issuer"};
2176 Account const alice{"alice"};
2177
2178 env.fund(XRP(10'000), issuer, alice);
2179 env.close();
2180 env(fset(issuer, asfDefaultRipple));
2181 env.close();
2182
2183 PrettyAsset const usd{issuer["USD"]};
2184 Issue const usdIssue = usd.raw().get<Issue>();
2185 env(trust(alice, usd(10'000)));
2186 env.close();
2187 env(pay(issuer, alice, usd(500)));
2188 env.close();
2189
2190 Vault const vault{env};
2191 auto [vaultTx, vaultKeylet] = vault.create({.owner = alice, .asset = usd});
2192 env(vaultTx);
2193 env.close();
2194
2195 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(500)}));
2196 env.close();
2197
2198 env(trust(alice, usd(0)));
2199 env.close();
2200 BEAST_EXPECT(!env.le(keylet::trustLine(alice.id(), usdIssue)));
2201 env(fclear(issuer, asfDefaultRipple));
2202 env.close();
2203
2204 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(50)}),
2205 Ter(selfExpected));
2206 env.close();
2207 };
2208
2209 auto const runCoverWithdraw = [this](FeatureBitset features, TER selfExpected) {
2210 using namespace loan_broker;
2211
2212 Env env(*this, features);
2213 Account const issuer{"issuer"};
2214 Account const alice{"alice"};
2215
2216 env.fund(XRP(10'000), issuer, alice);
2217 env.close();
2218 env(fset(issuer, asfDefaultRipple));
2219 env.close();
2220
2221 PrettyAsset const usd{issuer["USD"]};
2222 Issue const usdIssue = usd.raw().get<Issue>();
2223 env(trust(alice, usd(10'000)));
2224 env.close();
2225 env(pay(issuer, alice, usd(1'000)));
2226 env.close();
2227
2228 Vault const vault{env};
2229 auto const [createTx, vaultKeylet, subscriptionDate] = vault.createClosedEnded(
2230 {.owner = alice, .asset = usd, .subscriptionOffset = std::chrono::seconds{60}});
2231 (void)subscriptionDate;
2232 env(createTx);
2233 env.close();
2234
2235 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(500)}));
2236 env.close();
2237
2238 auto const brokerKeylet =
2239 keylet::loanBroker(alice.id(), SeqProxy::rawSequence(env.seq(alice)));
2240 env(set(alice, vaultKeylet.key));
2241 env.close();
2242 env(coverDeposit(alice, brokerKeylet.key, usd(100).value()));
2243 env.close();
2244
2245 env(fclear(issuer, asfDefaultRipple));
2246 env.close();
2247 BEAST_EXPECT(env.le(keylet::trustLine(alice.id(), usdIssue)));
2248
2249 Number const destBefore = env.balance(alice, usd.raw()).number();
2250 Number const coverBefore = env.le(brokerKeylet)->at(sfCoverAvailable);
2251 Number const withdrawAmt{50};
2252
2253 env(coverWithdraw(alice, brokerKeylet.key, usd(50).value()), Ter(selfExpected));
2254 env.close();
2255
2256 Number const destAfter = env.balance(alice, usd.raw()).number();
2257 Number const coverAfter = env.le(brokerKeylet)->at(sfCoverAvailable);
2258 if (isTesSuccess(selfExpected))
2259 {
2260 BEAST_EXPECT(destAfter == destBefore + withdrawAmt);
2261 BEAST_EXPECT(coverAfter == coverBefore - withdrawAmt);
2262 }
2263 else
2264 {
2265 BEAST_EXPECT(destAfter == destBefore);
2266 BEAST_EXPECT(coverAfter == coverBefore);
2267 }
2268 };
2269
2270 auto const runDeletedCoverWithdraw = [this](FeatureBitset features, TER selfExpected) {
2271 using namespace loan_broker;
2272
2273 Env env(*this, features);
2274 Account const issuer{"issuer"};
2275 Account const alice{"alice"};
2276
2277 env.fund(XRP(10'000), issuer, alice);
2278 env.close();
2279 env(fset(issuer, asfDefaultRipple));
2280 env.close();
2281
2282 PrettyAsset const usd{issuer["USD"]};
2283 Issue const usdIssue = usd.raw().get<Issue>();
2284 env(trust(alice, usd(10'000)));
2285 env.close();
2286 env(pay(issuer, alice, usd(600)));
2287 env.close();
2288
2289 Vault const vault{env};
2290 auto const [createTx, vaultKeylet, subscriptionDate] = vault.createClosedEnded(
2291 {.owner = alice, .asset = usd, .subscriptionOffset = std::chrono::seconds{60}});
2292 (void)subscriptionDate;
2293 env(createTx);
2294 env.close();
2295
2296 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(500)}));
2297 env.close();
2298
2299 auto const brokerKeylet =
2300 keylet::loanBroker(alice.id(), SeqProxy::rawSequence(env.seq(alice)));
2301 env(set(alice, vaultKeylet.key));
2302 env.close();
2303 env(coverDeposit(alice, brokerKeylet.key, usd(100).value()));
2304 env.close();
2305
2306 env(trust(alice, usd(0)));
2307 env.close();
2308 BEAST_EXPECT(!env.le(keylet::trustLine(alice.id(), usdIssue)));
2309 env(fclear(issuer, asfDefaultRipple));
2310 env.close();
2311
2312 env(coverWithdraw(alice, brokerKeylet.key, usd(50).value()), Ter(selfExpected));
2313 env.close();
2314 };
2315
2316 auto const runPrivateVault = [this](FeatureBitset features, TER selfExpected) {
2317 Env env(*this, features);
2318 Account const issuer{"issuer"};
2319 Account const alice{"alice"};
2320 Account const pdOwner{"pdOwner"};
2321 Account const credIssuer{"credIssuer"};
2322 std::string const credType = "credential";
2323
2324 env.fund(XRP(10'000), issuer, alice, pdOwner, credIssuer);
2325 env.close();
2326 env(fset(issuer, asfDefaultRipple));
2327 env.close();
2328
2329 PrettyAsset const usd{issuer["USD"]};
2330 env(trust(alice, usd(10'000)));
2331 env.close();
2332 env(pay(issuer, alice, usd(1'000)));
2333 env.close();
2334
2335 Vault const vault{env};
2336 auto [vaultTx, vaultKeylet] =
2337 vault.create({.owner = alice, .asset = usd, .flags = tfVaultPrivate});
2338 env(vaultTx);
2339 env.close();
2340
2341 pdomain::Credentials const credentials{{.issuer = credIssuer, .credType = credType}};
2342 env(pdomain::setTx(pdOwner, credentials));
2343 auto const domainId = pdomain::getNewDomain(env.meta());
2344 {
2345 auto domainTx = vault.set({.owner = alice, .id = vaultKeylet.key});
2346 domainTx[sfDomainID] = to_string(domainId);
2347 env(domainTx);
2348 env.close();
2349 }
2350
2351 env(credentials::create(alice, credIssuer, credType));
2352 env(credentials::accept(alice, credIssuer, credType));
2353 env.close();
2354
2355 env(vault.deposit({.depositor = alice, .id = vaultKeylet.key, .amount = usd(500)}));
2356 env.close();
2357
2358 env(fclear(issuer, asfDefaultRipple));
2359 env.close();
2360
2361 env(vault.withdraw({.depositor = alice, .id = vaultKeylet.key, .amount = usd(50)}),
2362 Ter(selfExpected));
2363 env.close();
2364 };
2365
2366 testcase(
2367 "bug: VaultWithdraw to self fails with tecINTERNAL after issuer "
2368 "clears asfDefaultRipple even though the trust line exists "
2369 "(pre-fixCleanup3_4_0)");
2370 runExistingLine(cashBasisAll_ - fixCleanup3_4_0, tecINTERNAL);
2371
2372 testcase(
2373 "bug: VaultWithdraw to self succeeds after issuer clears "
2374 "asfDefaultRipple when the trust line exists (post-fixCleanup3_4_0)");
2375 runExistingLine(cashBasisAll_, tesSUCCESS);
2376
2377 testcase(
2378 "bug: VaultWithdraw to self with an existing line still gets "
2379 "tecFROZEN under asfGlobalFreeze (post-fixCleanup3_4_0)");
2380 runExistingLine(cashBasisAll_, tecFROZEN, true);
2381
2382 testcase(
2383 "bug: VaultWithdraw to self fails with tecINTERNAL after issuer "
2384 "clears asfDefaultRipple and the trust line was deleted "
2385 "(pre-fixCleanup3_4_0)");
2386 runDeletedLine(cashBasisAll_ - fixCleanup3_4_0, tecINTERNAL);
2387
2388 testcase(
2389 "bug: VaultWithdraw to self fails with terNO_RIPPLE after issuer "
2390 "clears asfDefaultRipple and the trust line was deleted "
2391 "(post-fixCleanup3_4_0)");
2392 runDeletedLine(cashBasisAll_, terNO_RIPPLE);
2393
2394 testcase(
2395 "bug: LoanBrokerCoverWithdraw to self fails with tecINTERNAL after "
2396 "issuer clears asfDefaultRipple even though the trust line exists "
2397 "(pre-fixCleanup3_4_0)");
2398 runCoverWithdraw(cashBasisAll_ - fixCleanup3_4_0, tecINTERNAL);
2399
2400 testcase(
2401 "bug: LoanBrokerCoverWithdraw to self succeeds after issuer clears "
2402 "asfDefaultRipple when the trust line exists (post-fixCleanup3_4_0)");
2403 runCoverWithdraw(cashBasisAll_, tesSUCCESS);
2404
2405 testcase(
2406 "bug: LoanBrokerCoverWithdraw to self fails with tecINTERNAL after "
2407 "issuer clears asfDefaultRipple and the trust line was deleted "
2408 "(pre-fixCleanup3_4_0)");
2409 runDeletedCoverWithdraw(cashBasisAll_ - fixCleanup3_4_0, tecINTERNAL);
2410
2411 testcase(
2412 "bug: LoanBrokerCoverWithdraw to self fails with terNO_RIPPLE after "
2413 "issuer clears asfDefaultRipple and the trust line was deleted "
2414 "(post-fixCleanup3_4_0)");
2415 runDeletedCoverWithdraw(cashBasisAll_, terNO_RIPPLE);
2416
2417 testcase(
2418 "bug: private VaultWithdraw to self fails with tecINTERNAL after "
2419 "issuer clears asfDefaultRipple even though the trust line exists "
2420 "(pre-fixCleanup3_4_0)");
2421 runPrivateVault(cashBasisAll_ - fixCleanup3_4_0, tecINTERNAL);
2422
2423 testcase(
2424 "bug: private VaultWithdraw to self succeeds after issuer clears "
2425 "asfDefaultRipple when the trust line exists (post-fixCleanup3_4_0)");
2426 runPrivateVault(cashBasisAll_, tesSUCCESS);
2427 }
2428
2429 // Bug 1: a sponsored XRP VaultWithdraw to a distinct destination is
2430 // rejected because the vault invariant treats the holder's touched
2431 // but economically unchanged AccountRoot as a second payout
2432 // recipient. Sequence/ticket processing still touches the holder
2433 // while the sponsor pays the fee, so the holder's XRP delta is
2434 // present-zero and is not normalized away. If this happens on the
2435 // last Subscription ledger of a closed-ended vault, the holder
2436 // cannot retry until Redemption (tecTOO_SOON during Investment).
2437 //
2438 // Fixed by ValidVault::deltaAssetsForParty always collapsing an
2439 // economically-zero XRP delta to absence, regardless of who paid the
2440 // fee.
2441 void
2443 {
2444 using namespace test::jtx;
2445
2446 auto const runScenario = [this](FeatureBitset features, TER expected) {
2447 Env env{*this, features};
2448 Account const owner{"owner"};
2449 Account const holder{"holder"};
2450 Account const destination{"destination"};
2451 Account const sponsor{"sponsor"};
2452 env.fund(XRP(10'000), owner, holder, destination, sponsor);
2453 env.close();
2454
2455 constexpr std::uint32_t investmentPeriod = 14u * 24u * 60u * 60u;
2456 auto const [vault, vaultKeylet, subscriptionDate, redemptionDate] =
2457 makeClosedEndedVault(env, owner, xrpIssue(), 120u, investmentPeriod);
2458 BEAST_EXPECT(redemptionDate - subscriptionDate == investmentPeriod);
2459
2460 env(vault.deposit(
2461 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()}));
2462 env.close();
2463
2464 // Inclusive SubscriptionDate boundary: still Subscription, so an
2465 // ordinary withdrawal is allowed.
2466 closeToTime(env, Tp{D{subscriptionDate}});
2467
2468 auto const vaultBefore = env.le(vaultKeylet);
2469 if (!BEAST_EXPECT(vaultBefore))
2470 return;
2471 auto const assetsTotalBefore = vaultBefore->at(sfAssetsTotal);
2472 auto const holderBalanceBefore = env.balance(holder);
2473 auto const destinationBalanceBefore = env.balance(destination);
2474 auto const sponsorBalanceBefore = env.balance(sponsor);
2475 auto const fee = env.current()->fees().base;
2476
2477 auto withdraw = vault.withdraw(
2478 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()});
2479 withdraw[sfDestination] = destination.human();
2480 env(withdraw,
2481 Fee(fee),
2482 sponsor::As(sponsor, spfSponsorFee),
2483 Sig(sfSponsorSignature, sponsor),
2484 Ter(expected));
2485 env.close();
2486
2487 auto const vaultAfter = env.le(vaultKeylet);
2488 if (!BEAST_EXPECT(vaultAfter))
2489 return;
2490 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore - fee);
2491
2492 if (expected == tesSUCCESS)
2493 {
2494 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore - XRP(100).value());
2495 BEAST_EXPECT(env.balance(holder) == holderBalanceBefore);
2496 BEAST_EXPECT(env.balance(destination) == destinationBalanceBefore + XRP(100));
2497 return;
2498 }
2499
2500 // Invariant rollback: the payout and share burn are undone, but
2501 // sequence processing and the sponsored fee charge remain.
2502 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore);
2503 BEAST_EXPECT(env.balance(holder) == holderBalanceBefore);
2504 BEAST_EXPECT(env.balance(destination) == destinationBalanceBefore);
2505
2506 // Once the ledger advances into Investment, the same holder
2507 // cannot retry until Redemption.
2508 auto retry = vault.withdraw(
2509 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()});
2510 retry[sfDestination] = destination.human();
2511 env(retry, Ter(tecTOO_SOON));
2512 };
2513
2514 testcase(
2515 "bug: sponsored XRP withdrawal to a distinct destination misreads a "
2516 "touched-but-zero sender delta as a second recipient "
2517 "(pre-fixCleanup3_4_0)");
2518 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
2519
2520 testcase(
2521 "bug: sponsored XRP withdrawal to a distinct destination succeeds "
2522 "(post-fixCleanup3_4_0)");
2523 runScenario(cashBasisAll_, tesSUCCESS);
2524 }
2525
2526 // Bug 2: a co-signed fee sponsor named as the withdrawal's own
2527 // destination pays its fee from the same AccountRoot it is paid into,
2528 // so its net XRP delta is (payout - fee). The invariant never fee-
2529 // corrected the destination side at all, so this always failed the
2530 // equal-amount check against the vault's outflow (payout).
2531 //
2532 // Fixed by ValidVault::deltaAssetsForParty adding the fee back onto
2533 // whichever inspected party's AccountRoot actually paid it -- the
2534 // sender, or a distinct destination -- not just the sender.
2535 void
2537 {
2538 using namespace test::jtx;
2539
2540 auto const runScenario = [this](FeatureBitset features, TER expected) {
2541 Env env{*this, features};
2542 Account const owner{"owner"};
2543 Account const holder{"holder"};
2544 Account const sponsor{"sponsor"};
2545 env.fund(XRP(10'000), owner, holder, sponsor);
2546 env.close();
2547
2548 Vault const vault{env};
2549 auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = xrpIssue()});
2550 env(vaultTx);
2551 env.close();
2552
2553 env(vault.deposit(
2554 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()}));
2555 env.close();
2556
2557 auto const vaultBefore = env.le(vaultKeylet);
2558 if (!BEAST_EXPECT(vaultBefore))
2559 return;
2560 auto const assetsTotalBefore = vaultBefore->at(sfAssetsTotal);
2561 auto const sponsorBalanceBefore = env.balance(sponsor);
2562 auto const fee = env.current()->fees().base;
2563
2564 // The sponsor both receives the withdrawal (as sfDestination)
2565 // and pays its own fee (co-signed) from the same AccountRoot.
2566 auto withdraw = vault.withdraw(
2567 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()});
2568 withdraw[sfDestination] = sponsor.human();
2569 env(withdraw,
2570 Fee(fee),
2571 sponsor::As(sponsor, spfSponsorFee),
2572 Sig(sfSponsorSignature, sponsor),
2573 Ter(expected));
2574 env.close();
2575
2576 auto const vaultAfter = env.le(vaultKeylet);
2577 if (!BEAST_EXPECT(vaultAfter))
2578 return;
2579
2580 if (expected == tesSUCCESS)
2581 {
2582 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore - XRP(100).value());
2583 // Paid the withdrawal, then separately debited for the fee
2584 // it chose to cover; net effect is payout minus fee.
2585 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore + XRP(100) - fee);
2586 return;
2587 }
2588
2589 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore);
2590 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore - fee);
2591 };
2592
2593 testcase(
2594 "bug: co-signed sponsor named as withdrawal destination has its "
2595 "own fee debit misread as breaking the payout equality "
2596 "(pre-fixCleanup3_4_0)");
2597 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED);
2598
2599 testcase(
2600 "bug: co-signed sponsor named as withdrawal destination succeeds "
2601 "(post-fixCleanup3_4_0)");
2602 runScenario(cashBasisAll_, tesSUCCESS);
2603 }
2604
2605 // Pre-funded fee sponsorship draws the fee from ltSponsorship.sfFeeAmount,
2606 // so feePayerAccountRoot must return nullopt rather than the sponsor's
2607 // AccountRoot. A bystander sponsor leaves that branch unexercised: the
2608 // result is only consulted by deltaAssetsForParty via `payer && *payer ==
2609 // id`. Naming the sponsor as sfDestination makes the early return
2610 // load-bearing -- returning the sponsor's id instead of nullopt would add
2611 // the fee back onto a balance that never paid it, and the equal-amount
2612 // check against the vault outflow would fail.
2613 //
2614 // Contrast testBugSponsorAsDestinationFeeMisappliedToPayout, where the
2615 // sponsor co-signs and so really does pay from its own AccountRoot.
2616 void
2618 {
2619 using namespace test::jtx;
2620
2621 auto const runScenario = [this](
2622 FeatureBitset features,
2623 TER expected,
2624 bool const sponsorIsDestination) {
2625 Env env{*this, features};
2626 Account const owner{"owner"};
2627 Account const holder{"holder"};
2628 Account const destination{"destination"};
2629 Account const sponsor{"sponsor"};
2630 env.fund(XRP(10'000), owner, holder, destination, sponsor);
2631 env.close();
2632
2633 Vault const vault{env};
2634 auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = xrpIssue()});
2635 env(vaultTx);
2636 env.close();
2637
2638 env(vault.deposit(
2639 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()}));
2640 env.close();
2641
2642 auto const fee = env.current()->fees().base;
2643 env(sponsor::set_fee(sponsor, 0, fee), sponsor::SponseeAcc(holder));
2644 env.close();
2645
2646 auto const vaultBefore = env.le(vaultKeylet);
2647 if (!BEAST_EXPECT(vaultBefore))
2648 return;
2649 auto const assetsTotalBefore = vaultBefore->at(sfAssetsTotal);
2650 auto const holderBalanceBefore = env.balance(holder);
2651 auto const destinationBalanceBefore = env.balance(destination);
2652 auto const sponsorBalanceBefore = env.balance(sponsor);
2653
2654 Account const& recipient = sponsorIsDestination ? sponsor : destination;
2655 auto withdraw = vault.withdraw(
2656 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()});
2657 withdraw[sfDestination] = recipient.human();
2658 env(withdraw, Fee(fee), sponsor::As(sponsor, spfSponsorFee), Ter(expected));
2659 env.close();
2660
2661 auto const vaultAfter = env.le(vaultKeylet);
2662 if (!BEAST_EXPECT(vaultAfter))
2663 return;
2664 // Holder is economically unchanged (sequence only); the fee is
2665 // taken from the sponsorship object, not any AccountRoot.
2666 BEAST_EXPECT(env.balance(holder) == holderBalanceBefore);
2667
2668 if (expected == tesSUCCESS)
2669 {
2670 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore - XRP(100).value());
2671 if (sponsorIsDestination)
2672 {
2673 // The sponsor receives the payout and is not debited for
2674 // the fee. The sponsor has to BE the destination for
2675 // FeePayerType::SponsorPreFunded to matter.
2676 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore + XRP(100));
2677 }
2678 else
2679 {
2680 BEAST_EXPECT(env.balance(destination) == destinationBalanceBefore + XRP(100));
2681 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore);
2682 }
2683 auto const sponsorship = env.le(keylet::sponsorship(sponsor, holder));
2684 if (!BEAST_EXPECT(sponsorship))
2685 return;
2686 BEAST_EXPECT(!sponsorship->isFieldPresent(sfFeeAmount));
2687 return;
2688 }
2689
2690 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore);
2691 BEAST_EXPECT(env.balance(sponsor) == sponsorBalanceBefore);
2692 if (!sponsorIsDestination)
2693 BEAST_EXPECT(env.balance(destination) == destinationBalanceBefore);
2694 };
2695
2696 testcase(
2697 "pre-funded fee XRP withdrawal to a distinct destination succeeds "
2698 "(post-fixCleanup3_4_0)");
2699 runScenario(cashBasisAll_, tesSUCCESS, false);
2700
2701 testcase(
2702 "bug: pre-funded sponsor named as withdrawal destination misreads "
2703 "the sender's touched-but-zero delta as a second recipient "
2704 "(pre-fixCleanup3_4_0)");
2705 runScenario(cashBasisAll_ - fixCleanup3_4_0, tecINVARIANT_FAILED, true);
2706
2707 testcase(
2708 "bug: pre-funded sponsor named as withdrawal destination receives "
2709 "the full payout (post-fixCleanup3_4_0)");
2710 runScenario(cashBasisAll_, tesSUCCESS, true);
2711 }
2712
2713 // Unsponsored third-party XRP withdrawal: the sender's AccountRoot moves
2714 // by exactly -fee. Pre-amendment, the sender-only fee correction then
2715 // collapses that to absence so the dual-recipient guard does not fire.
2716 void
2718 {
2719 using namespace test::jtx;
2720
2721 testcase(
2722 "unsponsored XRP withdrawal to a distinct destination succeeds "
2723 "(pre-fixCleanup3_4_0)");
2724
2725 Env env{*this, cashBasisAll_ - fixCleanup3_4_0};
2726 Account const owner{"owner"};
2727 Account const holder{"holder"};
2728 Account const destination{"destination"};
2729 env.fund(XRP(10'000), owner, holder, destination);
2730 env.close();
2731
2732 Vault const vault{env};
2733 auto [vaultTx, vaultKeylet] = vault.create({.owner = owner, .asset = xrpIssue()});
2734 env(vaultTx);
2735 env.close();
2736
2737 env(vault.deposit(
2738 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()}));
2739 env.close();
2740
2741 auto const vaultBefore = env.le(vaultKeylet);
2742 if (!BEAST_EXPECT(vaultBefore))
2743 return;
2744 auto const assetsTotalBefore = vaultBefore->at(sfAssetsTotal);
2745 auto const holderBalanceBefore = env.balance(holder);
2746 auto const destinationBalanceBefore = env.balance(destination);
2747 auto const fee = env.current()->fees().base;
2748
2749 auto withdraw = vault.withdraw(
2750 {.depositor = holder, .id = vaultKeylet.key, .amount = XRP(100).value()});
2751 withdraw[sfDestination] = destination.human();
2752 env(withdraw, Fee(fee), Ter(tesSUCCESS));
2753 env.close();
2754
2755 auto const vaultAfter = env.le(vaultKeylet);
2756 if (!BEAST_EXPECT(vaultAfter))
2757 return;
2758 BEAST_EXPECT(vaultAfter->at(sfAssetsTotal) == assetsTotalBefore - XRP(100).value());
2759 BEAST_EXPECT(env.balance(holder) == holderBalanceBefore - fee);
2760 BEAST_EXPECT(env.balance(destination) == destinationBalanceBefore + XRP(100));
2761 }
2762
2763public:
2764 void
2791};
2792
2794
2795} // namespace xrpl
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
constexpr TIss const & get() const
A currency issued by an account.
Definition Issue.h:18
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
void testBugSelfWithdrawAfterIssuerClearsDefaultRipple()
void testBugSponsorAsDestinationFeeMisappliedToPayout()
void testBugVaultLockedByPartialWithdraw()
void testVaultWithdrawEqualityEnforced()
void testVaultDepositNegativeBalanceFromOppositeLimit()
std::optional< RoundTripOvershootVault > makeRoundTripOvershootVault(test::jtx::Env &env)
FeatureBitset const cashBasisAll_
void testBugSponsoredWithdrawZeroDeltaMisclassifiedAsSecondRecipient()
std::optional< ImpairedLoanVault > makeImpairedLoanVault(test::jtx::Env &env, int otherDeposit)
void testBugVaultDepositOvercreditsAcrossScaleBoundary()
void testBugVaultDustDebitCanonicalizesToNoOp()
void testUnsponsoredWithdrawToDistinctDestinationPreAmendment()
void testVaultDepositCanonicalizeToZero()
void testBugMptZeroWithdrawMissingHolding()
void run() override
Runs the suite.
void testVaultWithdrawCanonicalizeToZero()
void testBugIouZeroWithdrawMissingTrustLine()
void testBugDepositShareTruncationSubUlp()
Shared base for the Vault*_test family under src/test/app/vault/.
NetClock::duration D
NetClock::time_point Tp
FeatureBitset const all_
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())
test::jtx::PrettyAsset PrettyAsset
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
std::uint32_t seq(Account const &account) const
Returns the next sequence number on account.
Definition Env.cpp:302
void trust(STAmount const &amount, Account const &account)
Establish trust lines.
Definition Env.cpp:354
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
T make_unique(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 sponsorship(AccountID const &sponsor, AccountID const &sponsee) noexcept
A Sponsorship.
Definition Indexes.cpp:366
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
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
constexpr FlagValue spfSponsorFee
Definition TxFlags.h:467
@ terNO_RIPPLE
Definition TER.h:226
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
std::optional< STAmount > assetsToSharesWithdraw(SLE::ConstRef vault, SLE::ConstRef issuance, STAmount const &assets, TruncateShares truncate=TruncateShares::No, WaiveUnrealizedLoss waive=WaiveUnrealizedLoss::No)
From the perspective of a vault, return the number of shares to demand from the depositor when they a...
STAmount clawbackAmount(SLE::ConstRef vault, std::optional< STAmount > const &maybeAmount, AccountID const &account)
constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage)
Definition Protocol.h:127
@ tefINTERNAL
Definition TER.h:167
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
BaseUInt< 192 > MPTID
MPTID is a 192-bit value representing MPT Issuance ID, which is a concatenation of a 32-bit sequence ...
Definition UintTypes.h:54
std::map< std::string, AmendmentSupport > const & allAmendments()
All amendments libxrpl knows about.
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecINTERNAL
Definition TER.h:321
@ tecTOO_SOON
Definition TER.h:329
@ tecINVARIANT_FAILED
Definition TER.h:324
@ tecFROZEN
Definition TER.h:314
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecNO_LINE
Definition TER.h:312
@ tecPRECISION_LOSS
Definition TER.h:374
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, xrpl)
@ tesSUCCESS
Definition TER.h:253
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
UInt256 key
Definition Keylet.h:21
static json::Value clawback(ClawbackArgs const &args)
Definition vault.cpp:112