xrpld
Loading...
Searching...
No Matches
OfferMPT_test.cpp
1#include <test/jtx/AMM.h>
2#include <test/jtx/CaptureLogs.h>
3#include <test/jtx/Env.h>
4#include <test/jtx/PathSet.h>
5#include <test/jtx/TestHelpers.h>
6#include <test/jtx/WSClient.h>
7#include <test/jtx/acctdelete.h>
8#include <test/jtx/amount.h>
9#include <test/jtx/balance.h>
10#include <test/jtx/envconfig.h>
11#include <test/jtx/fee.h>
12#include <test/jtx/jtx_json.h>
13#include <test/jtx/mpt.h>
14#include <test/jtx/noop.h>
15#include <test/jtx/offer.h>
16#include <test/jtx/owners.h>
17#include <test/jtx/paths.h>
18#include <test/jtx/pay.h>
19#include <test/jtx/rate.h>
20#include <test/jtx/require.h>
21#include <test/jtx/sendmax.h>
22#include <test/jtx/tags.h>
23#include <test/jtx/ter.h>
24#include <test/jtx/ticket.h>
25#include <test/jtx/trust.h>
26#include <test/jtx/txflags.h>
27
28#include <xrpl/basics/Number.h>
29#include <xrpl/basics/base_uint.h>
30#include <xrpl/beast/unit_test/suite.h>
31#include <xrpl/beast/utility/Journal.h>
32#include <xrpl/core/ServiceRegistry.h>
33#include <xrpl/json/json_value.h>
34#include <xrpl/ledger/helpers/DirectoryHelpers.h>
35#include <xrpl/protocol/AccountID.h>
36#include <xrpl/protocol/Book.h>
37#include <xrpl/protocol/ErrorCodes.h>
38#include <xrpl/protocol/Feature.h>
39#include <xrpl/protocol/Indexes.h>
40#include <xrpl/protocol/Issue.h>
41#include <xrpl/protocol/LedgerFormats.h>
42#include <xrpl/protocol/MPTIssue.h>
43#include <xrpl/protocol/Protocol.h>
44#include <xrpl/protocol/SField.h>
45#include <xrpl/protocol/STAmount.h>
46#include <xrpl/protocol/Seed.h>
47#include <xrpl/protocol/SeqProxy.h>
48#include <xrpl/protocol/TER.h>
49#include <xrpl/protocol/TxFlags.h>
50#include <xrpl/protocol/UintTypes.h>
51#include <xrpl/protocol/XRPAmount.h>
52#include <xrpl/protocol/jss.h>
53
54#include <algorithm>
55#include <cstddef>
56#include <cstdint>
57#include <functional>
58#include <map>
59#include <memory>
60#include <optional>
61#include <string>
62#include <type_traits>
63#include <utility>
64#include <vector>
65
66namespace xrpl::test {
67
69{
70 static XRPAmount
72 {
73 return env.current()->fees().accountReserve(count, 1);
74 }
75
76 static std::uint32_t
78 {
79 return env.current()->header().parentCloseTime.time_since_epoch().count();
80 }
81
82public:
83 void
85 {
86 testcase("Incorrect Removal of Funded Offers");
87
88 // We need at least two paths. One at good quality and one at bad
89 // quality. The bad quality path needs two offer books in a row.
90 // Each offer book should have two offers at the same quality, the
91 // offers should be completely consumed, and the payment should
92 // require both offers to be satisfied. The first offer must
93 // be "taker gets" XRP. Old, broken would remove the first
94 // "taker gets" xrp offer, even though the offer is still funded and
95 // not used for the payment.
96
97 using namespace jtx;
98 auto const gw = Account{"gateway"};
99 Account const alice{"alice"};
100 Account const bob{"bob"};
101 Account const carol{"carol"};
102
103 auto const test = [&](auto&& issue1, auto&& issue2) {
104 Env env{*this, features};
105
106 env.fund(XRP(10'000), alice, bob, carol, gw);
107 env.close();
108
109 auto const usd =
110 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}});
111 auto const btc =
112 issue2({.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}});
113
114 env(pay(gw, alice, btc(1'000)));
115
116 env(pay(gw, carol, usd(1'000)));
117 env(pay(gw, carol, btc(1'000)));
118
119 // Must be two offers at the same quality
120 // "taker gets" must be XRP
121 // (Different amounts, so I can distinguish the offers)
122 env(offer(carol, btc(49), XRP(49)));
123 env(offer(carol, btc(51), XRP(51)));
124
125 // Offers for the poor quality path
126 // Must be two offers at the same quality
127 env(offer(carol, XRP(50), usd(50)));
128 env(offer(carol, XRP(50), usd(50)));
129
130 // Offers for the good quality path
131 env(offer(carol, btc(1), usd(100)));
132
133 PathSet const paths(TestPath(XRP, usd), TestPath(usd));
134
135 env(pay(alice, bob, usd(100)),
136 Json(paths.json()),
137 Sendmax(btc(1'000)),
138 Txflags(tfPartialPayment));
139
140 env.require(Balance(bob, usd(100)));
141 BEAST_EXPECT(
142 !isOffer(env, carol, btc(1), usd(100)) && isOffer(env, carol, btc(49), XRP(49)));
143 };
145 }
146
147 void
149 {
150 testcase("Removing Canceled Offers");
151
152 using namespace jtx;
153 Env env{*this, features};
154
155 auto const gw = Account{"gateway"};
156 auto const alice = Account{"alice"};
157
158 env.fund(XRP(10'000), alice, gw);
159 env.close();
160
161 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
162
163 env(pay(gw, alice, usd(50)));
164 env.close();
165
166 auto const offer1Seq = env.seq(alice);
167
168 env(offer(alice, XRP(500), usd(100)), Require(Offers(alice, 1)));
169 env.close();
170
171 BEAST_EXPECT(isOffer(env, alice, XRP(500), usd(100)));
172
173 // cancel the offer above and replace it with a new offer
174 auto const offer2Seq = env.seq(alice);
175
176 env(offer(alice, XRP(300), usd(100)),
177 Json(jss::OfferSequence, offer1Seq),
178 Require(Offers(alice, 1)));
179 env.close();
180
181 BEAST_EXPECT(
182 isOffer(env, alice, XRP(300), usd(100)) && !isOffer(env, alice, XRP(500), usd(100)));
183
184 // Test canceling non-existent offer.
185 // auto const offer3Seq = env.seq (alice);
186
187 env(offer(alice, XRP(400), usd(200)),
188 Json(jss::OfferSequence, offer1Seq),
189 Require(Offers(alice, 2)));
190 env.close();
191
192 BEAST_EXPECT(
193 isOffer(env, alice, XRP(300), usd(100)) && isOffer(env, alice, XRP(400), usd(200)));
194
195 // Test cancellation now with OfferCancel tx
196 auto const offer4Seq = env.seq(alice);
197 env(offer(alice, XRP(222), usd(111)), Require(Offers(alice, 3)));
198 env.close();
199
200 BEAST_EXPECT(isOffer(env, alice, XRP(222), usd(111)));
201 env(offerCancel(alice, offer4Seq));
202 env.close();
203 BEAST_EXPECT(env.seq(alice) == offer4Seq + 2);
204
205 BEAST_EXPECT(!isOffer(env, alice, XRP(222), usd(111)));
206
207 // Create an offer that both fails with a tecEXPIRED code and removes
208 // an offer. Show that the attempt to remove the offer fails.
209 env.require(Offers(alice, 2));
210
211 env(offer(alice, XRP(5), usd(2)),
212 Json(sfExpiration.fieldName, lastClose(env)),
213 Json(jss::OfferSequence, offer2Seq),
214 Ter(TER{tecEXPIRED}));
215 env.close();
216
217 env.require(Offers(alice, 2));
218 BEAST_EXPECT(isOffer(env, alice, XRP(300), usd(100))); // offer2
219 BEAST_EXPECT(!isOffer(env, alice, XRP(5), usd(2))); // expired
220 }
221
222 void
224 {
225 testcase("Tiny payments");
226
227 // Regression test for tiny payments
228 using namespace jtx;
229 using namespace std::chrono_literals;
230 auto const alice = Account{"alice"};
231 auto const bob = Account{"bob"};
232 auto const carol = Account{"carol"};
233 auto const gw = Account{"gw"};
234
235 auto const test = [&](auto&& issue1, auto&& issue2) {
236 Env env{*this, features};
237
238 env.fund(XRP(10'000), alice, bob, carol, gw);
239 env.close();
240
241 auto const usd = issue1({
242 .env = env,
243 .token = "USD",
244 .issuer = gw,
245 .holders = {alice, bob, carol},
246 .limit = 400'000'000,
247 });
248 auto const eur = issue2({
249 .env = env,
250 .token = "EUR",
251 .issuer = gw,
252 .holders = {alice, bob, carol},
253 .limit = 400'000'000,
254 });
255
256 env(pay(gw, alice, usd(100'000'000)));
257 env(pay(gw, carol, eur(100'000'000)));
258
259 // Create more offers than the loop max count in DeliverNodeReverse
260 // Note: the DeliverNodeReverse code has been removed; however since
261 // this is a regression test the original test is being left as-is
262 // for now.
263 for (int i = 0; i < 101; ++i)
264 env(offer(carol, usd(1'000'000), eur(2'000'000)));
265
266 // Original Offer test sends EUR(10**-81). MPT is integral,
267 // therefore and integral value is sent respecting the exchange
268 // rate. I.e. if EUR(1) is sent then it'll result in USD(0).
269 env(pay(alice, bob, eur(2)), Path(~eur), Sendmax(usd(100)));
270 };
272 }
273
274 void
276 {
277 testcase("XRP Tiny payments");
278
279 // Regression test for tiny xrp payments
280 // In some cases, when the payment code calculates
281 // the amount of xrp needed as input to an xrp->iou offer
282 // it would incorrectly round the amount to zero (even when
283 // round-up was set to true).
284 // The bug would cause funded offers to be incorrectly removed
285 // because the code thought they were unfunded.
286 // The conditions to trigger the bug are:
287 // 1) When we calculate the amount of input xrp needed for an offer
288 // from xrp->iou, the amount is less than 1 drop (after rounding
289 // up the float representation).
290 // 2) There is another offer in the same book with a quality
291 // sufficiently bad that when calculating the input amount
292 // needed the amount is not set to zero.
293
294 using namespace jtx;
295 using namespace std::chrono_literals;
296 auto const alice = Account{"alice"};
297 auto const bob = Account{"bob"};
298 auto const carol = Account{"carol"};
299 auto const dan = Account{"dan"};
300 auto const erin = Account{"erin"};
301 auto const gw = Account{"gw"};
302
303 Env env{*this, features};
304
305 env.fund(XRP(10'000), alice, bob, carol, dan, erin, gw);
306 env.close();
307
308 MPT const usd = MPTTester({
309 .env = env,
310 .issuer = gw,
311 .holders = {alice, bob, carol, dan, erin},
312 .pay = std::nullopt,
313 });
314 env(pay(gw, carol, usd(99'999)));
315 env(pay(gw, dan, usd(100'000)));
316 env(pay(gw, erin, usd(100'000)));
317 env.close();
318
319 // Carol doesn't quite have enough funds for this offer
320 // The amount left after this offer is taken will cause
321 // STAmount to incorrectly round to zero when the next offer
322 // (at a good quality) is considered. (when the now removed
323 // stAmountCalcSwitchover2 patch was inactive)
324 env(offer(carol, drops(1), usd(99'999)));
325 // Offer at a quality poor enough so when the input xrp is
326 // calculated in the reverse pass, the amount is not zero.
327 env(offer(dan, XRP(100), usd(1)));
328
329 env.close();
330 // This is the funded offer that will be incorrectly removed.
331 // It is considered after the offer from carol, which leaves a
332 // tiny amount left to pay. When calculating the amount of xrp
333 // needed for this offer, it will incorrectly compute zero in both
334 // the forward and reverse passes (when the now removed
335 // stAmountCalcSwitchover2 was inactive.)
336 env(offer(erin, drops(2), usd(100'000)));
337
338 env(pay(alice, bob, usd(100'000)),
339 Path(~usd),
340 Sendmax(XRP(102)),
341 Txflags(tfNoRippleDirect | tfPartialPayment));
342
343 env.require(Offers(carol, 0), Offers(dan, 1));
344
345 // offer was correctly consumed. There is still some
346 // liquidity left on that offer.
347 env.require(Balance(erin, usd(99'999)), Offers(erin, 1));
348 }
349
350 void
352 {
353 testcase("Rm small increased q offers XRP");
354
355 // Carol places an offer, but cannot fully fund the offer. When her
356 // funding is taken into account, the offer's quality drops below its
357 // initial quality and has an input amount of 1 drop. This is removed as
358 // an offer that may block offer books.
359
360 using namespace jtx;
361 using namespace std::chrono_literals;
362 auto const alice = Account{"alice"};
363 auto const bob = Account{"bob"};
364 auto const carol = Account{"carol"};
365 auto const gw = Account{"gw"};
366
367 // Test offer crossing
368 for (auto const crossBothOffers : {false, true})
369 {
370 Env env{*this, features};
371
372 env.fund(XRP(10'000), alice, bob, carol, gw);
373
374 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
375 // underfund carol's offer
376 auto const initialCarolUSD = usd(499);
377 env(pay(gw, carol, initialCarolUSD));
378 env(pay(gw, bob, usd(100'000)));
379 env.close();
380 // This offer is underfunded
381 env(offer(carol, drops(1), usd(1'000)));
382 env.close();
383 // offer at a lower quality
384 env(offer(bob, drops(2), usd(1'000), tfPassive));
385 env.close();
386 env.require(Offers(bob, 1), Offers(carol, 1));
387
388 // alice places an offer that crosses carol's; depending on
389 // "crossBothOffers" it may cross bob's as well
390 auto const aliceTakerGets = crossBothOffers ? drops(2) : drops(1);
391 env(offer(alice, usd(1'000), aliceTakerGets));
392 env.close();
393
394 env.require(
395 Offers(carol, 0),
396 Balance(
397 carol,
398 initialCarolUSD)); // offer is removed but not taken
399 if (crossBothOffers)
400 {
401 env.require(
402 Offers(alice, 0), Balance(alice, usd(1'000))); // alice's offer is crossed
403 }
404 else
405 {
406 env.require(
407 Offers(alice, 1), Balance(alice, usd(0))); // alice's offer is not crossed
408 }
409 }
410
411 // Test payments
412 for (auto const partialPayment : {false, true})
413 {
414 Env env{*this, features};
415
416 env.fund(XRP(10'000), alice, bob, carol, gw);
417 env.close();
418
419 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
420 auto const initialCarolUSD = usd(999);
421 env(pay(gw, carol, initialCarolUSD));
422 env.close();
423 env(pay(gw, bob, usd(100'000)));
424 env.close();
425 env(offer(carol, drops(1), usd(1'000)));
426 env.close();
427 env(offer(bob, drops(2), usd(2'000), tfPassive));
428 env.close();
429 env.require(Offers(bob, 1), Offers(carol, 1));
430
431 std::uint32_t const flags =
432 partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect;
433
434 TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL};
435
436 env(pay(alice, bob, usd(5'000)),
437 Path(~usd),
438 Sendmax(XRP(1)),
439 Txflags(flags),
440 Ter(expectedTer));
441 env.close();
442
443 if (expectedTer == tesSUCCESS)
444 {
445 env.require(Offers(carol, 0));
446 env.require(Balance(carol,
447 initialCarolUSD)); // offer is removed but not taken
448 }
449 else
450 {
451 // TODO: Offers are not removed when payments fail
452 // If that is addressed, the test should show that carol's
453 // offer is removed but not taken, as in the other branch of
454 // this if statement
455 }
456 }
457 }
458
459 void
461 {
462 testcase("Rm small increased q offers MPT");
463
464 // Carol places an offer, but cannot fully fund the offer. When her
465 // funding is taken into account, the offer's quality drops below its
466 // initial quality and has an input amount of 1 drop. This is removed as
467 // an offer that may block offer books.
468
469 using namespace jtx;
470 using namespace std::chrono_literals;
471 auto const alice = Account{"alice"};
472 auto const bob = Account{"bob"};
473 auto const carol = Account{"carol"};
474 auto const gw = Account{"gw"};
475
476 auto const test = [&](auto&& issue1, auto&& issue2) {
477 auto const tinyAmount = [&]<typename T>(T const& token) -> PrettyAmount {
478 if constexpr (std::is_same_v<T, IOU>)
479 {
480 STAmount const amt(
481 token,
482 /*mantissa*/ 1,
483 /*exponent*/ -81);
484 return PrettyAmount(amt, token.account.name());
485 }
486 else
487 {
488 STAmount const amt(
489 token,
490 /*mantissa*/ 1,
491 /*exponent*/ 0);
492 return PrettyAmount(amt, "MPT");
493 }
494 };
495
496 // Test offer crossing
497 for (auto const crossBothOffers : {false, true})
498 {
499 Env env{*this, features};
500
501 env.fund(XRP(10'000), alice, bob, carol, gw);
502 env.close();
503
504 auto const usd = issue1({
505 .env = env,
506 .token = "USD",
507 .issuer = gw,
508 .holders = {alice, bob, carol},
509 .limit = 100'000'000,
510 });
511 auto const eur = issue2({
512 .env = env,
513 .token = "EUR",
514 .issuer = gw,
515 .holders = {alice, bob, carol},
516 .limit = 100'000'000,
517 });
518 // underfund carol's offer
519 auto const initialCarolUSD = tinyAmount(usd);
520 env(pay(gw, carol, initialCarolUSD));
521 env(pay(gw, bob, usd(100'000)));
522 env(pay(gw, alice, eur(100'000)));
523 env.close();
524 // This offer is underfunded
525 env(offer(carol, eur(10), usd(10'000)));
526 env.close();
527 // offer at a lower quality
528 env(offer(bob, eur(10), usd(5'000), tfPassive));
529 env.close();
530 env.require(Offers(bob, 1), Offers(carol, 1));
531
532 // alice places an offer that crosses carol's; depending on
533 // "crossBothOffers" it may cross bob's as well
534 // Whatever
535 auto const aliceTakerGets = crossBothOffers ? eur(2) : eur(1);
536 env(offer(alice, usd(1'000), aliceTakerGets));
537 env.close();
538
539 // carol's offer can be partially crossed when EUR is IOU:
540 // 10e-3EUR/1USD
541 using TEur = std::decay_t<decltype(eur)>;
542 static constexpr bool kIsEuriou = std::is_same_v<TEur, IOU>;
543 // partially crossed if IOU, removed but not taken if MPT
544 auto const balanceCarolUSD = kIsEuriou ? usd(0) : initialCarolUSD;
545
546 env.require(Offers(carol, 0), Balance(carol, balanceCarolUSD));
547 if (crossBothOffers)
548 {
549 env.require(
550 Offers(alice, 0), Balance(alice, usd(1'000))); // alice's offer is crossed
551 }
552 else
553 {
554 // partially crossed if IOU, not crossed if MPT
555 auto const balanceAliceUSD = kIsEuriou ? usd(1) : usd(0);
556 env.require(Offers(alice, 1), Balance(alice, balanceAliceUSD));
557 }
558 }
559
560 // Test payments
561 for (auto const partialPayment : {false, true})
562 {
563 Env env{*this, features};
564
565 env.fund(XRP(10'000), alice, bob, carol, gw);
566 env.close();
567
568 auto const usd = issue1({
569 .env = env,
570 .token = "USD",
571 .issuer = gw,
572 .holders = {alice, bob, carol},
573 .limit = 100'000'000,
574 });
575 auto const eur = issue2({
576 .env = env,
577 .token = "EUR",
578 .issuer = gw,
579 .holders = {alice, bob, carol},
580 .limit = 100'000'000,
581 });
582 // underfund carol's offer
583 auto const initialCarolUSD = tinyAmount(usd);
584 env(pay(gw, carol, initialCarolUSD));
585 env(pay(gw, bob, usd(100'000)));
586 env(pay(gw, alice, eur(100'000)));
587 env.close();
588 // This offer is underfunded
589 env(offer(carol, eur(10), usd(2'000)));
590 env.close();
591 env(offer(bob, eur(20), usd(4'000), tfPassive));
592 env.close();
593 env.require(Offers(bob, 1), Offers(carol, 1));
594
595 std::uint32_t const flags =
596 partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect;
597
598 TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL};
599
600 env(pay(alice, bob, usd(5'000)),
601 Path(~usd),
602 Sendmax(eur(100)),
603 Txflags(flags),
604 Ter(expectedTer));
605 env.close();
606
607 if (expectedTer == tesSUCCESS)
608 {
609 // carol's offer can be partially crossed when EUR is IOU:
610 // 10e-3EUR/1USD
611 using TEur = std::decay_t<decltype(eur)>;
612 static constexpr bool kIsEuriou = std::is_same_v<TEur, IOU>;
613 // partially crossed if IOU, removed but not taken if MPT
614 auto const balanceCarolUSD = kIsEuriou ? usd(0) : initialCarolUSD;
615 env.require(Offers(carol, 0));
616 env.require(Balance(carol, balanceCarolUSD));
617 }
618 else
619 {
620 // TODO: Offers are not removed when payments fail
621 // If that is addressed, the test should show that carol's
622 // offer is removed but not taken, as in the other branch of
623 // this if statement
624 }
625 }
626 };
628 }
629
630 void
632 {
633 testcase("MPT issuer offer dust removal uses remaining issuance capacity");
634
635 using namespace jtx;
636
637 Account const issuer{"issuer"};
638 Account const carol{"carol"};
639 Account const bob{"bob"};
640
641 Env env{*this, features};
642 env.fund(XRP(10'000), issuer, carol, bob);
643 env.close();
644
645 MPTTester const musd(
646 {.env = env, .issuer = issuer, .holders = {carol, bob}, .maxAmt = 101});
647
648 // The issuer offer is fully fundable when placed. Later issuance leaves
649 // only one MPT of remaining capacity, so this issuer-owned MPT offer
650 // must be clipped by owner funds just like a holder-funded offer.
651 auto const issuerOfferSeq = env.seq(issuer);
652 env(offer(issuer, drops(1), musd(100)));
653 env.close();
654
655 env(pay(issuer, carol, musd(100)));
656 env.close();
657 BEAST_EXPECT(env.balance(issuer, musd) == musd(-100));
658 BEAST_EXPECT(env.balance(carol, musd) == musd(100));
659
660 // Carol's same-quality offer provides the legitimately funded side of
661 // the crossing. Without the issuer-cap dust-removal check, Bob would
662 // receive Carol's 100 MPT plus one free self-issued MPT from issuer's
663 // stale offer while paying only Carol's one drop.
664 auto const carolOfferSeq = env.seq(carol);
665 env(offer(carol, drops(1), musd(100)));
666 env.close();
667
668 auto const issuerOffer = keylet::offer(issuer.id(), SeqProxy::rawSequence(issuerOfferSeq));
669 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
670 BEAST_EXPECT(env.le(issuerOffer) != nullptr);
671 BEAST_EXPECT(env.le(carolOffer) != nullptr);
672
673 env(offer(bob, musd(101), drops(2), tfImmediateOrCancel));
674 env.close();
675
676 BEAST_EXPECT(env.le(issuerOffer) == nullptr);
677 BEAST_EXPECT(env.le(carolOffer) == nullptr);
678 env.require(Offers(issuer, 0), Offers(carol, 0), Offers(bob, 0));
679 BEAST_EXPECT(env.balance(issuer, musd) == musd(-100));
680 BEAST_EXPECT(env.balance(carol, musd) == musd(0));
681 BEAST_EXPECT(env.balance(bob, musd) == musd(100));
682 }
683
684 // Issuer-owned MPT sell offer + transfer fee + remaining capacity 1.
685 //
686 // OfferStream's dust check is fee-blind: it clips by owner funds only, sees
687 // 1 MPT for 1 XRP and keeps the offer. BookStep then ceils ownerGives for
688 // the fee and floors funds/rate back to 0, so the offer can't give anyone a
689 // single unit. It used to be consumed as a zero slice and left at the tip
690 // of the book; under featureMPTokensV2 it is removed instead. The removal
691 // survives the taker's tecKILLED because CreateOffer applies sbCancel when
692 // applyGuts fails.
693 void
695 {
696 testcase("MPT offer whose funded output rounds to zero is removed");
697
698 using namespace jtx;
699
700 Account const issuer{"issuer"};
701 Account const bob{"bob"};
702
703 Env env{*this, features};
704 env.fund(XRP(10'000), issuer, bob);
705 env.close();
706
707 // 10% transfer fee: Rate = QUALITY_ONE + 10_000 * 10_000 = 1.1e9.
708 // floor(1 * QUALITY_ONE / rate) == 0, which is the BookStep clip.
709 constexpr std::uint16_t kTenPercentFee = 10'000;
710 MPTTester const usd({
711 .env = env,
712 .issuer = issuer,
713 .holders = {bob},
714 .transferFee = kTenPercentFee,
715 .maxAmt = 1,
716 });
717 BEAST_EXPECT(usd.checkTransferFee(kTenPercentFee));
718
719 // TakerPays is large enough that quality-scaling 100 MPT → 1 MPT still
720 // leaves TakerPays >= 1 drop, so OfferStream keeps the offer. The
721 // 1-drop offer in testMPTIssuerOfferUsesRemainingCapacity is dust
722 // removed there instead (its scaled TakerPays rounds to 0).
723 auto const issuerOfferSeq = env.seq(issuer);
724 env(offer(issuer, XRP(100), usd(100)));
725 env.close();
726
727 auto const issuerOffer = keylet::offer(issuer.id(), SeqProxy::rawSequence(issuerOfferSeq));
728 BEAST_EXPECT(env.le(issuerOffer) != nullptr);
729 BEAST_EXPECT(env.balance(issuer, usd) == usd(0));
730
731 auto const bobXRPBefore = env.balance(bob);
732 auto const bobMPTBefore = env.balance(bob, usd);
733 auto const fee = env.current()->fees().base;
734
735 // Offer crossing sets ownerPaysTransferFee=true, so trOut is the 10%
736 // rate (Payment would use QUALITY_ONE and would not hit this).
737 env(offer(bob, usd(100), XRP(100), tfImmediateOrCancel), Ter(tecKILLED));
738 env.close();
739
740 // The unfillable offer is gone, nothing was issued, and Bob's IOC does
741 // not rest.
742 BEAST_EXPECT(env.le(issuerOffer) == nullptr);
743 BEAST_EXPECT(env.balance(issuer, usd) == usd(0));
744 BEAST_EXPECT(env.balance(bob, usd) == bobMPTBefore);
745 BEAST_EXPECT(env.balance(bob) == bobXRPBefore - fee);
746 env.require(Offers(issuer, 0), Offers(bob, 0));
747 }
748
749 // Same zero-output offer, but with funded liquidity behind it.
750 //
751 // A consumed zero slice makes the step produce nothing, so the strand is
752 // found dry in rev (StrandFlow) and dropped, and Carol's offer is never
753 // reached — the tip offer blocks the book for every taker, permanently.
754 // Removing it lets the same transaction cross Carol.
755 void
757 {
758 testcase("MPT zero-output offer does not block the book");
759
760 using namespace jtx;
761
762 Account const issuer{"issuer"};
763 Account const carol{"carol"};
764 Account const bob{"bob"};
765
766 Env env{*this, features};
767 env.fund(XRP(10'000), issuer, carol, bob);
768 env.close();
769
770 constexpr std::uint16_t kTenPercentFee = 10'000;
771 MPT const usd = MPTTester({
772 .env = env,
773 .issuer = issuer,
774 .holders = {carol, bob},
775 .transferFee = kTenPercentFee,
776 .maxAmt = 101,
777 });
778
779 // Leaves the issuer one MPT of issuance capacity, which the 10% fee
780 // rounds down to zero output.
781 env(pay(issuer, carol, usd(100)));
782 env.close();
783
784 // The issuer's offer is the better quality, so it sits at the tip.
785 auto const issuerOfferSeq = env.seq(issuer);
786 env(offer(issuer, XRP(100), usd(100)));
787 env.close();
788
789 auto const carolOfferSeq = env.seq(carol);
790 env(offer(carol, XRP(200), usd(100)));
791 env.close();
792
793 auto const issuerOffer = keylet::offer(issuer.id(), SeqProxy::rawSequence(issuerOfferSeq));
794 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
795 BEAST_EXPECT(env.le(issuerOffer) != nullptr);
796 BEAST_EXPECT(env.le(carolOffer) != nullptr);
797
798 env(offer(bob, usd(50), XRP(100)));
799 env.close();
800
801 // The issuer's offer is removed and Bob crosses Carol in the same
802 // transaction. Carol pays the 10% fee on top of the 50 she gives.
803 BEAST_EXPECT(env.le(issuerOffer) == nullptr);
804 BEAST_EXPECT(env.balance(bob, usd) == usd(50));
805 BEAST_EXPECT(env.balance(carol, usd) == usd(45));
806 BEAST_EXPECT(env.balance(issuer, usd) == usd(-95));
807
808 auto const sle = env.le(carolOffer);
809 BEAST_EXPECT(sle != nullptr);
810 if (sle)
811 {
812 BEAST_EXPECT((*sle)[sfTakerPays] == XRP(100));
813 BEAST_EXPECT((*sle)[sfTakerGets] == usd(50));
814 }
815 env.require(Offers(issuer, 0), Offers(carol, 1), Offers(bob, 0));
816 }
817
818 // Same tip-block as testMPTOfferFeeZeroOutUnblocksBook, but the unfillable
819 // offer is a holder's. isFunded() is IOU-issuer only, so 1 MPT + a 10% fee
820 // floors the same way. Not specific to issuerSelfDebitHookMPT.
821 void
823 {
824 testcase("MPT holder zero-output offer does not block the book");
825
826 using namespace jtx;
827
828 Account const issuer{"issuer"};
829 Account const alice{"alice"};
830 Account const carol{"carol"};
831 Account const bob{"bob"};
832
833 Env env{*this, features};
834 env.fund(XRP(10'000), issuer, alice, carol, bob);
835 env.close();
836
837 constexpr std::uint16_t kTenPercentFee = 10'000;
838 MPT const usd = MPTTester({
839 .env = env,
840 .issuer = issuer,
841 .holders = {alice, carol, bob},
842 .transferFee = kTenPercentFee,
843 });
844
845 env(pay(issuer, alice, usd(1)));
846 env(pay(issuer, carol, usd(100)));
847 env.close();
848
849 auto const aliceOfferSeq = env.seq(alice);
850 env(offer(alice, XRP(100), usd(100)));
851 env.close();
852
853 auto const carolOfferSeq = env.seq(carol);
854 env(offer(carol, XRP(200), usd(100)));
855 env.close();
856
857 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
858 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
859 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
860 BEAST_EXPECT(env.le(carolOffer) != nullptr);
861
862 env(offer(bob, usd(50), XRP(100)));
863 env.close();
864
865 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
866 BEAST_EXPECT(env.balance(alice, usd) == usd(1));
867 BEAST_EXPECT(env.balance(bob, usd) == usd(50));
868 BEAST_EXPECT(env.balance(carol, usd) == usd(45));
869
870 auto const sle = env.le(carolOffer);
871 BEAST_EXPECT(sle != nullptr);
872 if (sle)
873 {
874 BEAST_EXPECT((*sle)[sfTakerPays] == XRP(100));
875 BEAST_EXPECT((*sle)[sfTakerGets] == usd(50));
876 }
877 env.require(Offers(alice, 0), Offers(carol, 1), Offers(bob, 0));
878 }
879
880 // The MaximumAmount limit on an MPT input can also clip an offer's output
881 // to zero. That slice is consumed rather than removed: the rest of the
882 // offer is still funded, so it must stay on the book. The owner here is
883 // the output issuer, so consumeOffer() reaches issuerSelfDebitHookMPT()
884 // with a zero amount, which the hook has to tolerate (it used to assert
885 // amount > 0 and abort a Debug build).
886 void
888 {
889 testcase("MPT issuer offer clipped to zero output by the issuance cap");
890
891 using namespace jtx;
892
893 Account const issuerA{"issuerA"};
894 Account const issuerB{"issuerB"};
895 Account const alice{"alice"};
896 Account const bob{"bob"};
897
898 Env env{*this, features};
899 env.fund(XRP(10'000), issuerA, issuerB, alice, bob);
900 env.close();
901
902 // BookStep limits an MPT input to MaximumAmount (see maxIn_). a's cap
903 // is far below the offer's TakerPays, so limitStepIn() scales TakerGets
904 // down to floor(10 * 1 / 1'000) == 0.
905 MPT const a =
906 MPTTester({.env = env, .issuer = issuerA, .holders = {alice, issuerB}, .maxAmt = 10});
907 MPT const b = MPTTester({.env = env, .issuer = issuerB, .holders = {bob}});
908
909 env(pay(issuerA, alice, a(10)));
910 env.close();
911
912 auto const offerSeq = env.seq(issuerB);
913 env(offer(issuerB, a(1'000), b(1)));
914 env.close();
915
916 auto const bookOffer = keylet::offer(issuerB.id(), SeqProxy::rawSequence(offerSeq));
917 BEAST_EXPECT(env.le(bookOffer) != nullptr);
918
919 env(pay(alice, bob, b(1)),
920 Sendmax(a(10)),
921 Path(~b),
922 Txflags(tfNoRippleDirect),
924 env.close();
925
926 // The step produces nothing, so the payment can't deliver, and the
927 // capped offer is left on the book untouched.
928 BEAST_EXPECT(env.le(bookOffer) != nullptr);
929 BEAST_EXPECT(env.balance(alice, a) == a(10));
930 BEAST_EXPECT(env.balance(issuerB, a) == a(0));
931 BEAST_EXPECT(env.balance(bob, b) == b(0));
932 }
933
934 // IOU twin, pre and post featureMPTokensV2.
935 //
936 // An IOU issuer is isFunded() (unlimited), so they never take the
937 // funds < ownerGives clip. A holder does. Alice's TakerGets is the smallest
938 // IOU (1e-81) and floor(funds * QUALITY_ONE / 1.1e9) == 0, because the
939 // mantissa can no longer renormalize at the minimum exponent. The offer
940 // survives OfferStream's dust check through its TakerPays >= TakerGets
941 // early return, so this is the IOU shape that can block a book: quality
942 // <= 1 with an epsilon-funded owner.
943 //
944 // Pre-amendment BookStep consumes a zero slice, Alice's offer stays at the
945 // tip and Carol's funded offer is unreachable. Post-amendment Alice's offer
946 // is removed and the same transaction crosses Carol.
947 void
949 {
950 testcase("IOU offer whose funded output rounds to zero");
951
952 using namespace jtx;
953
954 // EUR has no transfer rate, so the taker is not grossed up on the
955 // input and the crossed amounts stay round.
956 auto const test = [&](FeatureBitset const& fs) {
957 Account const gw{"gateway"};
958 Account const gw2{"gateway2"};
959 Account const alice{"alice"};
960 Account const carol{"carol"};
961 Account const dan{"dan"};
962 auto const usd = gw["USD"];
963 auto const eur = gw2["EUR"];
964
965 Env env{*this, fs};
966 env.fund(XRP(10'000), gw, gw2, alice, carol, dan);
967 env.close();
968
969 env(rate(gw, 1.1));
970 env.trust(usd(10'000), alice, carol, dan);
971 env.trust(eur(10'000), alice, carol, dan);
972 env.close();
973
974 env(pay(gw, alice, usd(kEpsilon)));
975 env(pay(gw, carol, usd(100)));
976 env(pay(gw2, dan, eur(1'000)));
977 env.close();
978 BEAST_EXPECT(env.balance(alice, usd) == usd(kEpsilon));
979
980 // Alice is at the tip (1 USD per EUR), Carol behind her (0.5).
981 auto const aliceOfferSeq = env.seq(alice);
982 env(offer(alice, eur(100), usd(100)));
983 env.close();
984
985 auto const carolOfferSeq = env.seq(carol);
986 env(offer(carol, eur(200), usd(100)));
987 env.close();
988
989 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
990 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
991 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
992 BEAST_EXPECT(env.le(carolOffer) != nullptr);
993
994 env(offer(dan, usd(50), eur(100)));
995 env.close();
996
997 if (fs[featureMPTokensV2])
998 {
999 // Alice's offer is removed, Dan crosses Carol.
1000 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1001 BEAST_EXPECT(env.balance(dan, usd) == usd(50));
1002 BEAST_EXPECT(env.balance(dan, eur) == eur(900));
1003 BEAST_EXPECT(env.balance(carol, usd) == usd(45));
1004 BEAST_EXPECT(env.balance(carol, eur) == eur(100));
1005
1006 auto const sle = env.le(carolOffer);
1007 BEAST_EXPECT(sle != nullptr);
1008 if (sle)
1009 {
1010 BEAST_EXPECT((*sle)[sfTakerPays] == eur(100));
1011 BEAST_EXPECT((*sle)[sfTakerGets] == usd(50));
1012 }
1013 env.require(Offers(alice, 0), Offers(carol, 1), Offers(dan, 0));
1014 }
1015 else
1016 {
1017 // Alice's offer is consumed as a zero slice: the SLE is
1018 // unchanged, Carol is never reached and Dan's offer rests.
1019 auto const sle = env.le(aliceOffer);
1020 BEAST_EXPECT(sle != nullptr);
1021 if (sle)
1022 {
1023 BEAST_EXPECT((*sle)[sfTakerPays] == eur(100));
1024 BEAST_EXPECT((*sle)[sfTakerGets] == usd(100));
1025 }
1026 BEAST_EXPECT(env.balance(dan, usd) == usd(0));
1027 BEAST_EXPECT(env.balance(dan, eur) == eur(1'000));
1028 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
1029 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1030 env.require(Offers(alice, 1), Offers(carol, 1), Offers(dan, 1));
1031 }
1032
1033 // Alice keeps her epsilon either way.
1034 BEAST_EXPECT(env.balance(alice, usd) == usd(kEpsilon));
1035 };
1036
1037 test(features - featureMPTokensV2);
1038 test(features);
1039 }
1040
1041 // OfferStream keeps an offer when ownerFunds >= TakerGets. BookStep then
1042 // clips against TakerGets * transferRate. For TakerPays of 1 integral
1043 // unit and funds in [TakerGets, TakerGets*rate), that clip truncates
1044 // TakerPays to 0 while leaving a positive out. Without the BookStep
1045 // guard the issuer of the input MPT (BookStep is strand[0]) would take
1046 // the funded TakerGets for free. Offer crossing, not Payment: only
1047 // crossing sets ownerPaysTransferFee, so trOut is the fee rate.
1048 void
1050 {
1051 testcase(
1052 "MPT offer whose fee-clipped input truncates to zero is "
1053 "removed");
1054
1055 using namespace jtx;
1056
1057 // 10%: ownerGives = 1000 * 1.1 = 1100. funds = 1001 is in
1058 // [1000, 1100). floor(1001 / 1.1) = 910 out; in = floor(910/1000)
1059 // = 0.
1060 constexpr std::uint16_t kTenPercentFee = 10'000;
1061
1062 auto const run = [&](auto&& makeOut) {
1063 Account const bondIssuer{"bondIssuer"};
1064 Account const outIssuer{"outIssuer"};
1065 Account const alice{"alice"};
1066
1067 Env env{*this, features};
1068 env.fund(XRP(10'000), bondIssuer, outIssuer, alice);
1069 env.close();
1070
1071 MPT const bond = MPTTester({.env = env, .issuer = bondIssuer, .holders = {alice}});
1072 auto const out = makeOut(env, outIssuer, bondIssuer, alice, kTenPercentFee);
1073
1074 env(pay(outIssuer, alice, out(1'001)));
1075 env.close();
1076
1077 auto const aliceOfferSeq = env.seq(alice);
1078 env(offer(alice, bond(1), out(1'000)));
1079 env.close();
1080
1081 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
1082 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
1083 BEAST_EXPECT(env.balance(alice, out) == out(1'001));
1084
1085 auto const issuerOutBefore = env.balance(bondIssuer, out);
1086
1087 // bondIssuer is the input-MPT issuer, so BookStep is first
1088 // and a zero-in / positive-out strand would have been applied.
1089 env(offer(bondIssuer, out(1'000), bond(1), tfImmediateOrCancel), Ter(tecKILLED));
1090 env.close();
1091
1092 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1093 BEAST_EXPECT(env.balance(alice, out) == out(1'001));
1094 BEAST_EXPECT(env.balance(alice, bond) == bond(0));
1095 BEAST_EXPECT(env.balance(bondIssuer, out) == issuerOutBefore);
1096 env.require(Offers(alice, 0), Offers(bondIssuer, 0));
1097 };
1098
1099 run([&](Env& env,
1100 Account const& gw,
1101 Account const& taker,
1102 Account const& alice,
1103 std::uint16_t) {
1104 auto const usd = gw["USD"];
1105 env(rate(gw, 1.1));
1106 env.trust(usd(10'000), alice, taker);
1107 env.close();
1108 return usd;
1109 });
1110
1111 run([&](Env& env,
1112 Account const& gw,
1113 Account const& taker,
1114 Account const& alice,
1115 std::uint16_t fee) {
1116 return MPT(MPTTester(
1117 {.env = env, .issuer = gw, .holders = {alice, taker}, .transferFee = fee}));
1118 });
1119 }
1120
1121 // Same un-fillable tip, with funded liquidity behind it. Removing the
1122 // zero-in offer lets the same crossing reach Carol. A consumed zero-in
1123 // slice would have succeeded as a strand (out > 0) and never tried her.
1124 void
1126 {
1127 testcase("MPT zero-input offer does not block the book");
1128
1129 using namespace jtx;
1130
1131 Account const bondIssuer{"bondIssuer"};
1132 Account const gw{"gateway"};
1133 Account const alice{"alice"};
1134 Account const carol{"carol"};
1135 auto const usd = gw["USD"];
1136
1137 Env env{*this, features};
1138 env.fund(XRP(10'000), bondIssuer, gw, alice, carol);
1139 env.close();
1140
1141 MPT const bond = MPTTester({.env = env, .issuer = bondIssuer, .holders = {alice, carol}});
1142
1143 env(rate(gw, 1.1));
1144 env.trust(usd(10'000), alice, carol, bondIssuer);
1145 env.close();
1146
1147 env(pay(gw, alice, usd(1'001)));
1148 env(pay(gw, carol, usd(2'000)));
1149 env.close();
1150
1151 // Alice is the better quality (1000 USD / 1 BOND) and sits at the
1152 // tip. Her 1001 USD cannot cover the 10% fee on 1000.
1153 auto const aliceOfferSeq = env.seq(alice);
1154 env(offer(alice, bond(1), usd(1'000)));
1155 env.close();
1156
1157 auto const carolOfferSeq = env.seq(carol);
1158 env(offer(carol, bond(2), usd(1'000)));
1159 env.close();
1160
1161 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
1162 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
1163 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
1164 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1165
1166 env(offer(bondIssuer, usd(500), bond(1)));
1167 env.close();
1168
1169 // Alice's offer is removed unconsumed. BondIssuer crosses Carol
1170 // for 500 USD; Carol pays the 10% fee on that 500.
1171 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1172 BEAST_EXPECT(env.balance(alice, usd) == usd(1'001));
1173 BEAST_EXPECT(env.balance(alice, bond) == bond(0));
1174 BEAST_EXPECT(env.balance(bondIssuer, usd) == usd(500));
1175 BEAST_EXPECT(env.balance(carol, usd) == usd(1'450));
1176 BEAST_EXPECT(env.balance(carol, bond) == bond(1));
1177
1178 auto const sle = env.le(carolOffer);
1179 BEAST_EXPECT(sle != nullptr);
1180 if (sle)
1181 {
1182 BEAST_EXPECT((*sle)[sfTakerPays] == bond(1));
1183 BEAST_EXPECT((*sle)[sfTakerGets] == usd(500));
1184 }
1185 env.require(Offers(alice, 0), Offers(carol, 1), Offers(bondIssuer, 0));
1186 }
1187
1188 // TakerPays = 2 in the same funds window must still fill: the clip
1189 // leaves in = 1, not 0. A too-broad "any reduced offer" guard would
1190 // wrongly delete it.
1191 void
1193 {
1194 testcase("MPT offer with TakerPays 2 still fills after the fee clip");
1195
1196 using namespace jtx;
1197
1198 Account const bondIssuer{"bondIssuer"};
1199 Account const gw{"gateway"};
1200 Account const alice{"alice"};
1201 auto const usd = gw["USD"];
1202
1203 Env env{*this, features};
1204 env.fund(XRP(10'000), bondIssuer, gw, alice);
1205 env.close();
1206
1207 MPT const bond = MPTTester({.env = env, .issuer = bondIssuer, .holders = {alice}});
1208
1209 env(rate(gw, 1.1));
1210 env.trust(usd(10'000), alice, bondIssuer);
1211 env.close();
1212
1213 env(pay(gw, alice, usd(1'001)));
1214 env.close();
1215
1216 auto const aliceOfferSeq = env.seq(alice);
1217 env(offer(alice, bond(2), usd(1'000)));
1218 env.close();
1219
1220 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
1221 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
1222
1223 env(offer(bondIssuer, usd(1'000), bond(2), tfImmediateOrCancel));
1224 env.close();
1225
1226 // in' = floor(2 * 1001 / 1100) = 1; out = 910. Alice pays her
1227 // whole 1001 (ownerGives) and is credited 1 BOND. The leftover
1228 // {1, 90} is unfunded after that debit, so it is deleted.
1229 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1230 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
1231 BEAST_EXPECT(env.balance(alice, bond) == bond(1));
1232 BEAST_EXPECT(env.balance(bondIssuer, usd) == usd(910));
1233 env.require(Offers(alice, 0), Offers(bondIssuer, 0));
1234 }
1235
1236 // A funds-limited MPT offer delivers floor(funds / rate), so the owner
1237 // owes ceil(out × rate), not all of funds. With a 1.5 rate, 10 funds 6 out,
1238 // which costs 9; 11 funds 7 out, which costs exactly 11.
1239 void
1241 {
1242 testcase("Funds-limited MPT offer owner pays ceil(out * rate)");
1243
1244 using namespace jtx;
1245
1246 Account const issuer{"issuer"};
1247 Account const seller{"seller"};
1248 Account const buyer{"buyer"};
1249
1250 struct TestCase
1251 {
1252 std::int64_t funds;
1253 std::int64_t out;
1254 std::int64_t paid;
1255 };
1256 for (auto const& tc : {
1257 TestCase{.funds = 10, .out = 6, .paid = 9},
1258 TestCase{.funds = 11, .out = 7, .paid = 11},
1259 })
1260 {
1261 Env env{*this, features};
1262 env.fund(XRP(10'000), issuer, seller, buyer);
1263 env.close();
1264
1265 // TransferFee 50'000 is a 1.5 rate.
1266 MPT const usd = MPTTester(
1267 {.env = env, .issuer = issuer, .holders = {seller, buyer}, .transferFee = 50'000});
1268
1269 env(pay(issuer, seller, usd(tc.funds)));
1270 env.close();
1271
1272 env(offer(seller, XRP(100), usd(100)));
1273 env.close();
1274
1275 auto const sellerXRPBefore = env.balance(seller);
1276
1277 env(offer(buyer, usd(100), XRP(100)));
1278 env.close();
1279
1280 // Only the fee is burned: OutstandingAmount drops by paid - out.
1281 BEAST_EXPECT(env.balance(buyer, usd) == usd(tc.out));
1282 BEAST_EXPECT(env.balance(seller, usd) == usd(tc.funds - tc.paid));
1283 BEAST_EXPECT(env.balance(seller) == sellerXRPBefore + XRP(tc.out));
1284 BEAST_EXPECT(env.balance(issuer, usd) == usd(-(tc.funds - tc.paid + tc.out)));
1285 env.require(Offers(seller, 0), Offers(buyer, 1));
1286 }
1287 }
1288
1289 // After the fix the owner keeps a unit that can't fund any output. The
1290 // zero-out removal deletes the offer, and the same crossing reaches Carol.
1291 void
1293 {
1294 testcase("Funds-limited MPT offer leftover does not block the book");
1295
1296 using namespace jtx;
1297
1298 Account const issuer{"issuer"};
1299 Account const seller{"seller"};
1300 Account const carol{"carol"};
1301 Account const buyer{"buyer"};
1302
1303 Env env{*this, features};
1304 env.fund(XRP(10'000), issuer, seller, carol, buyer);
1305 env.close();
1306
1307 MPT const usd = MPTTester({
1308 .env = env,
1309 .issuer = issuer,
1310 .holders = {seller, carol, buyer},
1311 .transferFee = 50'000,
1312 });
1313
1314 env(pay(issuer, seller, usd(10)));
1315 env(pay(issuer, carol, usd(100)));
1316 env.close();
1317
1318 // The seller's offer is the better quality, so it sits at the tip.
1319 auto const sellerOfferSeq = env.seq(seller);
1320 env(offer(seller, XRP(100), usd(100)));
1321 auto const carolOfferSeq = env.seq(carol);
1322 env(offer(carol, XRP(200), usd(100)));
1323 env.close();
1324
1325 env(offer(buyer, usd(10), XRP(20)));
1326 env.close();
1327
1328 // The seller gives 6 for 6 XRP and pays 9, keeping 1. That unit funds
1329 // floor(1 / 1.5) = 0, so the offer is removed. Carol gives the other 4
1330 // for 8 XRP and pays ceil(4 * 1.5) = 6.
1331 BEAST_EXPECT(
1332 env.le(keylet::offer(seller.id(), SeqProxy::rawSequence(sellerOfferSeq))) == nullptr);
1333 BEAST_EXPECT(env.balance(seller, usd) == usd(1));
1334 BEAST_EXPECT(env.balance(carol, usd) == usd(94));
1335 BEAST_EXPECT(env.balance(buyer, usd) == usd(10));
1336 BEAST_EXPECT(env.balance(issuer, usd) == usd(-105));
1337
1338 auto const sle = env.le(keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq)));
1339 BEAST_EXPECT(sle != nullptr);
1340 if (sle)
1341 {
1342 BEAST_EXPECT((*sle)[sfTakerPays] == XRP(192));
1343 BEAST_EXPECT((*sle)[sfTakerGets] == usd(96));
1344 }
1345 env.require(Offers(seller, 0), Offers(carol, 1), Offers(buyer, 0));
1346 }
1347
1348 // XRP twin of the zero-in fee clip. TakerPays of 1 drop truncates to 0
1349 // in the same funds window. XrpEndpointStep precedes BookStep, so the
1350 // strand dries instead of applying the zero-in slice: pre-amendment the
1351 // tip stays and Carol is unreachable (a stuck book, not theft).
1352 // Post-amendment the tip is removed and the same crossing reaches Carol.
1353 void
1355 {
1356 testcase("XRP offer whose fee-clipped input truncates to zero");
1357
1358 using namespace jtx;
1359
1360 auto const test = [&](FeatureBitset const& fs) {
1361 Account const gw{"gateway"};
1362 Account const alice{"alice"};
1363 Account const carol{"carol"};
1364 Account const dan{"dan"};
1365 auto const usd = gw["USD"];
1366
1367 Env env{*this, fs};
1368 env.fund(XRP(10'000), gw, alice, carol, dan);
1369 env.close();
1370
1371 env(rate(gw, 1.1));
1372 env.trust(usd(10'000), alice, carol, dan);
1373 env.close();
1374
1375 env(pay(gw, alice, usd(1'001)));
1376 env(pay(gw, carol, usd(2'000)));
1377 env.close();
1378
1379 // Alice at the tip (1000 USD per drop), Carol behind (500).
1380 auto const aliceOfferSeq = env.seq(alice);
1381 env(offer(alice, drops(1), usd(1'000)));
1382 env.close();
1383
1384 auto const carolOfferSeq = env.seq(carol);
1385 env(offer(carol, drops(2), usd(1'000)));
1386 env.close();
1387
1388 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
1389 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
1390 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
1391 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1392
1393 env(offer(dan, usd(500), drops(1)));
1394 env.close();
1395
1396 if (fs[featureMPTokensV2])
1397 {
1398 // Alice's offer is removed, Dan crosses Carol.
1399 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1400 BEAST_EXPECT(env.balance(dan, usd) == usd(500));
1401 BEAST_EXPECT(env.balance(carol, usd) == usd(1'450));
1402
1403 auto const sle = env.le(carolOffer);
1404 BEAST_EXPECT(sle != nullptr);
1405 if (sle)
1406 {
1407 BEAST_EXPECT((*sle)[sfTakerPays] == drops(1));
1408 BEAST_EXPECT((*sle)[sfTakerGets] == usd(500));
1409 }
1410 env.require(Offers(alice, 0), Offers(carol, 1), Offers(dan, 0));
1411 }
1412 else
1413 {
1414 // The strand dries on Alice's zero-in slice: her SLE is
1415 // unchanged, Carol is never reached and Dan's offer rests.
1416 auto const sle = env.le(aliceOffer);
1417 BEAST_EXPECT(sle != nullptr);
1418 if (sle)
1419 {
1420 BEAST_EXPECT((*sle)[sfTakerPays] == drops(1));
1421 BEAST_EXPECT((*sle)[sfTakerGets] == usd(1'000));
1422 }
1423 BEAST_EXPECT(env.balance(dan, usd) == usd(0));
1424 BEAST_EXPECT(env.balance(carol, usd) == usd(2'000));
1425 env.require(Offers(alice, 1), Offers(carol, 1), Offers(dan, 1));
1426 }
1427
1428 // Alice keeps her USD either way.
1429 BEAST_EXPECT(env.balance(alice, usd) == usd(1'001));
1430 };
1431
1432 test(features - featureMPTokensV2);
1433 test(features);
1434 }
1435
1436 // An MPT TakerPays whose legacy divide() quotient lands in [2^63, 2^64)
1437 // used to be read as a negative rate, and getRate() dropped the sign, so
1438 // the offer was indexed at a far better quality than its amounts. It must
1439 // rest at its true quality, behind a normally priced offer.
1440 void
1442 {
1443 testcase("MPT offer with a large TakerPays rests at its true quality");
1444
1445 using namespace jtx;
1446
1447 Account const gw{"gateway"};
1448 Account const alice{"alice"};
1449 Account const carol{"carol"};
1450 auto const usd = gw["USD"];
1451
1452 Env env{*this, features};
1453 env.fund(XRP(10'000), gw, alice, carol);
1454 env.close();
1455
1456 MPT const mpt = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}});
1457
1458 env.trust(usd(10'000), alice, carol);
1459 env.close();
1460
1461 STAmount const dust{usd.issue(), 1, -7};
1462 env(pay(gw, alice, dust));
1463 env(pay(gw, carol, usd(100)));
1464 env.close();
1465
1466 auto const carolOfferSeq = env.seq(carol);
1467 env(offer(carol, mpt(100), usd(100)));
1468 env.close();
1469
1470 STAmount const largeMpt = mpt(184'467'440'737'095'516);
1471 auto const aliceOfferSeq = env.seq(alice);
1472 env(offer(alice, largeMpt, dust));
1473 env.close();
1474
1475 auto const dirQuality = [&](Account const& owner, std::uint32_t seq) {
1476 auto const sle = env.le(keylet::offer(owner.id(), SeqProxy::rawSequence(seq)));
1477 BEAST_EXPECT(sle != nullptr);
1478 if (!sle)
1479 return STAmount{};
1480 return amountFromQuality(getQuality(sle->getFieldH256(sfBookDirectory)));
1481 };
1482
1483 auto const aliceRate = dirQuality(alice, aliceOfferSeq);
1484 auto const carolRate = dirQuality(carol, carolOfferSeq);
1485 BEAST_EXPECT(aliceRate == STAmount(noIssue(), Number{largeMpt} / Number{dust}));
1486 BEAST_EXPECT(carolRate == STAmount(noIssue(), 1));
1487 // A higher rate is a worse quality: Carol's offer is the tip.
1488 BEAST_EXPECT(carolRate < aliceRate);
1489 }
1490
1491 void
1493 {
1494 using namespace jtx;
1495 auto const alice = Account{"alice"};
1496 auto const bob = Account{"bob"};
1497
1498 {
1499 testcase("Partially funded MPT/XRP input offer cannot be consumed for free");
1500
1501 Env env{*this, features};
1502 auto const gw = Account{"gw"};
1503
1504 env.fund(XRP(10'000), gw, alice, bob);
1505 env.close();
1506
1507 MPTTester const usd({.env = env, .issuer = gw, .holders = {alice}});
1508
1509 auto const aliceOfferSeq = env.seq(alice);
1510 env(offer(alice, usd(1), drops(1'000'000)));
1511 env.close();
1512
1513 auto const targetBalance = reserve(env, 2) + drops(999'999);
1514 auto const drain = env.balance(alice).value().xrp() - targetBalance.value().xrp() -
1515 env.current()->fees().base;
1516 env(pay(alice, gw, drops(drain)));
1517 env.close();
1518
1519 auto const aliceXRPBefore = env.balance(alice);
1520 auto const bobXRPBefore = env.balance(bob);
1521
1522 env(pay(gw, bob, drops(1'000'000)),
1523 Sendmax(usd(1)),
1524 Path(~XRP),
1525 Txflags(tfNoRippleDirect | tfPartialPayment),
1526 Ter(tecPATH_DRY));
1527 env.close();
1528
1529 // alice's offer sells 1,000,000 drops for usd(1) but she can fund
1530 // only 999,999. Filling the clipped remainder would require a
1531 // fractional usd (MPT) input that rounds down to zero, so without
1532 // the fix the taker could take the funded drops for free.
1533 // shouldRmSmallIncreasedQOffer() now treats the MPT input as
1534 // integral (like XRP) and removes the degraded offer, so the
1535 // payment goes dry. The removal happens only inside the crossing:
1536 // tecPATH_DRY discards everything but the fee, so the offer itself
1537 // stays in the ledger, unconsumed.
1538 BEAST_EXPECT(
1539 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq))) != nullptr);
1540 BEAST_EXPECT(env.balance(alice) == aliceXRPBefore);
1541 BEAST_EXPECT(env.balance(bob) == bobXRPBefore);
1542 }
1543
1544 {
1545 testcase("Partially funded MPT/IOU input offer cannot be consumed for free");
1546
1547 Env env{*this, features};
1548 auto const mptIssuer = Account{"mptIssuer"};
1549 auto const iouIssuer = Account{"iouIssuer"};
1550
1551 env.fund(XRP(10'000), mptIssuer, iouIssuer, alice, bob);
1552 env.close();
1553
1554 auto const eur = iouIssuer["EUR"];
1555 env.trust(eur(100), alice, bob);
1556 env(pay(iouIssuer, alice, eur(0.5)));
1557 env.close();
1558
1559 MPTTester const usd({.env = env, .issuer = mptIssuer, .holders = {alice}});
1560
1561 auto const aliceOfferSeq = env.seq(alice);
1562 env(offer(alice, usd(1), eur(1)));
1563 env.close();
1564
1565 auto const aliceEURBefore = env.balance(alice, eur);
1566 auto const bobEURBefore = env.balance(bob, eur);
1567
1568 env(pay(mptIssuer, bob, eur(1)),
1569 Sendmax(usd(1)),
1570 Path(~eur),
1571 Txflags(tfNoRippleDirect | tfPartialPayment),
1572 Ter(tecPATH_DRY));
1573 env.close();
1574
1575 // Same zero-input regression as the MPT/XRP case above, but with
1576 // an IOU (eur) output leg: the fractional usd (MPT) input rounds
1577 // to zero. The degraded offer is removed during crossing, the
1578 // payment goes dry, and tecPATH_DRY leaves the offer in the ledger.
1579 BEAST_EXPECT(
1580 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq))) != nullptr);
1581 BEAST_EXPECT(env.balance(alice, eur) == aliceEURBefore);
1582 BEAST_EXPECT(env.balance(bob, eur) == bobEURBefore);
1583 }
1584
1585 {
1586 testcase("Partially funded MPT/MPT input offer cannot be consumed for free");
1587
1588 Env env{*this, features};
1589 auto const issuerA = Account{"issuerA"};
1590 auto const issuerB = Account{"issuerB"};
1591
1592 env.fund(XRP(10'000), issuerA, issuerB, alice, bob);
1593 env.close();
1594
1595 MPTTester const usd({.env = env, .issuer = issuerA, .holders = {alice}});
1596 MPTTester const eur({.env = env, .issuer = issuerB, .holders = {alice, bob}});
1597
1598 env(pay(issuerB, alice, eur(999'999)));
1599 env.close();
1600
1601 auto const aliceOfferSeq = env.seq(alice);
1602 env(offer(alice, usd(1), eur(1'000'000)));
1603 env.close();
1604
1605 auto const aliceEURBefore = eur.getBalance(alice);
1606 auto const bobEURBefore = eur.getBalance(bob);
1607
1608 env(pay(issuerA, bob, eur(1'000'000)),
1609 Sendmax(usd(1)),
1610 Path(~eur),
1611 Txflags(tfNoRippleDirect | tfPartialPayment),
1612 Ter(tecPATH_DRY));
1613 env.close();
1614
1615 // Same zero-input regression as above, but with both legs MPT: the
1616 // fractional usd (MPT) input rounds to zero. The degraded offer is
1617 // removed during crossing, the payment goes dry, and tecPATH_DRY
1618 // leaves the offer in the ledger.
1619 BEAST_EXPECT(
1620 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq))) != nullptr);
1621 BEAST_EXPECT(env.balance(alice, eur) == eur(aliceEURBefore));
1622 BEAST_EXPECT(env.balance(bob, eur) == eur(bobEURBefore));
1623 }
1624
1625 {
1626 // The dry cases above never observe the degraded offer actually
1627 // being removed, because tecPATH_DRY rolls the removal back. Here a
1628 // second, fully funded offer lets the crossing succeed, so the
1629 // removal persists: alice's degraded offer is deleted from the
1630 // book (not taken for free) while carol's good offer fills.
1631 testcase(
1632 "Partially funded MPT input offer is removed, not consumed, "
1633 "when a funded offer crosses");
1634
1635 Env env{*this, features};
1636 auto const gw = Account{"gw"};
1637 auto const carol = Account{"carol"};
1638
1639 env.fund(XRP(10'000), gw, alice, carol, bob);
1640 env.close();
1641
1642 MPTTester const usd({.env = env, .issuer = gw, .holders = {alice, carol, bob}});
1643
1644 // alice's offer sells 1,000,000 drops for usd(1) but, as in the
1645 // dry cases above, she can fund only 999,999 drops, so filling the
1646 // clipped remainder would require a fractional usd (MPT) input that
1647 // rounds down to zero.
1648 auto const aliceOfferSeq = env.seq(alice);
1649 env(offer(alice, usd(1), drops(1'000'000)));
1650 env.close();
1651
1652 auto const targetBalance = reserve(env, 2) + drops(999'999);
1653 auto const drain = env.balance(alice).value().xrp() - targetBalance.value().xrp() -
1654 env.current()->fees().base;
1655 env(pay(alice, gw, drops(drain)));
1656 env.close();
1657
1658 // carol's same-quality offer is fully funded and provides the
1659 // legitimate side of the crossing.
1660 auto const carolOfferSeq = env.seq(carol);
1661 env(offer(carol, usd(1), drops(1'000'000)));
1662 env.close();
1663
1664 // bob needs usd to buy drops.
1665 env(pay(gw, bob, usd(2)));
1666 env.close();
1667
1668 auto const aliceOffer = keylet::offer(alice.id(), SeqProxy::rawSequence(aliceOfferSeq));
1669 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
1670 BEAST_EXPECT(env.le(aliceOffer) != nullptr);
1671 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1672
1673 auto const aliceXRPBefore = env.balance(alice);
1674 auto const bobXRPBefore = env.balance(bob);
1675
1676 // bob buys drops with usd, wanting more than carol alone supplies so
1677 // the crossing also reaches alice's offer. carol's offer fills;
1678 // alice's degraded offer is removed rather than taken for free, so
1679 // bob receives only carol's 1,000,000 drops and pays only usd(1).
1680 env(offer(bob, drops(2'000'000), usd(2), tfImmediateOrCancel));
1681 env.close();
1682
1683 BEAST_EXPECT(env.le(aliceOffer) == nullptr);
1684 BEAST_EXPECT(env.le(carolOffer) == nullptr);
1685 env.require(Offers(alice, 0), Offers(carol, 0), Offers(bob, 0));
1686
1687 // alice's offer was removed, not consumed: her balances are
1688 // unchanged and none of her funded 999'999 drops leaked to bob.
1689 BEAST_EXPECT(env.balance(alice) == aliceXRPBefore);
1690 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
1691 BEAST_EXPECT(env.balance(carol, usd) == usd(1));
1692 BEAST_EXPECT(env.balance(bob, usd) == usd(1));
1693 BEAST_EXPECT(
1694 env.balance(bob) == bobXRPBefore + drops(1'000'000) - env.current()->fees().base);
1695 }
1696 }
1697
1698 void
1700 {
1701 testcase("Book with destroyed MPT issuance as input");
1702
1703 using namespace jtx;
1704
1705 Account const issuer{"issuer"};
1706 Account const gw{"gw"};
1707 Account const alice{"alice"};
1708 Account const carol{"carol"};
1709
1710 Env env{*this, features};
1711 env.fund(XRP(10'000), issuer, gw, alice, carol);
1712 env.close();
1713
1714 auto const usd = gw["USD"];
1715 env.trust(usd(1'000), alice, carol);
1716 env(pay(gw, carol, usd(100)));
1717 env.close();
1718
1719 MPTTester bond({.env = env, .issuer = issuer, .holders = {carol}});
1720
1721 // carol buys musd. The offer doesn't add to OutstandingAmount, so the
1722 // issuer can still destroy the issuance while the offer is on the book.
1723 auto const carolOfferSeq = env.seq(carol);
1724 env(offer(carol, bond(10), usd(10)));
1725 env.close();
1726
1727 bond.destroy();
1728 env.close();
1729 BEAST_EXPECT(!env.le(keylet::mptokenIssuance(bond.issuanceID())));
1730
1731 auto const carolOffer = keylet::offer(carol.id(), SeqProxy::rawSequence(carolOfferSeq));
1732 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1733
1734 // The issuer is the strand source, so the musd -> usd BookStep is the
1735 // first step. It's built with no MaximumAmount cap because the
1736 // issuance is gone, then its check() rejects the missing issuance.
1737 env(pay(issuer, alice, usd(10)),
1738 Sendmax(bond(10)),
1739 Path(~usd),
1740 Txflags(tfNoRippleDirect),
1742 env.close();
1743
1744 BEAST_EXPECT(env.le(carolOffer) != nullptr);
1745 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
1746 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
1747 }
1748
1749 void
1751 {
1752 testcase("Insufficient Reserve");
1753
1754 // If an account places an offer and its balance
1755 // *before* the transaction began isn't high enough
1756 // to meet the reserve *after* the transaction runs,
1757 // then no offer should go on the books but if the
1758 // offer partially or fully crossed the tx succeeds.
1759
1760 using namespace jtx;
1761
1762 auto const gw = Account{"gateway"};
1763 auto const alice = Account{"alice"};
1764 auto const bob = Account{"bob"};
1765 auto const carol = Account{"carol"};
1766
1767 auto const xrpOffer = XRP(1'000);
1768
1769 // No crossing:
1770 {
1771 Env env{*this, features};
1772
1773 env.fund(XRP(1'000'000), gw);
1774
1775 auto const f = env.current()->fees().base;
1776 auto const r = reserve(env, 0);
1777
1778 env.fund(r + f, alice);
1779
1780 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
1781
1782 auto const usdOffer = usd(1'000);
1783
1784 env(pay(gw, alice, usdOffer), Ter(tesSUCCESS));
1785 env(offer(alice, xrpOffer, usdOffer), Ter(tecINSUF_RESERVE_OFFER));
1786
1787 env.require(Balance(alice, r - f), Owners(alice, 1));
1788 }
1789
1790 // Partial cross:
1791 {
1792 Env env{*this, features};
1793
1794 env.fund(XRP(1'000'000), gw);
1795
1796 auto const f = env.current()->fees().base;
1797 auto const r = reserve(env, 0);
1798
1799 env.fund(r + f, alice);
1800 env.fund(r + 2 * f + xrpOffer, bob);
1801
1802 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
1803
1804 auto const usdOffer = usd(1'000);
1805 auto const usdOffer2 = usd(500);
1806 auto const xrpOffer2 = XRP(500);
1807
1808 env(offer(bob, usdOffer2, xrpOffer2), Ter(tesSUCCESS));
1809
1810 env(pay(gw, alice, usdOffer), Ter(tesSUCCESS));
1811 env(offer(alice, xrpOffer, usdOffer), Ter(tesSUCCESS));
1812
1813 env.require(
1814 Balance(alice, r - f + xrpOffer2),
1815 Balance(alice, usdOffer2),
1816 Owners(alice, 1),
1817 Balance(bob, r + xrpOffer2),
1818 Balance(bob, usdOffer2),
1819 Owners(bob, 1));
1820 }
1821
1822 // Account has enough reserve as is, but not enough
1823 // if an offer were added. Attempt to sell MPTs to
1824 // buy XRP. If it fully crosses, we succeed.
1825 {
1826 Env env{*this, features};
1827
1828 env.fund(XRP(1'000'000), gw);
1829
1830 auto const f = env.current()->fees().base;
1831 auto const r = reserve(env, 0);
1832
1833 env.fund(r + f, alice);
1834
1835 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
1836
1837 auto const usdOffer = usd(1'000);
1838 auto const usdOffer2 = usd(500);
1839 auto const xrpOffer2 = XRP(500);
1840
1841 env.fund(r + f + xrpOffer, bob, carol);
1842 env(offer(bob, usdOffer2, xrpOffer2), Ter(tesSUCCESS));
1843 env(offer(carol, usdOffer, xrpOffer), Ter(tesSUCCESS));
1844
1845 env(pay(gw, alice, usdOffer), Ter(tesSUCCESS));
1846 env(offer(alice, xrpOffer, usdOffer), Ter(tesSUCCESS));
1847
1848 env.require(
1849 Balance(alice, r - f + xrpOffer),
1850 Balance(alice, usd(0)),
1851 Owners(alice, 1),
1852 Balance(bob, r + xrpOffer2),
1853 Balance(bob, usdOffer2),
1854 Owners(bob, 1),
1855 Balance(carol, r + xrpOffer2),
1856 Balance(carol, usdOffer2),
1857 Owners(carol, 2));
1858 }
1859 }
1860
1861 // Helper function that returns the Offers on an account.
1864 {
1866 forEachItem(*env.current(), account, [&result](SLE::ConstRef sle) {
1867 if (sle->getType() == ltOFFER)
1868 result.push_back(sle);
1869 });
1870 return result;
1871 }
1872
1873 void
1875 {
1876 testcase("Fill Modes");
1877
1878 using namespace jtx;
1879
1880 auto const startBalance = XRP(1'000'000);
1881 auto const gw = Account{"gateway"};
1882 auto const alice = Account{"alice"};
1883 auto const bob = Account{"bob"};
1884
1885 // Fill or Kill - unless we fully cross, just charge a fee and don't
1886 // place the offer on the books. But also clean up expired offers
1887 // that are discovered along the way.
1888 //
1889 {
1890 Env env{*this, features};
1891
1892 auto const f = env.current()->fees().base;
1893
1894 env.fund(startBalance, gw, alice, bob);
1895
1896 MPTTester musd({.env = env, .issuer = gw});
1897 MPT const usd = musd["USD"];
1898
1899 // bob creates an offer that expires before the next ledger close.
1900 env(offer(bob, usd(500), XRP(500)),
1901 Json(sfExpiration.fieldName, lastClose(env) + 1),
1902 Ter(tesSUCCESS));
1903
1904 // The offer expires (it's not removed yet).
1905 env.close();
1906 env.require(Owners(bob, 1), Offers(bob, 1));
1907
1908 // bob creates the offer that will be crossed.
1909 env(offer(bob, usd(500), XRP(500)), Ter(tesSUCCESS));
1910 env.close();
1911 env.require(Owners(bob, 2), Offers(bob, 2));
1912
1913 musd.authorize({.account = alice});
1914 env(pay(gw, alice, usd(1'000)), Ter(tesSUCCESS));
1915
1916 // Order that can't be filled but will remove bob's expired offer:
1917 env(offer(alice, XRP(1'000), usd(1'000)), Txflags(tfFillOrKill), Ter(tecKILLED));
1918
1919 env.require(
1920 Balance(alice, startBalance - (f * 2)),
1921 Balance(alice, usd(1'000)),
1922 Owners(alice, 1),
1923 Offers(alice, 0),
1924 Balance(bob, startBalance - (f * 2)),
1925 Balance(bob, usd(kNone)),
1926 Owners(bob, 1),
1927 Offers(bob, 1));
1928
1929 // Order that can be filled
1930 env(offer(alice, XRP(500), usd(500)), Txflags(tfFillOrKill), Ter(tesSUCCESS));
1931
1932 env.require(
1933 Balance(alice, startBalance - (f * 3) + XRP(500)),
1934 Balance(alice, usd(500)),
1935 Owners(alice, 1),
1936 Offers(alice, 0),
1937 Balance(bob, startBalance - (f * 2) - XRP(500)),
1938 Balance(bob, usd(500)),
1939 Owners(bob, 1),
1940 Offers(bob, 0));
1941 }
1942
1943 // Immediate or Cancel - cross as much as possible
1944 // and add nothing on the books:
1945 {
1946 Env env{*this, features};
1947
1948 auto const f = env.current()->fees().base;
1949
1950 env.fund(startBalance, gw, alice, bob);
1951
1952 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
1953
1954 env(pay(gw, alice, usd(1'000)), Ter(tesSUCCESS));
1955
1956 // No cross:
1957 {
1958 env(offer(alice, XRP(1'000), usd(1000)),
1959 Txflags(tfImmediateOrCancel),
1960 Ter(tecKILLED));
1961 }
1962
1963 env.require(
1964 Balance(alice, startBalance - f - f),
1965 Balance(alice, usd(1000)),
1966 Owners(alice, 1),
1967 Offers(alice, 0));
1968
1969 // Partially cross:
1970 env(offer(bob, usd(50), XRP(50)), Ter(tesSUCCESS));
1971 env(offer(alice, XRP(1000), usd(1000)), Txflags(tfImmediateOrCancel), Ter(tesSUCCESS));
1972
1973 env.require(
1974 Balance(alice, startBalance - f - f - f + XRP(50)),
1975 Balance(alice, usd(950)),
1976 Owners(alice, 1),
1977 Offers(alice, 0),
1978 Balance(bob, startBalance - f - XRP(50)),
1979 Balance(bob, usd(50)),
1980 Owners(bob, 1),
1981 Offers(bob, 0));
1982
1983 // Fully cross:
1984 env(offer(bob, usd(50), XRP(50)), Ter(tesSUCCESS));
1985 env(offer(alice, XRP(50), usd(50)), Txflags(tfImmediateOrCancel), Ter(tesSUCCESS));
1986
1987 env.require(
1988 Balance(alice, startBalance - f - f - f - f + XRP(100)),
1989 Balance(alice, usd(900)),
1990 Owners(alice, 1),
1991 Offers(alice, 0),
1992 Balance(bob, startBalance - f - f - XRP(100)),
1993 Balance(bob, usd(100)),
1994 Owners(bob, 1),
1995 Offers(bob, 0));
1996 }
1997
1998 // tfPassive -- place the offer without crossing it.
1999 {
2000 Env env(*this, features);
2001
2002 env.fund(startBalance, gw, alice, bob);
2003 env.close();
2004
2005 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {bob}});
2006
2007 env(pay(gw, bob, usd(1'000)));
2008 env.close();
2009
2010 env(offer(alice, usd(1'000), XRP(2'000)));
2011 env.close();
2012
2013 auto const aliceOffers = offersOnAccount(env, alice);
2014 BEAST_EXPECT(aliceOffers.size() == 1);
2015 for (auto const& offerPtr : aliceOffers)
2016 {
2017 auto const& offer = *offerPtr;
2018 BEAST_EXPECT(offer[sfTakerGets] == XRP(2'000));
2019 BEAST_EXPECT(offer[sfTakerPays] == usd(1'000));
2020 }
2021
2022 // bob creates a passive offer that could cross alice's.
2023 // bob's offer should stay in the ledger.
2024 env(offer(bob, XRP(2'000), usd(1'000), tfPassive));
2025 env.close();
2026 env.require(Offers(alice, 1));
2027
2028 auto const bobOffers = offersOnAccount(env, bob);
2029 BEAST_EXPECT(bobOffers.size() == 1);
2030 for (auto const& offerPtr : bobOffers)
2031 {
2032 auto const& offer = *offerPtr;
2033 BEAST_EXPECT(offer[sfTakerGets] == usd(1'000));
2034 BEAST_EXPECT(offer[sfTakerPays] == XRP(2'000));
2035 }
2036
2037 // It should be possible for gw to cross both of those offers.
2038 env(offer(gw, XRP(2'000), usd(1'000)));
2039 env.close();
2040 env.require(Offers(alice, 0));
2041 env.require(Offers(gw, 0));
2042 env.require(Offers(bob, 1));
2043
2044 env(offer(gw, usd(1'000), XRP(2'000)));
2045 env.close();
2046 env.require(Offers(bob, 0));
2047 env.require(Offers(gw, 0));
2048 }
2049
2050 // tfPassive -- cross only offers of better quality.
2051 {
2052 Env env(*this, features);
2053
2054 env.fund(startBalance, gw, "alice", "bob");
2055 env.close();
2056
2057 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {bob}});
2058
2059 env(pay(gw, "bob", usd(10'000)));
2060 env(offer("alice", usd(5'000), XRP(1'001)));
2061 env.close();
2062
2063 env(offer("alice", usd(5'000), XRP(1'000)));
2064 env.close();
2065
2066 auto const aliceOffers = offersOnAccount(env, "alice");
2067 BEAST_EXPECT(aliceOffers.size() == 2);
2068
2069 // bob creates a passive offer. That offer should cross one
2070 // of alice's (the one with better quality) and leave alice's
2071 // other offer untouched.
2072 env(offer("bob", XRP(2'000), usd(10'000), tfPassive));
2073 env.close();
2074 env.require(Offers("alice", 1));
2075
2076 auto const bobOffers = offersOnAccount(env, "bob");
2077 BEAST_EXPECT(bobOffers.size() == 1);
2078 for (auto const& offerPtr : bobOffers)
2079 {
2080 auto const& offer = *offerPtr;
2081 BEAST_EXPECT(offer[sfTakerGets] == usd(4'995));
2082 BEAST_EXPECT(offer[sfTakerPays] == XRP(999));
2083 }
2084 }
2085 }
2086
2087 void
2089 {
2090 testcase("MPT AMM limitQuality checks rounded integral output");
2091
2092 using namespace jtx;
2093
2094 Account const gw{"gateway"};
2095 Account const alice{"alice"};
2096 Account const bob{"bob"};
2097
2098 // IOC used to reject the AMM strand with tecKILLED. The continuous
2099 // limitQuality target is about 32.88 MPT; rounding to nearest requested
2100 // 33 MPT and made the realized AMM quality miss Bob's limit. The
2101 // discrete fallback takes the largest satisfying integer output: 32.
2102 {
2103 Env env{*this, features};
2104
2105 env.fund(XRP(10'000), gw, alice, bob);
2106 env.close();
2107
2108 MPTTester const btc({
2109 .env = env,
2110 .issuer = gw,
2111 .holders = {alice, bob},
2112 .pay = 100'000,
2113 .flags = kMptDexFlags,
2114 });
2115 AMM const amm(env, alice, XRP(100), btc(1'000));
2116
2117 auto const bobBTCBefore = btc.getBalance(bob);
2118 auto const [xrpBefore, btcBefore, lpBefore] = amm.balances();
2119
2120 env(offer(bob, btc(100), drops(10'340'000)), Txflags(tfImmediateOrCancel));
2121 env.close();
2122
2123 auto const [xrpAfter, btcAfter, lpAfter] = amm.balances();
2124 BEAST_EXPECT(btc.getBalance(bob) == bobBTCBefore + 32);
2125 BEAST_EXPECT(xrpAfter > xrpBefore);
2126 BEAST_EXPECT(btcAfter < btcBefore);
2127 BEAST_EXPECT(lpAfter == lpBefore);
2128 BEAST_EXPECT(expectOffers(env, bob, 0));
2129 }
2130
2131 // A standard OfferCreate at the same limit used to bypass the AMM and
2132 // rest unchanged on the book. It should now take the largest
2133 // satisfying 32-MPT AMM fill first, then leave only the remainder on
2134 // the book.
2135 {
2136 Env env{*this, features};
2137
2138 env.fund(XRP(10'000), gw, alice, bob);
2139 env.close();
2140
2141 MPTTester const btc({
2142 .env = env,
2143 .issuer = gw,
2144 .holders = {alice, bob},
2145 .pay = 100'000,
2146 .flags = kMptDexFlags,
2147 });
2148 AMM const amm(env, alice, XRP(100), btc(1'000));
2149
2150 auto const bobBTCBefore = btc.getBalance(bob);
2151 auto const [xrpBefore, btcBefore, lpBefore] = amm.balances();
2152
2153 env(offer(bob, btc(100), drops(10'340'000)));
2154 env.close();
2155
2156 auto const [xrpAfter, btcAfter, lpAfter] = amm.balances();
2157 BEAST_EXPECT(btc.getBalance(bob) == bobBTCBefore + 32);
2158 BEAST_EXPECT(xrpAfter > xrpBefore);
2159 BEAST_EXPECT(btcAfter < btcBefore);
2160 BEAST_EXPECT(lpAfter == lpBefore);
2161 BEAST_EXPECT(expectOffers(env, bob, 1));
2162
2163 auto const bobOffers = offersOnAccount(env, bob);
2164 if (BEAST_EXPECT(bobOffers.size() == 1))
2165 {
2166 BEAST_EXPECT((*bobOffers[0])[sfTakerPays] != btc(100));
2167 BEAST_EXPECT((*bobOffers[0])[sfTakerGets] != drops(10'340'000));
2168 }
2169 }
2170
2171 // Mirror the IOC case with the integral output flipped from MPT units
2172 // to XRP drops. The same continuous target (~32.88) used to round up
2173 // to 33 drops and miss limitQuality; the discrete fallback allows the
2174 // largest satisfying 32-drop AMM fill.
2175 {
2176 Env env{*this, features};
2177
2178 env.fund(XRP(10'000), gw, alice, bob);
2179 env.close();
2180
2181 MPTTester const btc({
2182 .env = env,
2183 .issuer = gw,
2184 .holders = {alice, bob},
2185 .pay = 200'000'000,
2186 .flags = kMptDexFlags,
2187 });
2188 AMM const amm(env, alice, drops(1'000), btc(100'000'000));
2189
2190 auto const bobXRPBefore = env.balance(bob, XRP);
2191 auto const baseFee = env.current()->fees().base;
2192 auto const [xrpBefore, btcBefore, lpBefore] = amm.balances();
2193
2194 env(offer(bob, drops(100), btc(10'340'000)), Txflags(tfImmediateOrCancel));
2195 env.close();
2196
2197 auto const [xrpAfter, btcAfter, lpAfter] = amm.balances();
2198 env.require(Balance(bob, bobXRPBefore + drops(32) - baseFee));
2199 BEAST_EXPECT(xrpAfter < xrpBefore);
2200 BEAST_EXPECT(btcAfter > btcBefore);
2201 BEAST_EXPECT(lpAfter == lpBefore);
2202 BEAST_EXPECT(expectOffers(env, bob, 0));
2203 }
2204
2205 // Mirror the standard OfferCreate case as well. It should consume the
2206 // largest satisfying 32-drop AMM fill before leaving only the remainder
2207 // on the book.
2208 {
2209 Env env{*this, features};
2210
2211 env.fund(XRP(10'000), gw, alice, bob);
2212 env.close();
2213
2214 MPTTester const btc({
2215 .env = env,
2216 .issuer = gw,
2217 .holders = {alice, bob},
2218 .pay = 200'000'000,
2219 .flags = kMptDexFlags,
2220 });
2221 AMM const amm(env, alice, drops(1'000), btc(100'000'000));
2222
2223 auto const bobXRPBefore = env.balance(bob, XRP);
2224 auto const baseFee = env.current()->fees().base;
2225 auto const [xrpBefore, btcBefore, lpBefore] = amm.balances();
2226
2227 env(offer(bob, drops(100), btc(10'340'000)));
2228 env.close();
2229
2230 auto const [xrpAfter, btcAfter, lpAfter] = amm.balances();
2231 env.require(Balance(bob, bobXRPBefore + drops(32) - baseFee));
2232 BEAST_EXPECT(xrpAfter < xrpBefore);
2233 BEAST_EXPECT(btcAfter > btcBefore);
2234 BEAST_EXPECT(lpAfter == lpBefore);
2235 BEAST_EXPECT(expectOffers(env, bob, 1));
2236
2237 auto const bobOffers = offersOnAccount(env, bob);
2238 if (BEAST_EXPECT(bobOffers.size() == 1))
2239 {
2240 BEAST_EXPECT((*bobOffers[0])[sfTakerPays] != drops(100));
2241 BEAST_EXPECT((*bobOffers[0])[sfTakerGets] != btc(10'340'000));
2242 }
2243 }
2244 }
2245
2246 void
2248 {
2249 testcase("Malformed Detection");
2250
2251 using namespace jtx;
2252
2253 auto const startBalance = XRP(1'000'000);
2254 auto const gw = Account{"gateway"};
2255 auto const alice = Account{"alice"};
2256
2257 Env env{*this, features};
2258
2259 env.fund(startBalance, gw, alice);
2260
2261 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
2262
2263 // Sell and buy the same asset
2264 {
2265 // Alice tries an MPT to MPT order:
2266 env(pay(gw, alice, usd(1'000)), Ter(tesSUCCESS));
2267 env(offer(alice, usd(1'000), usd(1'000)), Ter(temREDUNDANT));
2268 env.require(Owners(alice, 1), Offers(alice, 0));
2269 }
2270
2271 // Offers with negative amounts
2272 {
2273 env(offer(alice, -usd(1'000), XRP(1'000)), Ter(temBAD_AMOUNT));
2274 env.require(Owners(alice, 1), Offers(alice, 0));
2275 }
2276
2277 // Bad MPT
2278 {
2279 auto const bad = MPT(badMPT());
2280
2281 env(offer(alice, XRP(1'000), bad(1'000)), Ter(temBAD_CURRENCY));
2282 env.require(Owners(alice, 1), Offers(alice, 0));
2283 }
2284 }
2285
2286 void
2288 {
2289 testcase("Offer Expiration");
2290
2291 using namespace jtx;
2292
2293 auto const gw = Account{"gateway"};
2294 auto const alice = Account{"alice"};
2295 auto const bob = Account{"bob"};
2296
2297 auto const startBalance = XRP(1'000'000);
2298 auto const xrpOffer = XRP(1'000);
2299
2300 Env env{*this, features};
2301
2302 env.fund(startBalance, gw, alice, bob);
2303 env.close();
2304
2305 auto const f = env.current()->fees().base;
2306
2307 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
2308 auto const usdOffer = usd(1'000);
2309
2310 env(pay(gw, alice, usdOffer), Ter(tesSUCCESS));
2311 env.close();
2312 env.require(
2313 Balance(alice, startBalance - f),
2314 Balance(alice, usdOffer),
2315 Offers(alice, 0),
2316 Owners(alice, 1));
2317
2318 // Place an offer that should have already expired.
2319 env(offer(alice, xrpOffer, usdOffer),
2320 Json(sfExpiration.fieldName, lastClose(env)),
2321 Ter(TER{tecEXPIRED}));
2322
2323 env.require(
2324 Balance(alice, startBalance - f - f),
2325 Balance(alice, usdOffer),
2326 Offers(alice, 0),
2327 Owners(alice, 1));
2328 env.close();
2329
2330 // Add an offer that expires before the next ledger close
2331 env(offer(alice, xrpOffer, usdOffer),
2332 Json(sfExpiration.fieldName, lastClose(env) + 1),
2333 Ter(tesSUCCESS));
2334 env.require(
2335 Balance(alice, startBalance - f - f - f),
2336 Balance(alice, usdOffer),
2337 Offers(alice, 1),
2338 Owners(alice, 2));
2339
2340 // The offer expires (it's not removed yet)
2341 env.close();
2342 env.require(
2343 Balance(alice, startBalance - f - f - f),
2344 Balance(alice, usdOffer),
2345 Offers(alice, 1),
2346 Owners(alice, 2));
2347
2348 // Add offer - the expired offer is removed
2349 env(offer(bob, usdOffer, xrpOffer), Ter(tesSUCCESS));
2350
2351 env.require(
2352 Balance(alice, startBalance - f - f - f),
2353 Balance(alice, usdOffer),
2354 Offers(alice, 0),
2355 Owners(alice, 1),
2356 Balance(bob, startBalance - f),
2357 Balance(bob, usd(kNone)),
2358 Offers(bob, 1),
2359 Owners(bob, 1));
2360 }
2361
2362 void
2364 {
2365 testcase("Unfunded Crossing");
2366
2367 using namespace jtx;
2368
2369 auto const gw = Account{"gateway"};
2370
2371 auto const xrpOffer = XRP(1'000);
2372
2373 Env env{*this, features};
2374
2375 env.fund(XRP(1'000'000), gw);
2376
2377 // The fee that's charged for transactions
2378 auto const f = env.current()->fees().base;
2379
2380 // Account is at the reserve, and will dip below once
2381 // fees are subtracted.
2382 env.fund(reserve(env, 0), "alice");
2383 MPT const usd = MPTTester({.env = env, .issuer = gw});
2384 auto const usdOffer = usd(1'000);
2385 env(offer("alice", usdOffer, xrpOffer), Ter(tecUNFUNDED_OFFER));
2386 env.require(Balance("alice", reserve(env, 0) - f), Owners("alice", 0));
2387
2388 // Account has just enough for the reserve and the
2389 // fee.
2390 env.fund(reserve(env, 0) + f, "bob");
2391 env(offer("bob", usdOffer, xrpOffer), Ter(tecUNFUNDED_OFFER));
2392 env.require(Balance("bob", reserve(env, 0)), Owners("bob", 0));
2393
2394 // Account has enough for the reserve, the fee and
2395 // the offer, and a bit more, but not enough for the
2396 // reserve after the offer is placed.
2397 env.fund(reserve(env, 0) + f + XRP(1), "carol");
2398 env(offer("carol", usdOffer, xrpOffer), Ter(tecINSUF_RESERVE_OFFER));
2399 env.require(Balance("carol", reserve(env, 0) + XRP(1)), Owners("carol", 0));
2400
2401 // Account has enough for the reserve plus one
2402 // offer, and the fee.
2403 env.fund(reserve(env, 1) + f, "dan");
2404 env(offer("dan", usdOffer, xrpOffer), Ter(tesSUCCESS));
2405 env.require(Balance("dan", reserve(env, 1)), Owners("dan", 1));
2406
2407 // Account has enough for the reserve plus one
2408 // offer, the fee and the entire offer amount.
2409 env.fund(reserve(env, 1) + f + xrpOffer, "eve");
2410 env(offer("eve", usdOffer, xrpOffer), Ter(tesSUCCESS));
2411 env.require(Balance("eve", reserve(env, 1) + xrpOffer), Owners("eve", 1));
2412 }
2413
2414 void
2415 testSelfCross(bool usePartner, FeatureBitset features)
2416 {
2417 testcase(std::string("Self-crossing") + (usePartner ? ", with partner account" : ""));
2418
2419 using namespace jtx;
2420 auto const gw = Account{"gateway"};
2421 auto const partner = Account{"partner"};
2422
2423 auto const test = [&](auto&& issue1, auto&& issue2) {
2424 Env env{*this, features};
2425 env.close();
2426
2427 env.fund(XRP(10'000), gw);
2428 auto const usd = issue1({.env = env, .token = "USD", .issuer = gw});
2429 auto const btc = issue2({.env = env, .token = "BTC", .issuer = gw});
2430 using TUsd = std::decay_t<decltype(usd)>;
2431 using TBtc = std::decay_t<decltype(btc)>;
2432 if (usePartner)
2433 {
2434 env.fund(XRP(10'000), partner);
2435 if constexpr (std::is_same_v<TUsd, IOU>)
2436 {
2437 env(trust(partner, usd(100)));
2438 }
2439 else
2440 {
2441 MPTTester musd(env, gw, usd);
2442 musd.authorize({.account = partner});
2443 }
2444 if constexpr (std::is_same_v<TBtc, IOU>)
2445 {
2446 env(trust(partner, btc(500)));
2447 }
2448 else
2449 {
2450 MPTTester mbtc(env, gw, btc);
2451 mbtc.authorize({.account = partner});
2452 }
2453 env(pay(gw, partner, usd(100)));
2454 env(pay(gw, partner, btc(500)));
2455 }
2456 auto const& accountToTest = usePartner ? partner : gw;
2457
2458 env.close();
2459 env.require(Offers(accountToTest, 0));
2460
2461 // PART 1:
2462 // we will make two offers that can be used to bridge BTC to USD
2463 // through XRP
2464 env(offer(accountToTest, btc(250), XRP(1'000)));
2465 env.require(Offers(accountToTest, 1));
2466
2467 // validate that the book now shows a BTC for XRP offer
2468 BEAST_EXPECT(isOffer(env, accountToTest, btc(250), XRP(1'000)));
2469
2470 auto const secondLegSeq = env.seq(accountToTest);
2471 env(offer(accountToTest, XRP(1'000), usd(50)));
2472 env.require(Offers(accountToTest, 2));
2473
2474 // validate that the book also shows a XRP for USD offer
2475 BEAST_EXPECT(isOffer(env, accountToTest, XRP(1'000), usd(50)));
2476
2477 // now make an offer that will cross and auto-bridge, meaning
2478 // the outstanding offers will be taken leaving us with none
2479 env(offer(accountToTest, usd(50), btc(250)));
2480
2481 auto jrr = getBookOffers(env, usd, btc);
2482 BEAST_EXPECT(jrr[jss::offers].isArray());
2483 BEAST_EXPECT(jrr[jss::offers].size() == 0);
2484
2485 jrr = getBookOffers(env, btc, XRP);
2486 BEAST_EXPECT(jrr[jss::offers].isArray());
2487 BEAST_EXPECT(jrr[jss::offers].size() == 0);
2488
2489 // At this point, all offers are expected to be consumed.
2490 {
2491 auto const acctOffers = offersOnAccount(env, accountToTest);
2492
2493 // No stale offers
2494 BEAST_EXPECT(acctOffers.empty());
2495 for (auto const& offerPtr : acctOffers)
2496 {
2497 auto const& offer = *offerPtr;
2498 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
2499 BEAST_EXPECT(offer[sfTakerGets] == usd(0));
2500 BEAST_EXPECT(offer[sfTakerPays] == XRP(0));
2501 }
2502 }
2503
2504 // cancel that lingering second offer so that it doesn't interfere
2505 // with the next set of offers we test. This will not be needed once
2506 // the bridging bug is fixed
2507 env(offerCancel(accountToTest, secondLegSeq));
2508 env.require(Offers(accountToTest, 0));
2509
2510 // PART 2:
2511 // simple direct crossing BTC to USD and then USD to BTC which
2512 // causes the first offer to be replaced
2513 env(offer(accountToTest, btc(250), usd(50)));
2514 env.require(Offers(accountToTest, 1));
2515
2516 // validate that the book shows one BTC for USD offer and no USD for
2517 // BTC offers
2518 BEAST_EXPECT(isOffer(env, accountToTest, btc(250), usd(50)));
2519
2520 jrr = getBookOffers(env, usd, btc);
2521 BEAST_EXPECT(jrr[jss::offers].isArray());
2522 BEAST_EXPECT(jrr[jss::offers].size() == 0);
2523
2524 // this second offer would self-cross directly, so it causes the
2525 // first offer by the same owner/taker to be removed
2526 env(offer(accountToTest, usd(50), btc(250)));
2527 env.require(Offers(accountToTest, 1));
2528
2529 // validate that we now have just the second offer...the first
2530 // was removed
2531 jrr = getBookOffers(env, btc, usd);
2532 BEAST_EXPECT(jrr[jss::offers].isArray());
2533 BEAST_EXPECT(jrr[jss::offers].size() == 0);
2534
2535 BEAST_EXPECT(isOffer(env, accountToTest, usd(50), btc(250)));
2536 };
2538 }
2539
2540 void
2542 {
2543 // This test creates an offer test for negative balance
2544 // with transfer fees and miniscule funds.
2545 testcase("Negative Balance");
2546
2547 using namespace jtx;
2548 FeatureBitset const localFeatures = features | fixReducedOffersV2;
2549
2550 Env env{*this, localFeatures};
2551
2552 auto const gw = Account{"gateway"};
2553 auto const alice = Account{"alice"};
2554 auto const bob = Account{"bob"};
2555
2556 // these *interesting* amounts were taken
2557 // from the original JS test that was ported here
2558 auto const gwInitialBalance = drops(1'149'999'730);
2559 auto const aliceInitialBalance = drops(499'946'999'680);
2560 auto const bobInitialBalance = drops(10'199'999'920);
2561
2562 env.fund(gwInitialBalance, gw);
2563 env.fund(aliceInitialBalance, alice);
2564 env.fund(bobInitialBalance, bob);
2565
2566 MPTTester const musd(
2567 {.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 5'000});
2568 MPT const usd = musd;
2569 auto const smallAmount = STAmount{usd, 1};
2570
2571 env(pay(gw, alice, usd(50)));
2572 env(pay(gw, bob, smallAmount));
2573
2574 env(offer(alice, usd(50), XRP(150'000)));
2575
2576 // unfund the offer
2577 env(pay(alice, gw, usd(50)));
2578
2579 // verify balances
2580 auto jrr = ledgerEntryMPT(env, alice, usd);
2581 // this represents 0 since MPTAmount is a default field
2582 BEAST_EXPECT(!jrr[jss::node].isMember(sfMPTAmount.fieldName));
2583
2584 jrr = ledgerEntryMPT(env, bob, usd);
2585 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1");
2586
2587 // create crossing offer
2588 std::uint32_t const bobOfferSeq = env.seq(bob);
2589 env(offer(bob, XRP(2000), usd(1)));
2590
2591 // With the rounding introduced by fixReducedOffersV2, bob's
2592 // offer does not cross alice's offer and goes straight into
2593 // the ledger.
2594 jrr = ledgerEntryMPT(env, bob, usd);
2595 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1");
2596
2597 json::Value const bobOffer = ledgerEntryOffer(env, bob, bobOfferSeq)[jss::node];
2598 BEAST_EXPECT(bobOffer[sfTakerGets.jsonName][jss::value] == "1");
2599 BEAST_EXPECT(bobOffer[sfTakerPays.jsonName] == "2000000000");
2600 }
2601
2602 void
2603 testOfferCrossWithXRP(bool reverseOrder, FeatureBitset features)
2604 {
2605 testcase(
2606 std::string("Offer Crossing with XRP, ") + (reverseOrder ? "Reverse" : "Normal") +
2607 " order");
2608
2609 using namespace jtx;
2610
2611 Env env{*this, features};
2612
2613 auto const gw = Account{"gateway"};
2614 auto const alice = Account{"alice"};
2615 auto const bob = Account{"bob"};
2616
2617 env.fund(XRP(10'000), gw, alice, bob);
2618
2619 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
2620
2621 env(pay(gw, alice, usd(500)));
2622
2623 if (reverseOrder)
2624 env(offer(bob, usd(1), XRP(4'000)));
2625
2626 env(offer(alice, XRP(150'000), usd(50)));
2627
2628 if (!reverseOrder)
2629 env(offer(bob, usd(1), XRP(4000)));
2630
2631 // Existing offer pays better than this wants.
2632 // Fully consume existing offer.
2633 // Pay 1 USD, get 4000 XRP.
2634
2635 auto jrr = ledgerEntryMPT(env, bob, usd);
2636 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1");
2637 jrr = ledgerEntryRoot(env, bob);
2638 BEAST_EXPECT(
2639 jrr[jss::node][sfBalance.fieldName] ==
2640 to_string(
2641 (XRP(10000) - XRP(reverseOrder ? 4000 : 3000) - env.current()->fees().base * 2)
2642 .xrp()));
2643
2644 jrr = ledgerEntryMPT(env, alice, usd);
2645 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "499");
2646 jrr = ledgerEntryRoot(env, alice);
2647 BEAST_EXPECT(
2648 jrr[jss::node][sfBalance.fieldName] ==
2649 to_string(
2650 (XRP(10000) + XRP(reverseOrder ? 4000 : 3000) - env.current()->fees().base * 2)
2651 .xrp()));
2652 }
2653
2654 void
2656 {
2657 testcase("Offer Crossing with Limit Override");
2658
2659 using namespace jtx;
2660
2661 Env env{*this, features};
2662
2663 auto const gw = Account{"gateway"};
2664 auto const alice = Account{"alice"};
2665 auto const bob = Account{"bob"};
2666
2667 env.fund(XRP(100000), gw, alice, bob);
2668
2669 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
2670
2671 env(pay(gw, alice, usd(500)));
2672
2673 env(offer(alice, XRP(150'000), usd(50)));
2674 env(offer(bob, usd(1), XRP(3'000)));
2675
2676 auto jrr = ledgerEntryMPT(env, bob, usd);
2677 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1");
2678 jrr = ledgerEntryRoot(env, bob);
2679 BEAST_EXPECT(
2680 jrr[jss::node][sfBalance.fieldName] ==
2681 to_string((XRP(100'000) - XRP(3'000) - env.current()->fees().base * 1).xrp()));
2682
2683 jrr = ledgerEntryMPT(env, alice, usd);
2684 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "499");
2685 jrr = ledgerEntryRoot(env, alice);
2686 BEAST_EXPECT(
2687 jrr[jss::node][sfBalance.fieldName] ==
2688 to_string((XRP(100'000) + XRP(3'000) - env.current()->fees().base * 2).xrp()));
2689 }
2690
2691 void
2693 {
2694 testcase("Offer Accept then Cancel.");
2695
2696 using namespace jtx;
2697
2698 Env env{*this, features};
2699
2700 MPT const usd = MPTTester({.env = env, .issuer = env.master});
2701
2702 auto const nextOfferSeq = env.seq(env.master);
2703 env(offer(env.master, XRP(500), usd(100)));
2704 env.close();
2705
2706 env(offerCancel(env.master, nextOfferSeq));
2707 BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2);
2708
2709 // ledger_accept, call twice and verify no odd behavior
2710 env.close();
2711 env.close();
2712 BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2);
2713 }
2714
2715 void
2717 {
2718 testcase("Currency Conversion: Entire Offer");
2719
2720 using namespace jtx;
2721
2722 Env env{*this, features};
2723
2724 auto const gw = Account{"gateway"};
2725 auto const alice = Account{"alice"};
2726 auto const bob = Account{"bob"};
2727
2728 env.fund(XRP(10'000), gw, alice, bob);
2729 env.require(Owners(bob, 0));
2730
2731 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
2732
2733 env.require(Owners(alice, 1), Owners(bob, 1));
2734
2735 env(pay(gw, alice, usd(100)));
2736 auto const bobOfferSeq = env.seq(bob);
2737 env(offer(bob, usd(100), XRP(500)));
2738
2739 env.require(Owners(alice, 1), Owners(bob, 2));
2740 auto jro = ledgerEntryOffer(env, bob, bobOfferSeq);
2741 BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(500).value().getText());
2742 BEAST_EXPECT(
2743 jro[jss::node][jss::TakerPays] == usd(100).value().getJson(JsonOptions::Values::None));
2744
2745 env(pay(alice, alice, XRP(500)), Sendmax(usd(100)));
2746
2747 auto jrr = ledgerEntryMPT(env, alice, usd);
2748 BEAST_EXPECT(!jrr[jss::node].isMember(sfMPTAmount.fieldName));
2749 jrr = ledgerEntryRoot(env, alice);
2750 BEAST_EXPECT(
2751 jrr[jss::node][sfBalance.fieldName] ==
2752 to_string((XRP(10'000) + XRP(500) - env.current()->fees().base * 2).xrp()));
2753
2754 jrr = ledgerEntryMPT(env, bob, usd);
2755 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100");
2756
2757 jro = ledgerEntryOffer(env, bob, bobOfferSeq);
2758 BEAST_EXPECT(jro[jss::error] == "entryNotFound");
2759 BEAST_EXPECT(jro[jss::error_code] == RpcEntryNotFound);
2760 BEAST_EXPECT(jro[jss::error_message] == "Entry not found.");
2761
2762 env.require(Owners(alice, 1), Owners(bob, 1));
2763 }
2764
2765 void
2767 {
2768 testcase("Currency Conversion: Offerer Into Debt");
2769
2770 using namespace jtx;
2771 auto const alice = Account{"alice"};
2772 auto const bob = Account{"bob"};
2773 auto const carol = Account{"carol"};
2774
2775 auto const test = [&](auto&& issue1, auto&& issue2, auto&& issue3) {
2776 Env env{*this, features};
2777
2778 env.fund(XRP(10'000), alice, bob, carol);
2779
2780 auto const usd =
2781 issue1({.env = env, .token = "USD", .issuer = alice, .holders = {bob}});
2782 auto const eurc =
2783 issue2({.env = env, .token = "EUC", .issuer = carol, .holders = {alice}});
2784 auto const eurb =
2785 issue3({.env = env, .token = "EUB", .issuer = bob, .holders = {carol}});
2786
2787 auto const bobOfferSeq = env.seq(bob);
2788 env(offer(bob, usd(50), eurc(200)), Ter(tecUNFUNDED_OFFER));
2789
2790 env(offer(alice, eurc(200), usd(50)));
2791
2792 auto jro = ledgerEntryOffer(env, bob, bobOfferSeq);
2793 BEAST_EXPECT(jro[jss::error] == "entryNotFound");
2794 BEAST_EXPECT(jro[jss::error_code] == RpcEntryNotFound);
2795 BEAST_EXPECT(jro[jss::error_message] == "Entry not found.");
2796 };
2798 }
2799
2800 void
2802 {
2803 testcase("Currency Conversion: In Parts");
2804
2805 using namespace jtx;
2806
2807 Env env{*this, features};
2808
2809 auto const gw = Account{"gateway"};
2810 auto const alice = Account{"alice"};
2811 auto const bob = Account{"bob"};
2812
2813 env.fund(XRP(10'000), gw, alice, bob);
2814
2815 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
2816
2817 env(pay(gw, alice, usd(200)));
2818
2819 auto const bobOfferSeq = env.seq(bob);
2820 env(offer(bob, usd(100), XRP(500)));
2821
2822 env(pay(alice, alice, XRP(200)), Sendmax(usd(100)));
2823
2824 // The previous payment reduced the remaining offer amount by 200 XRP
2825 auto jro = ledgerEntryOffer(env, bob, bobOfferSeq);
2826 BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(300).value().getText());
2827 BEAST_EXPECT(
2828 jro[jss::node][jss::TakerPays] == usd(60).value().getJson(JsonOptions::Values::None));
2829
2830 // the balance between alice and gw is 160 USD..200 less the 40 taken
2831 // by the offer
2832 auto jrr = ledgerEntryMPT(env, alice, usd);
2833 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "160");
2834 // alice now has 200 more XRP from the payment
2835 jrr = ledgerEntryRoot(env, alice);
2836 BEAST_EXPECT(
2837 jrr[jss::node][sfBalance.fieldName] ==
2838 to_string((XRP(10'000) + XRP(200) - env.current()->fees().base * 2).xrp()));
2839
2840 // bob got 40 USD from partial consumption of the offer
2841 jrr = ledgerEntryMPT(env, bob, usd);
2842 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "40");
2843
2844 // Alice converts USD to XRP which should fail
2845 // due to PartialPayment.
2846 env(pay(alice, alice, XRP(600)), Sendmax(usd(100)), Ter(tecPATH_PARTIAL));
2847
2848 // Alice converts USD to XRP, should succeed because
2849 // we permit partial payment
2850 env(pay(alice, alice, XRP(600)), Sendmax(usd(100)), Txflags(tfPartialPayment));
2851
2852 // Verify the offer was consumed
2853 jro = ledgerEntryOffer(env, bob, bobOfferSeq);
2854 BEAST_EXPECT(jro[jss::error] == "entryNotFound");
2855 BEAST_EXPECT(jro[jss::error_code] == RpcEntryNotFound);
2856 BEAST_EXPECT(jro[jss::error_message] == "Entry not found.");
2857
2858 // verify balances look right after the partial payment
2859 // only 300 XRP should have been payed since that's all
2860 // that remained in the offer from bob. The alice balance is now
2861 // 100 USD because another 60 USD were transferred to bob in the second
2862 // payment
2863 jrr = ledgerEntryMPT(env, alice, usd);
2864 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100");
2865 jrr = ledgerEntryRoot(env, alice);
2866 BEAST_EXPECT(
2867 jrr[jss::node][sfBalance.fieldName] ==
2868 to_string((XRP(10'000) + XRP(200) + XRP(300) - env.current()->fees().base * 4).xrp()));
2869
2870 // bob now has 100 USD - 40 from the first payment and 60 from the
2871 // second (partial) payment
2872 jrr = ledgerEntryMPT(env, bob, usd);
2873 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100");
2874 }
2875
2876 void
2878 {
2879 testcase("Cross Currency Payment: Start with XRP");
2880
2881 using namespace jtx;
2882
2883 Env env{*this, features};
2884
2885 auto const gw = Account{"gateway"};
2886 auto const alice = Account{"alice"};
2887 auto const bob = Account{"bob"};
2888 auto const carol = Account{"carol"};
2889
2890 env.fund(XRP(10'000), gw, alice, bob, carol);
2891
2892 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {carol, bob}});
2893
2894 env(pay(gw, carol, usd(500)));
2895
2896 auto const carolOfferSeq = env.seq(carol);
2897 env(offer(carol, XRP(500), usd(50)));
2898
2899 env(pay(alice, bob, usd(25)), Sendmax(XRP(333)));
2900
2901 auto jrr = ledgerEntryMPT(env, bob, usd);
2902 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "25");
2903
2904 jrr = ledgerEntryMPT(env, carol, usd);
2905 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "475");
2906
2907 auto jro = ledgerEntryOffer(env, carol, carolOfferSeq);
2908 BEAST_EXPECT(
2909 jro[jss::node][jss::TakerGets] == usd(25).value().getJson(JsonOptions::Values::None));
2910 BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(250).value().getText());
2911 }
2912
2913 void
2915 {
2916 testcase("Cross Currency Payment: End with XRP");
2917
2918 using namespace jtx;
2919
2920 Env env{*this, features};
2921
2922 auto const gw = Account{"gateway"};
2923 auto const alice = Account{"alice"};
2924 auto const bob = Account{"bob"};
2925 auto const carol = Account{"carol"};
2926
2927 env.fund(XRP(10'000), gw, alice, bob, carol);
2928
2929 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}});
2930
2931 env(pay(gw, alice, usd(500)));
2932
2933 auto const carolOfferSeq = env.seq(carol);
2934 env(offer(carol, usd(50), XRP(500)));
2935
2936 env(pay(alice, bob, XRP(250)), Sendmax(usd(333)));
2937
2938 auto jrr = ledgerEntryMPT(env, alice, usd);
2939 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "475");
2940
2941 jrr = ledgerEntryMPT(env, carol, usd);
2942 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "25");
2943
2944 jrr = ledgerEntryRoot(env, bob);
2945 BEAST_EXPECT(
2946 jrr[jss::node][sfBalance.fieldName] ==
2947 std::to_string(XRP(10'000).value().mantissa() + XRP(250).value().mantissa()));
2948
2949 auto jro = ledgerEntryOffer(env, carol, carolOfferSeq);
2950 BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(250).value().getText());
2951 BEAST_EXPECT(
2952 jro[jss::node][jss::TakerPays] == usd(25).value().getJson(JsonOptions::Values::None));
2953 }
2954
2955 void
2957 {
2958 testcase("Cross Currency Payment: Bridged");
2959
2960 using namespace jtx;
2961 auto const gw1 = Account{"gateway_1"};
2962 auto const gw2 = Account{"gateway_2"};
2963 auto const alice = Account{"alice"};
2964 auto const bob = Account{"bob"};
2965 auto const carol = Account{"carol"};
2966 auto const dan = Account{"dan"};
2967
2968 auto const test = [&](auto&& issue1, auto&& issue2) {
2969 Env env{*this, features};
2970
2971 env.fund(XRP(10'000), gw1, gw2, alice, bob, carol, dan);
2972
2973 auto const usd =
2974 issue1({.env = env, .token = "USD", .issuer = gw1, .holders = {alice, carol}});
2975 auto const eur =
2976 issue1({.env = env, .token = "EUR", .issuer = gw2, .holders = {bob, dan}});
2977
2978 env(pay(gw1, alice, usd(500)));
2979 env(pay(gw2, dan, eur(400)));
2980
2981 auto const carolOfferSeq = env.seq(carol);
2982 env(offer(carol, usd(50), XRP(500)));
2983
2984 auto const danOfferSeq = env.seq(dan);
2985 env(offer(dan, XRP(500), eur(50)));
2986
2988 jtp[0u][0u][jss::currency] = "XRP";
2989 env(pay(alice, bob, eur(30)), Json(jss::Paths, jtp), Sendmax(usd(333)));
2990
2991 BEAST_EXPECT(env.balance(alice, usd) == usd(470));
2992 BEAST_EXPECT(env.balance(bob, eur) == eur(30));
2993 BEAST_EXPECT(env.balance(carol, usd) == usd(30));
2994 BEAST_EXPECT(env.balance(dan, eur) == eur(370));
2995
2996 auto jro = ledgerEntryOffer(env, carol, carolOfferSeq);
2997 BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(200).value().getText());
2998 BEAST_EXPECT(
2999 jro[jss::node][jss::TakerPays] ==
3000 usd(20).value().getJson(JsonOptions::Values::None));
3001
3002 jro = ledgerEntryOffer(env, dan, danOfferSeq);
3003 BEAST_EXPECT(
3004 jro[jss::node][jss::TakerGets] ==
3005 eur(20).value().getJson(JsonOptions::Values::None));
3006 BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText());
3007 };
3009 }
3010
3011 void
3013 {
3014 // At least with Taker bridging, a sensitivity was identified if the
3015 // second leg goes dry before the first one. This test exercises that
3016 // case.
3017 testcase("Auto Bridged Second Leg Dry");
3018
3019 using namespace jtx;
3020 Account const alice{"alice"};
3021 Account const bob{"bob"};
3022 Account const carol{"carol"};
3023 Account const gw{"gateway"};
3024
3025 auto const test = [&](auto&& issue1, auto&& issue2) {
3026 Env env(*this, features);
3027
3028 env.fund(XRP(100'000'000), alice, bob, carol, gw);
3029 env.close();
3030
3031 auto const usd =
3032 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol}});
3033 auto const eur = issue1({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}});
3034
3035 env(pay(gw, alice, usd(10)));
3036 env(pay(gw, carol, usd(3)));
3037
3038 env(offer(alice, eur(2), XRP(1)));
3039 env(offer(alice, eur(2), XRP(1)));
3040
3041 env(offer(alice, XRP(1), usd(4)));
3042 env(offer(carol, XRP(1), usd(3)));
3043 env.close();
3044
3045 // Bob offers to buy 10 USD for 10 EUR.
3046 // 1. He spends 2 EUR taking Alice's auto-bridged offers and
3047 // gets 4 USD for that.
3048 // 2. He spends another 2 EUR taking Alice's last EUR->XRP offer
3049 // and
3050 // Carol's XRP-USD offer. He gets 3 USD for that.
3051 // The key for this test is that Alice's XRP->USD leg goes dry
3052 // before Alice's EUR->XRP. The XRP->USD leg is the second leg
3053 // which showed some sensitivity.
3054 env(pay(gw, bob, eur(10)));
3055 env.close();
3056 env(offer(bob, usd(10), eur(10)));
3057 env.close();
3058
3059 env.require(Balance(bob, usd(7)));
3060 env.require(Balance(bob, eur(6)));
3061 env.require(Offers(bob, 1));
3062 env.require(Owners(bob, 3));
3063
3064 env.require(Balance(alice, usd(6)));
3065 env.require(Balance(alice, eur(4)));
3066 env.require(Offers(alice, 0));
3067 env.require(Owners(alice, 2));
3068
3069 env.require(Balance(carol, usd(0)));
3070 env.require(Balance(carol, eur(kNone)));
3071
3072 env.require(Offers(carol, 0));
3073 env.require(Owners(carol, 1));
3074 };
3076 }
3077
3078 void
3080 {
3081 testcase("Offer Fees Consume Funds");
3082
3083 using namespace jtx;
3084 auto const gw1 = Account{"gateway_1"};
3085 auto const gw2 = Account{"gateway_2"};
3086 auto const gw3 = Account{"gateway_3"};
3087 auto const alice = Account{"alice"};
3088 auto const bob = Account{"bob"};
3089
3090 auto const test = [&](auto&& issue1, auto&& issue2, auto&& issue3) {
3091 Env env{*this, features};
3092
3093 // Provide micro amounts to compensate for fees to make results
3094 // round nice. reserve: Alice has 3 entries in the ledger, via trust
3095 // lines fees:
3096 // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) +
3097 // 1 for payment == 4
3098 auto const base = env.current()->fees().base;
3099 auto const startingXrp =
3100 XRP(100) + env.current()->fees().accountReserve(3, 1) + base * 4;
3101
3102 env.fund(startingXrp, gw1, gw2, gw3, alice, bob);
3103 env.close();
3104
3105 auto const usD1 =
3106 issue1({.env = env, .token = "US1", .issuer = gw1, .holders = {alice, bob}});
3107 auto const usD2 =
3108 issue2({.env = env, .token = "US2", .issuer = gw2, .holders = {alice, bob}});
3109 auto const usD3 =
3110 issue3({.env = env, .token = "US3", .issuer = gw3, .holders = {alice}});
3111
3112 env(pay(gw1, bob, usD1(500)));
3113
3114 env(offer(bob, XRP(200), usD1(200)));
3115 // Alice has 350 fees - a reserve of 50 = 250 reserve = 100
3116 // available. Ask for more than available to prove reserve works.
3117 env(offer(alice, usD1(200), XRP(200)));
3118
3119 BEAST_EXPECT(env.balance(alice, usD1) == usD1(100));
3120 BEAST_EXPECT(
3121 env.balance(alice) == STAmount(env.current()->fees().accountReserve(3, 1)));
3122
3123 BEAST_EXPECT(env.balance(bob, usD1) == usD1(400));
3124 };
3126 }
3127
3128 void
3130 {
3131 testcase("Offer Create, then Cross");
3132
3133 using namespace jtx;
3134
3135 Env env{*this, features};
3136
3137 auto const gw = Account{"gateway"};
3138 auto const alice = Account{"alice"};
3139 auto const bob = Account{"bob"};
3140
3141 env.fund(XRP(10'000), gw, alice, bob);
3142
3143 MPT const cur =
3144 MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 5'000});
3145
3146 env(pay(gw, bob, cur(100)));
3147
3148 env(offer(alice, cur(50'000), XRP(150'000)));
3149 env(offer(bob, XRP(100), cur(100)));
3150
3151 auto jrr = ledgerEntryMPT(env, alice, cur);
3152 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "34");
3153
3154 jrr = ledgerEntryMPT(env, bob, cur);
3155 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "64");
3156 }
3157
3158 void
3160 {
3161 testcase("Offer tfSell: Basic Sell");
3162
3163 using namespace jtx;
3164
3165 Env env{*this, features};
3166
3167 auto const gw = Account{"gateway"};
3168 auto const alice = Account{"alice"};
3169 auto const bob = Account{"bob"};
3170
3171 auto const startingXrp =
3172 XRP(100) + env.current()->fees().accountReserve(1, 1) + env.current()->fees().base * 2;
3173
3174 env.fund(startingXrp, gw, alice, bob);
3175
3176 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
3177
3178 env(pay(gw, bob, usd(500)));
3179
3180 env(offer(bob, XRP(200), usd(200)), Json(jss::Flags, tfSell));
3181 // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available.
3182 // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available.
3183 // Ask for more than available to prove reserve works.
3184 env(offer(alice, usd(200), XRP(200)), Json(jss::Flags, tfSell));
3185
3186 auto jrr = ledgerEntryMPT(env, alice, usd);
3187 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100");
3188 jrr = ledgerEntryRoot(env, alice);
3189 BEAST_EXPECT(
3190 jrr[jss::node][sfBalance.fieldName] ==
3191 STAmount(env.current()->fees().accountReserve(1, 1)).getText());
3192
3193 jrr = ledgerEntryMPT(env, bob, usd);
3194 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "400");
3195 }
3196
3197 void
3199 {
3200 testcase("Offer tfSell: 2x Sell Exceed Limit");
3201
3202 using namespace jtx;
3203
3204 Env env{*this, features};
3205
3206 auto const gw = Account{"gateway"};
3207 auto const alice = Account{"alice"};
3208 auto const bob = Account{"bob"};
3209
3210 auto const startingXrp =
3211 XRP(100) + env.current()->fees().accountReserve(1, 1) + env.current()->fees().base * 2;
3212
3213 env.fund(startingXrp, gw, alice, bob);
3214
3215 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
3216
3217 env(pay(gw, bob, usd(500)));
3218
3219 env(offer(bob, XRP(100), usd(200)));
3220 // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available.
3221 // Ask for more than available to prove reserve works.
3222 // Taker pays 100 USD for 100 XRP.
3223 // Selling XRP.
3224 // Will sell all 100 XRP and get more USD than asked for.
3225 env(offer(alice, usd(100), XRP(100)), Json(jss::Flags, tfSell));
3226
3227 auto jrr = ledgerEntryMPT(env, alice, usd);
3228 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "200");
3229 jrr = ledgerEntryRoot(env, alice);
3230 BEAST_EXPECT(
3231 jrr[jss::node][sfBalance.fieldName] ==
3232 STAmount(env.current()->fees().accountReserve(1, 1)).getText());
3233
3234 jrr = ledgerEntryMPT(env, bob, usd);
3235 BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "300");
3236 }
3237
3238 void
3240 {
3241 testcase("Client Issue #535: Gateway Cross Currency");
3242
3243 using namespace jtx;
3244 auto const gw = Account{"gateway"};
3245 auto const alice = Account{"alice"};
3246 auto const bob = Account{"bob"};
3247
3248 auto const test = [&](auto&& issue1, auto&& issue2) {
3249 Env env{*this, features};
3250
3251 auto const base = env.current()->fees().base;
3252 auto const startingXrp =
3253 XRP(100.1) + env.current()->fees().accountReserve(1, 1) + base * 2;
3254
3255 env.fund(startingXrp, gw, alice, bob);
3256 env.close();
3257
3258 auto const xts =
3259 issue1({.env = env, .token = "XTS", .issuer = gw, .holders = {alice, bob}});
3260 auto const xxx =
3261 issue2({.env = env, .token = "XXX", .issuer = gw, .holders = {alice, bob}});
3262 env.close();
3263
3264 env(pay(gw, alice, xts(1'000)));
3265 env(pay(gw, alice, xxx(100)));
3266 env(pay(gw, bob, xts(1'000)));
3267 env(pay(gw, bob, xxx(100)));
3268
3269 env(offer(alice, xts(1'000), xxx(100)));
3270
3271 // WS client is used here because the RPC client could not
3272 // be convinced to pass the build_path argument
3273 auto wsc = makeWSClient(env.app().config());
3274 json::Value payment;
3275 payment[jss::secret] = toBase58(generateSeed("bob"));
3276 payment[jss::id] = env.seq(bob);
3277 payment[jss::build_path] = true;
3278 payment[jss::tx_json] = pay(bob, bob, xxx(1));
3279 payment[jss::tx_json][jss::Sequence] =
3280 env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence);
3281 payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base);
3282 payment[jss::tx_json][jss::SendMax] =
3283 xts(15).value().getJson(JsonOptions::Values::None);
3284 auto jrr = wsc->invoke("submit", payment);
3285 BEAST_EXPECT(jrr[jss::status] == "success");
3286 BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS");
3287 if (wsc->version() == 2)
3288 {
3289 BEAST_EXPECT(hasEnvelope2(jrr));
3290 BEAST_EXPECT(jrr.isMember(jss::id) && jrr[jss::id] == 5);
3291 }
3292
3293 BEAST_EXPECT(env.balance(alice, xts) == xts(1010));
3294 BEAST_EXPECT(env.balance(alice, xxx) == xxx(99));
3295
3296 BEAST_EXPECT(env.balance(bob, xts) == xts(990));
3297 BEAST_EXPECT(env.balance(bob, xxx) == xxx(101));
3298 };
3300 }
3301
3302 void
3304 {
3305 // Test a number of different corner cases regarding adding a
3306 // possibly crossable offer to an account. The test is table
3307 // driven so it should be easy to add or remove tests.
3308 testcase("Partial Crossing");
3309
3310 using namespace jtx;
3311
3312 auto const gw = Account("gateway");
3313
3314 Env env{*this, features};
3315
3316 env.fund(XRP(10'000'000), gw);
3317 env.close();
3318
3319 auto musd = MPTTester({.env = env, .issuer = gw});
3320 MPT const usd = musd;
3321
3322 // The fee that's charged for transactions
3323 auto const f = env.current()->fees().base;
3324
3325 // To keep things simple all offers are 1 : 1 for XRP : USD.
3326 enum class PreAuthType { NoPreAuth, AcctPreAuth };
3327 struct TestData
3328 {
3329 std::string account; // Account operated on
3330 STAmount fundXrp; // Account funded with
3331 int bookAmount; // USD -> XRP offer on the books
3332 PreAuthType preAuth; // If true, pre-auth MPToken
3333 int offerAmount; // Account offers this much XRP -> USD
3334 TER tec; // Returned tec code
3335 STAmount spentXrp; // Amount removed from fundXrp
3336 PrettyAmount balanceUsd; // Balance on account end
3337 int offers; // Offers on account
3338 int owners; // Owners on account
3339 int scale = 1; // Scale MPT
3340 };
3341
3342 // clang-format off
3343 TestData const tests[]{
3344 // acct fundXrp bookAmt preTrust offerAmt tec spentXrp balanceUSD offers owners scale
3345 {.account="ann", .fundXrp=reserve(env, 0) + 0 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=f, .balanceUsd=usd( 0), .offers=0, .owners=0}, // Account is at the reserve, and will dip below once fees are subtracted.
3346 {.account="bev", .fundXrp=reserve(env, 0) + 1 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=f, .balanceUsd=usd( 0), .offers=0, .owners=0}, // Account has just enough for the reserve and the fee.
3347 {.account="cam", .fundXrp=reserve(env, 0) + 2 * f, .bookAmount=0, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tecINSUF_RESERVE_OFFER, .spentXrp=f, .balanceUsd=usd( 0), .offers=0, .owners=0}, // Account has enough for the reserve, the fee and the offer, and a bit more, but not enough for the reserve after the offer is placed.
3348 {.account="deb", .fundXrp=reserve(env, 0) + 2 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=2 * f, .balanceUsd=usd( 1), .offers=0, .owners=1, .scale=100000}, // Account has enough to buy a little USD then the offer runs dry.
3349 {.account="eve", .fundXrp=reserve(env, 1) + 0 * f, .bookAmount=0, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=f, .balanceUsd=usd( 0), .offers=1, .owners=1}, // No offer to cross
3350 {.account="flo", .fundXrp=reserve(env, 1) + 0 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 1) + f, .balanceUsd=usd( 1), .offers=0, .owners=1},
3351 {.account="gay", .fundXrp=reserve(env, 1) + 1 * f, .bookAmount=1000, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 50) + f, .balanceUsd=usd( 50), .offers=0, .owners=1},
3352 {.account="hye", .fundXrp=XRP(1000) + 1 * f, .bookAmount=1000, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 800) + f, .balanceUsd=usd( 800), .offers=0, .owners=1},
3353 {.account="ivy", .fundXrp=XRP( 1) + reserve(env, 1) + 1 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 1) + f, .balanceUsd=usd( 1), .offers=0, .owners=1},
3354 {.account="joy", .fundXrp=XRP( 1) + reserve(env, 2) + 1 * f, .bookAmount=1, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 1) + f, .balanceUsd=usd( 1), .offers=1, .owners=2},
3355 {.account="kim", .fundXrp=XRP( 900) + reserve(env, 2) + 1 * f, .bookAmount=999, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 999) + f, .balanceUsd=usd( 999), .offers=0, .owners=1},
3356 {.account="liz", .fundXrp=XRP( 998) + reserve(env, 0) + 1 * f, .bookAmount=999, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 998) + f, .balanceUsd=usd( 998), .offers=0, .owners=1},
3357 {.account="meg", .fundXrp=XRP( 998) + reserve(env, 1) + 1 * f, .bookAmount=999, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 999) + f, .balanceUsd=usd( 999), .offers=0, .owners=1},
3358 {.account="nia", .fundXrp=XRP( 998) + reserve(env, 2) + 1 * f, .bookAmount=999, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 999) + f, .balanceUsd=usd( 999), .offers=1, .owners=2},
3359 {.account="ova", .fundXrp=XRP( 999) + reserve(env, 0) + 1 * f, .bookAmount=1000, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 999) + f, .balanceUsd=usd( 999), .offers=0, .owners=1},
3360 {.account="pam", .fundXrp=XRP( 999) + reserve(env, 1) + 1 * f, .bookAmount=1000, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP(1000) + f, .balanceUsd=usd( 1000), .offers=0, .owners=1},
3361 {.account="rae", .fundXrp=XRP( 999) + reserve(env, 2) + 1 * f, .bookAmount=1000, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP(1000) + f, .balanceUsd=usd( 1000), .offers=0, .owners=1},
3362 {.account="sue", .fundXrp=XRP(1000) + reserve(env, 2) + 1 * f, .bookAmount=0, .preAuth=PreAuthType::NoPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=f, .balanceUsd=usd( 0), .offers=1, .owners=1},
3363 //---------------- Pre-created MPT ---------------------
3364 // Unlike from IOU, an issuer can't pre-create MPToken for an account (see similar tests in Offer_test.cpp)
3365 {.account="ned", .fundXrp=reserve(env, 1) + 0 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3366 {.account="ole", .fundXrp=reserve(env, 1) + 1 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3367 {.account="pat", .fundXrp=reserve(env, 1) + 2 * f, .bookAmount=0, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3368 {.account="quy", .fundXrp=reserve(env, 1) + 2 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecUNFUNDED_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3369 {.account="ron", .fundXrp=reserve(env, 1) + 3 * f, .bookAmount=0, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecINSUF_RESERVE_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3370 {.account="syd", .fundXrp=reserve(env, 1) + 3 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=3 * f, .balanceUsd=usd( 1), .offers=0, .owners=1, .scale=100000},
3371 {.account="ted", .fundXrp=XRP( 20) + reserve(env, 1) + 2 * f, .bookAmount=1000, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP(20) + 2 * f, .balanceUsd=usd( 20), .offers=0, .owners=1},
3372 {.account="uli", .fundXrp=reserve(env, 2) + 0 * f, .bookAmount=0, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tecINSUF_RESERVE_OFFER, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=0, .owners=1},
3373 {.account="vic", .fundXrp=reserve(env, 2) + 0 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 1) + 2 * f, .balanceUsd=usd( 1), .offers=0, .owners=1},
3374 {.account="wes", .fundXrp=reserve(env, 2) + 1 * f, .bookAmount=0, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=2 * f, .balanceUsd=usd( 0), .offers=1, .owners=2},
3375 {.account="xan", .fundXrp=reserve(env, 2) + 1 * f, .bookAmount=1, .preAuth=PreAuthType::AcctPreAuth, .offerAmount=1000, .tec=tesSUCCESS, .spentXrp=XRP( 1) + 2 * f, .balanceUsd=usd( 1), .offers=1, .owners=2},
3376 };
3377 // clang-format on
3378
3379 for (auto const& t : tests)
3380 {
3381 auto const acct = Account(t.account);
3382 env.fund(t.fundXrp, acct);
3383 env.close();
3384
3385 // Make sure gateway has no current offers.
3386 env.require(Offers(gw, 0));
3387
3388 // The gateway optionally creates an offer that would be crossed.
3389 auto const book = t.bookAmount;
3390 if (book != 0)
3391 env(offer(gw, XRP(book), usd(book * t.scale)));
3392 env.close();
3393 std::uint32_t const gwOfferSeq = env.seq(gw) - 1;
3394
3395 // Optionally pre-authorize MPT for acct.
3396 // Note this is not really part of the test, so we expect there
3397 // to be enough XRP reserve for acct to create the trust line.
3398 if (t.preAuth == PreAuthType::AcctPreAuth)
3399 musd.authorize({.account = acct});
3400 env.close();
3401
3402 {
3403 // Acct creates an offer. This is the heart of the test.
3404 auto const acctOffer = t.offerAmount;
3405 env(offer(acct, usd(acctOffer * t.scale), XRP(acctOffer)), Ter(t.tec));
3406 env.close();
3407 }
3408 std::uint32_t const acctOfferSeq = env.seq(acct) - 1;
3409
3410 auto const expBalanceUsd = [&] {
3411 if (t.scale == 1)
3412 return t.balanceUsd;
3413 // crossed offer has XRP available balance of 1 fee
3414 // mpt to XRP ratio is 10
3415 return usd(f.value() / 10);
3416 }();
3417 BEAST_EXPECT(env.balance(acct, usd) == expBalanceUsd);
3418 BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp);
3419 env.require(Offers(acct, t.offers));
3420 env.require(Owners(acct, t.owners));
3421
3422 auto acctOffers = offersOnAccount(env, acct);
3423 BEAST_EXPECT(acctOffers.size() == t.offers);
3424 if (!acctOffers.empty() && t.offers != 0)
3425 {
3426 auto const& acctOffer = *acctOffers.front();
3427
3428 auto const leftover = t.offerAmount - t.bookAmount;
3429 BEAST_EXPECT(acctOffer[sfTakerGets] == XRP(leftover));
3430 BEAST_EXPECT(acctOffer[sfTakerPays] == usd(leftover));
3431 }
3432
3433 if (t.preAuth == PreAuthType::NoPreAuth)
3434 {
3435 if (t.balanceUsd.value().signum() != 0)
3436 {
3437 // Verify the correct contents of MPT
3438 BEAST_EXPECT(env.balance(acct, usd) == expBalanceUsd);
3439 }
3440 else
3441 {
3442 // Verify that no MPT was created.
3443 auto const sle = env.le(keylet::mptoken(usd.issuanceID, acct));
3444 BEAST_EXPECT(!sle);
3445 }
3446 }
3447
3448 // Give the next loop a clean slate by canceling any left-overs
3449 // in the offers.
3450 env(offerCancel(acct, acctOfferSeq));
3451 env(offerCancel(gw, gwOfferSeq));
3452 env.close();
3453 }
3454 }
3455
3456 void
3458 {
3459 testcase("XRP Direct Crossing");
3460
3461 using namespace jtx;
3462
3463 auto const gw = Account("gateway");
3464 auto const alice = Account("alice");
3465 auto const bob = Account("bob");
3466
3467 Env env{*this, features};
3468
3469 env.fund(XRP(1'000'000), gw, bob);
3470 env.close();
3471
3472 // The fee that's charged for transactions.
3473 auto const fee = env.current()->fees().base;
3474
3475 // alice's account has enough for the reserve, one trust line plus two
3476 // offers, and two fees.
3477 env.fund(reserve(env, 2) + fee * 2, alice);
3478 env.close();
3479
3480 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
3481
3482 auto const usdOffer = usd(1'000);
3483 auto const xrpOffer = XRP(1'000);
3484
3485 env(pay(gw, alice, usdOffer));
3486 env.close();
3487 env.require(Balance(alice, usdOffer), Offers(alice, 0), Offers(bob, 0));
3488
3489 // The scenario:
3490 // o alice has USD but wants XRP.
3491 // o bob has XRP but wants USD.
3492 auto const aliceXRP = env.balance(alice);
3493 auto const bobsXRP = env.balance(bob);
3494
3495 env(offer(alice, xrpOffer, usdOffer));
3496 env.close();
3497 env(offer(bob, usdOffer, xrpOffer));
3498
3499 env.close();
3500 env.require(
3501 Balance(alice, usd(0)),
3502 Balance(bob, usdOffer),
3503 Balance(alice, aliceXRP + xrpOffer - fee),
3504 Balance(bob, bobsXRP - xrpOffer - fee),
3505 Offers(alice, 0),
3506 Offers(bob, 0));
3507
3508 BEAST_EXPECT(env.balance(bob, usd) == usdOffer);
3509
3510 // Make two more offers that leave one of the offers non-dry.
3511 env(offer(alice, usd(999), XRP(999)));
3512 env(offer(bob, xrpOffer, usdOffer));
3513
3514 env.close();
3515 env.require(Balance(alice, usd(999)));
3516 env.require(Balance(bob, usd(1)));
3517 env.require(Offers(alice, 0));
3518 BEAST_EXPECT(env.balance(bob, usd) == usd(1));
3519 {
3520 auto const bobsOffers = offersOnAccount(env, bob);
3521 BEAST_EXPECT(bobsOffers.size() == 1);
3522 auto const& bobsOffer = *bobsOffers.front();
3523
3524 BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER);
3525 BEAST_EXPECT(bobsOffer[sfTakerGets] == usd(1));
3526 BEAST_EXPECT(bobsOffer[sfTakerPays] == XRP(1));
3527 }
3528 }
3529
3530 void
3532 {
3533 testcase("Direct Crossing");
3534
3535 using namespace jtx;
3536 auto const gw = Account("gateway");
3537 auto const alice = Account("alice");
3538 auto const bob = Account("bob");
3539
3540 auto const test = [&](auto&& issue1, auto&& issue2) {
3541 Env env{*this, features};
3542
3543 env.fund(XRP(1000000), gw);
3544 env.close();
3545
3546 // The fee that's charged for transactions.
3547 auto const fee = env.current()->fees().base;
3548
3549 // Each account has enough for the reserve, two MPT's, one
3550 // offer, and two fees.
3551 env.fund(reserve(env, 3) + fee * 3, alice);
3552 env.fund(reserve(env, 3) + fee * 2, bob);
3553 env.close();
3554
3555 auto const usd = issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice}});
3556 auto const eur = issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}});
3557
3558 auto const usdOffer = usd(1'000);
3559 auto const eurOffer = eur(1'000);
3560
3561 env(pay(gw, alice, usdOffer));
3562 env(pay(gw, bob, eurOffer));
3563 env.close();
3564
3565 env.require(Balance(alice, usdOffer), Balance(bob, eurOffer));
3566
3567 // The scenario:
3568 // o alice has USD but wants EUR.
3569 // o bob has EUR but wants USD.
3570 env(offer(alice, eurOffer, usdOffer));
3571 env(offer(bob, usdOffer, eurOffer));
3572
3573 env.close();
3574 env.require(
3575 Balance(alice, eurOffer), Balance(bob, usdOffer), Offers(alice, 0), Offers(bob, 0));
3576
3577 // Alice's offer crossing created a default EUR trustline and
3578 // Bob's offer crossing created a default USD trustline:
3579 BEAST_EXPECT(env.balance(alice, eur) == eurOffer);
3580 BEAST_EXPECT(env.balance(bob, usd) == usdOffer);
3581
3582 // Make two more offers that leave one of the offers non-dry.
3583 // Guarantee the order of application by putting a close()
3584 // between them.
3585 env(offer(bob, eurOffer, usdOffer));
3586 env.close();
3587
3588 env(offer(alice, usd(999), eurOffer));
3589 env.close();
3590
3591 env.require(Offers(alice, 0));
3592 env.require(Offers(bob, 1));
3593
3594 env.require(Balance(alice, usd(999)));
3595 env.require(Balance(alice, eur(1)));
3596 env.require(Balance(bob, usd(1)));
3597 env.require(Balance(bob, eur(999)));
3598
3599 {
3600 auto bobsOffers = offersOnAccount(env, bob);
3601 if (BEAST_EXPECT(bobsOffers.size() == 1))
3602 {
3603 auto const& bobsOffer = *bobsOffers.front();
3604
3605 BEAST_EXPECT(bobsOffer[sfTakerGets] == usd(1));
3606 BEAST_EXPECT(bobsOffer[sfTakerPays] == eur(1));
3607 }
3608 }
3609
3610 // alice makes one more offer that cleans out bob's offer.
3611 env(offer(alice, usd(1), eur(1)));
3612 env.close();
3613
3614 env.require(Balance(alice, usd(1'000)));
3615 env.require(Balance(alice, eur(kNone)));
3616 env.require(Balance(bob, usd(kNone)));
3617 env.require(Balance(bob, eur(1'000)));
3618 env.require(Offers(alice, 0));
3619 env.require(Offers(bob, 0));
3620
3621 // The two MPT that were generated by the offers still here
3622 // Unlike IOU, MPToken is not automatically deleted
3623 if constexpr (std::is_same_v<std::decay_t<decltype(eur)>, MPT>)
3624 {
3625 BEAST_EXPECT(env.le(keylet::mptoken(eur.issuanceID, alice)));
3626 auto meur = MPTTester(env, gw, eur, {bob});
3627 // Delete created MPToken to free up reserve
3628 meur.authorize({.account = alice, .flags = tfMPTUnauthorize});
3629 }
3630 if constexpr (std::is_same_v<std::decay_t<decltype(usd)>, MPT>)
3631 {
3632 BEAST_EXPECT(env.le(keylet::mptoken(usd.issuanceID, bob)));
3633 auto musd = MPTTester(env, gw, usd, {alice});
3634 // Delete created MPToken to free up reserve
3635 musd.authorize({.account = bob, .flags = tfMPTUnauthorize});
3636 }
3637
3638 // Make two more offers that leave one of the offers non-dry. We
3639 // need to properly sequence the transactions:
3640 env(offer(alice, eur(999), usdOffer));
3641 env.close();
3642
3643 env(offer(bob, usdOffer, eurOffer));
3644 env.close();
3645
3646 env.require(Offers(alice, 0));
3647 env.require(Offers(bob, 0));
3648
3649 env.require(Balance(alice, usd(0)));
3650 env.require(Balance(alice, eur(999)));
3651 env.require(Balance(bob, usd(1'000)));
3652 env.require(Balance(bob, eur(1)));
3653 };
3655 }
3656
3657 void
3659 {
3660 testcase("Bridged Crossing");
3661
3662 using namespace jtx;
3663 auto const gw = Account("gateway");
3664 auto const alice = Account("alice");
3665 auto const bob = Account("bob");
3666 auto const carol = Account("carol");
3667
3668 auto const test = [&](auto&& issue1, auto&& issue2) {
3669 Env env{*this, features};
3670
3671 env.fund(XRP(1'000'000), gw, alice, bob, carol);
3672 env.close();
3673
3674 auto const usd = issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice}});
3675 auto const eur = issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {carol}});
3676
3677 auto const usdOffer = usd(1'000);
3678 auto const eurOffer = eur(1'000);
3679
3680 env(pay(gw, alice, usdOffer));
3681 env(pay(gw, carol, eurOffer));
3682 env.close();
3683
3684 // The scenario:
3685 // o alice has USD but wants XRP.
3686 // o bob has XRP but wants EUR.
3687 // o carol has EUR but wants USD.
3688 // Note that carol's offer must come last. If carol's offer is
3689 // placed before bob's or alice's, then autobridging will not occur.
3690 env(offer(alice, XRP(1'000), usdOffer));
3691 env(offer(bob, eurOffer, XRP(1'000)));
3692 auto const bobXrpBalance = env.balance(bob);
3693 env.close();
3694
3695 // carol makes an offer that partially consumes alice and bob's
3696 // offers.
3697 env(offer(carol, usd(400), eur(400)));
3698 env.close();
3699
3700 env.require(
3701 Balance(alice, usd(600)),
3702 Balance(bob, eur(400)),
3703 Balance(carol, usd(400)),
3704 Balance(bob, bobXrpBalance - XRP(400)),
3705 Offers(carol, 0));
3706 BEAST_EXPECT(env.balance(bob, eur) == eur(400));
3707 BEAST_EXPECT(env.balance(carol, usd) == usd(400));
3708 {
3709 auto const aliceOffers = offersOnAccount(env, alice);
3710 BEAST_EXPECT(aliceOffers.size() == 1);
3711 auto const& aliceOffer = *aliceOffers.front();
3712
3713 BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER);
3714 BEAST_EXPECT(aliceOffer[sfTakerGets] == usd(600));
3715 BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(600));
3716 }
3717 {
3718 auto const bobsOffers = offersOnAccount(env, bob);
3719 BEAST_EXPECT(bobsOffers.size() == 1);
3720 auto const& bobsOffer = *bobsOffers.front();
3721
3722 BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER);
3723 BEAST_EXPECT(bobsOffer[sfTakerGets] == XRP(600));
3724 BEAST_EXPECT(bobsOffer[sfTakerPays] == eur(600));
3725 }
3726
3727 // carol makes an offer that exactly consumes alice and bob's
3728 // offers.
3729 env(offer(carol, usd(600), eur(600)));
3730 env.close();
3731
3732 env.require(
3733 Balance(alice, usd(0)),
3734 Balance(bob, eurOffer),
3735 Balance(carol, usdOffer),
3736 Balance(bob, bobXrpBalance - XRP(1'000)),
3737 Offers(bob, 0),
3738 Offers(carol, 0));
3739 BEAST_EXPECT(env.balance(bob, eur) == eur(1'000));
3740 BEAST_EXPECT(env.balance(carol, usd) == usd(1'000));
3741
3742 // In pre-flow code alice's offer is left empty in the ledger.
3743 auto const aliceOffers = offersOnAccount(env, alice);
3744 if (!aliceOffers.empty())
3745 {
3746 BEAST_EXPECT(aliceOffers.size() == 1);
3747 auto const& aliceOffer = *aliceOffers.front();
3748
3749 BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER);
3750 BEAST_EXPECT(aliceOffer[sfTakerGets] == usd(0));
3751 BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(0));
3752 }
3753 };
3755 }
3756
3757 void
3759 {
3760 // Test a number of different corner cases regarding offer crossing
3761 // when the tfSell flag is set. The test is table driven so it
3762 // should be easy to add or remove tests.
3763 testcase("Sell Offer");
3764
3765 using namespace jtx;
3766
3767 auto const gw = Account("gateway");
3768
3769 Env env{*this, features};
3770
3771 env.fund(XRP(10'000'000), gw);
3772
3773 auto musd = MPTTester({.env = env, .issuer = gw});
3774 MPT const usd = musd;
3775
3776 // The fee that's charged for transactions
3777 auto const f = env.current()->fees().base;
3778
3779 // To keep things simple all offers are 1 : 1 for XRP : USD.
3780 struct TestData
3781 {
3782 std::string account; // Account operated on
3783 STAmount fundXrp; // XRP acct funded with
3784 STAmount fundUSD; // USD acct funded with
3785 STAmount gwGets; // gw's offer
3786 STAmount gwPays; //
3787 STAmount acctGets; // acct's offer
3788 STAmount acctPays; //
3789 TER tec; // Returned tec code
3790 STAmount spentXrp; // Amount removed from fundXrp
3791 STAmount finalUsd; // Final USD balance on acct
3792 int offers; // Offers on acct
3793 int owners; // Owners on acct
3794 STAmount takerGets; // Remainder of acct's offer
3795 STAmount takerPays; //
3796
3797 // Constructor with takerGets/takerPays
3798 TestData(
3799 std::string&& account, // Account operated on
3800 STAmount fundXrp, // XRP acct funded with
3801 STAmount fundUsd, // USD acct funded with
3802 STAmount gwGets, // gw's offer
3803 STAmount gwPays, //
3804 STAmount acctGets, // acct's offer
3805 STAmount acctPays, //
3806 TER tec, // Returned tec code
3807 STAmount spentXrp, // Amount removed from fundXrp
3808 STAmount finalUsd, // Final USD balance on acct
3809 int offers, // Offers on acct
3810 int owners, // Owners on acct
3811 STAmount takerGets, // Remainder of acct's offer
3812 STAmount takerPays) //
3813 : account(std::move(account))
3814 , fundXrp(std::move(fundXrp))
3815 , fundUSD(std::move(fundUsd))
3816 , gwGets(std::move(gwGets))
3817 , gwPays(std::move(gwPays))
3818 , acctGets(std::move(acctGets))
3819 , acctPays(std::move(acctPays))
3820 , tec(tec)
3821 , spentXrp(std::move(spentXrp))
3822 , finalUsd(std::move(finalUsd))
3823 , offers(offers)
3824 , owners(owners)
3825 , takerGets(std::move(takerGets))
3826 , takerPays(std::move(takerPays))
3827 {
3828 }
3829
3830 // Constructor without takerGets/takerPays
3831 TestData(
3832 std::string&& account, // Account operated on
3833 STAmount const& fundXrp, // XRP acct funded with
3834 STAmount const& fundUsd, // USD acct funded with
3835 STAmount const& gwGets, // gw's offer
3836 STAmount const& gwPays, //
3837 STAmount const& acctGets, // acct's offer
3838 STAmount const& acctPays, //
3839 TER tec, // Returned tec code
3840 STAmount const& spentXrp, // Amount removed from fundXrp
3841 STAmount const& finalUsd, // Final USD balance on acct
3842 int offers, // Offers on acct
3843 int owners) // Owners on acct
3844 : TestData(
3845 std::move(account),
3846 fundXrp,
3847 fundUsd,
3848 gwGets,
3849 gwPays,
3850 acctGets,
3851 acctPays,
3852 tec,
3853 spentXrp,
3854 finalUsd,
3855 offers,
3856 owners,
3857 STAmount{0},
3858 STAmount{0})
3859 {
3860 }
3861 };
3862
3863 // clang-format off
3864 TestData const tests[]{
3865 // acct pays XRP
3866 // acct fundXrp fundUSD gwGets gwPays acctGets acctPays tec spentXrp finalUSD offers owners takerGets takerPays
3867 {"ann", XRP(10) + reserve(env, 0) + 1 * f, usd( 0), XRP(10), usd( 5), usd(10), XRP(10), tecINSUF_RESERVE_OFFER, XRP( 0) + (1 * f), usd( 0), 0, 0},
3868 {"bev", XRP(10) + reserve(env, 1) + 1 * f, usd( 0), XRP(10), usd( 5), usd(10), XRP(10), tesSUCCESS, XRP( 0) + (1 * f), usd( 0), 1, 1, XRP(10), usd(10)},
3869 {"cam", XRP(10) + reserve(env, 0) + 1 * f, usd( 0), XRP(10), usd(10), usd(10), XRP(10), tesSUCCESS, XRP( 10) + (1 * f), usd(10), 0, 1},
3870 {"deb", XRP(10) + reserve(env, 0) + 1 * f, usd( 0), XRP(10), usd(20), usd(10), XRP(10), tesSUCCESS, XRP( 10) + (1 * f), usd(20), 0, 1},
3871 {"eve", XRP(10) + reserve(env, 0) + 1 * f, usd( 0), XRP(10), usd(20), usd( 5), XRP( 5), tesSUCCESS, XRP( 5) + (1 * f), usd(10), 0, 1},
3872 {"flo", XRP(10) + reserve(env, 0) + 1 * f, usd( 0), XRP(10), usd(20), usd(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), usd(20), 0, 1},
3873 {"gay", XRP(20) + reserve(env, 1) + 1 * f, usd( 0), XRP(10), usd(20), usd(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), usd(20), 0, 1},
3874 {"hye", XRP(20) + reserve(env, 2) + 1 * f, usd( 0), XRP(10), usd(20), usd(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), usd(20), 1, 2, XRP(10), usd(10)},
3875 // acct pays USD
3876 {"meg", reserve(env, 1) + 2 * f, usd(10), usd(10), XRP( 5), XRP(10), usd(10), tecINSUF_RESERVE_OFFER, XRP( 0) + (2 * f), usd(10), 0, 1},
3877 {"nia", reserve(env, 2) + 2 * f, usd(10), usd(10), XRP( 5), XRP(10), usd(10), tesSUCCESS, XRP( 0) + (2 * f), usd(10), 1, 2, usd(10), XRP(10)},
3878 {"ova", reserve(env, 1) + 2 * f, usd(10), usd(10), XRP(10), XRP(10), usd(10), tesSUCCESS, XRP(-10) + (2 * f), usd( 0), 0, 1},
3879 {"pam", reserve(env, 1) + 2 * f, usd(10), usd(10), XRP(20), XRP(10), usd(10), tesSUCCESS, XRP(-20) + (2 * f), usd( 0), 0, 1},
3880 {"qui", reserve(env, 1) + 2 * f, usd(10), usd(20), XRP(40), XRP(10), usd(10), tesSUCCESS, XRP(-20) + (2 * f), usd( 0), 0, 1},
3881 {"rae", reserve(env, 2) + 2 * f, usd(10), usd( 5), XRP( 5), XRP(10), usd(10), tesSUCCESS, XRP( -5) + (2 * f), usd( 5), 1, 2, usd( 5), XRP( 5)},
3882 {"sue", reserve(env, 2) + 2 * f, usd(10), usd( 5), XRP(10), XRP(10), usd(10), tesSUCCESS, XRP(-10) + (2 * f), usd( 5), 1, 2, usd( 5), XRP( 5)},
3883 };
3884 // clang-format on
3885
3886 auto const zeroUsd = usd(0);
3887 for (auto const& t : tests)
3888 {
3889 // Make sure gateway has no current offers.
3890 env.require(Offers(gw, 0));
3891
3892 auto const acct = Account(t.account);
3893
3894 env.fund(t.fundXrp, acct);
3895 env.close();
3896
3897 // Optionally give acct some USD. This is not part of the test,
3898 // so we assume that acct has sufficient USD to cover the reserve
3899 // on the trust line.
3900 if (t.fundUSD != zeroUsd)
3901 {
3902 musd.authorize({.account = acct});
3903 env.close();
3904 env(pay(gw, acct, t.fundUSD));
3905 env.close();
3906 }
3907
3908 env(offer(gw, t.gwGets, t.gwPays));
3909 env.close();
3910 std::uint32_t const gwOfferSeq = env.seq(gw) - 1;
3911
3912 // Acct creates a tfSell offer. This is the heart of the test.
3913 env(offer(acct, t.acctGets, t.acctPays, tfSell), Ter(t.tec));
3914 env.close();
3915 std::uint32_t const acctOfferSeq = env.seq(acct) - 1;
3916
3917 // Check results
3918 BEAST_EXPECT(env.balance(acct, usd) == t.finalUsd);
3919 BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp);
3920 env.require(Offers(acct, t.offers));
3921 env.require(Owners(acct, t.owners));
3922
3923 if (t.offers != 0)
3924 {
3925 auto const acctOffers = offersOnAccount(env, acct);
3926 if (!acctOffers.empty())
3927 {
3928 BEAST_EXPECT(acctOffers.size() == 1);
3929 auto const& acctOffer = *acctOffers.front();
3930
3931 BEAST_EXPECT(acctOffer[sfLedgerEntryType] == ltOFFER);
3932 BEAST_EXPECT(acctOffer[sfTakerGets] == t.takerGets);
3933 BEAST_EXPECT(acctOffer[sfTakerPays] == t.takerPays);
3934 }
3935 }
3936
3937 // Give the next loop a clean slate by canceling any left-overs
3938 // in the offers.
3939 env(offerCancel(acct, acctOfferSeq));
3940 env(offerCancel(gw, gwOfferSeq));
3941 env.close();
3942 }
3943 }
3944
3945 void
3947 {
3948 // Test a number of different corner cases regarding offer crossing
3949 // when both the tfSell flag and tfFillOrKill flags are set.
3950 testcase("Combine tfSell with tfFillOrKill");
3951
3952 using namespace jtx;
3953
3954 auto const gw = Account("gateway");
3955 auto const alice = Account("alice");
3956 auto const bob = Account("bob");
3957
3958 Env env{*this, features};
3959
3960 env.fund(XRP(10'000'000), gw, alice, bob);
3961
3962 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {bob}});
3963
3964 // bob offers XRP for USD.
3965 env(pay(gw, bob, usd(100)));
3966 env.close();
3967 env(offer(bob, XRP(2'000), usd(20)));
3968 env.close();
3969 {
3970 // alice submits a tfSell | tfFillOrKill offer that does not cross.
3971 env(offer(alice, usd(21), XRP(2'100), tfSell | tfFillOrKill), Ter(tecKILLED));
3972 env.close();
3973 env.require(Balance(alice, usd(kNone)));
3974 env.require(Offers(alice, 0));
3975 env.require(Balance(bob, usd(100)));
3976 }
3977 {
3978 // alice submits a tfSell | tfFillOrKill offer that crosses.
3979 // Even though tfSell is present it doesn't matter this time.
3980 env(offer(alice, usd(20), XRP(2'000), tfSell | tfFillOrKill));
3981 env.close();
3982 env.require(Balance(alice, usd(20)));
3983 env.require(Offers(alice, 0));
3984 env.require(Balance(bob, usd(80)));
3985 }
3986 {
3987 // alice submits a tfSell | tfFillOrKill offer that crosses and
3988 // returns more than was asked for (because of the tfSell flag).
3989 env(offer(bob, XRP(2'000), usd(20)));
3990 env.close();
3991 env(offer(alice, usd(10), XRP(1'500), tfSell | tfFillOrKill));
3992 env.close();
3993 env.require(Balance(alice, usd(35)));
3994 env.require(Offers(alice, 0));
3995 env.require(Balance(bob, usd(65)));
3996 }
3997 {
3998 // alice submits a tfSell | tfFillOrKill offer that doesn't cross.
3999 // This would have succeeded with a regular tfSell, but the
4000 // fillOrKill prevents the transaction from crossing since not
4001 // all of the offer is consumed.
4002
4003 // We're using bob's left-over offer for XRP(500), USD(5)
4004 env(offer(alice, usd(1), XRP(501), tfSell | tfFillOrKill), Ter(tecKILLED));
4005 env.close();
4006 env.require(Balance(alice, usd(35)));
4007 env.require(Offers(alice, 0));
4008 env.require(Balance(bob, usd(65)));
4009 }
4010 {
4011 // Alice submits a tfSell | tfFillOrKill offer that finishes
4012 // off the remainder of bob's offer.
4013
4014 // We're using bob's left-over offer for XRP(500), USD(5)
4015 env(offer(alice, usd(1), XRP(500), tfSell | tfFillOrKill));
4016 env.close();
4017 env.require(Balance(alice, usd(40)));
4018 env.require(Offers(alice, 0));
4019 env.require(Balance(bob, usd(60)));
4020 }
4021 }
4022
4023 void
4025 {
4026 testcase("Transfer Rate Offer");
4027
4028 using namespace jtx;
4029 auto const gw1 = Account("gateway1");
4030
4031 {
4032 auto const issuer = Account("issuer");
4033 auto const sender = Account("sender");
4034 auto const receiver = Account("receiver");
4035 auto const seller = Account("seller");
4036 auto const buyer = Account("buyer");
4037
4038 Env env{*this, features};
4039 env.fund(XRP(10'000), issuer, sender, receiver, seller, buyer);
4040 env.close();
4041
4042 MPTTester mpt{{
4043 .env = env,
4044 .issuer = issuer,
4045 .holders = {sender, receiver, seller, buyer},
4046 .transferFee = 100,
4047 }};
4048 MPT const token = mpt;
4049
4050 mpt.pay(issuer, sender, 2'000);
4051 mpt.pay(issuer, seller, 2'000);
4052
4053 // A direct holder-to-holder payment of 999 MPT at a 0.1% fee
4054 // requires 1000 from the sender and burns one MPT.
4055 env(pay(sender, receiver, token(999)), Ter(tecPATH_PARTIAL));
4056 env.close();
4057 env(pay(sender, receiver, token(999)), Sendmax(token(1'000)));
4058 env.close();
4059
4060 BEAST_EXPECT(mpt.getBalance(sender) == 1'000);
4061 BEAST_EXPECT(mpt.getBalance(receiver) == 999);
4062 BEAST_EXPECT(mpt.getBalance(issuer) == 3'999);
4063
4064 // CLOB crossing should apply the same fee quantum. The offer
4065 // owner pays ceil(999 * 1.001) = 1000, not floor(...) = 999.
4066 env(offer(seller, XRP(999), token(999)));
4067 env.close();
4068 env(offer(buyer, token(999), XRP(999)));
4069 env.close();
4070
4071 BEAST_EXPECT(mpt.getBalance(seller) == 1'000);
4072 BEAST_EXPECT(mpt.getBalance(buyer) == 999);
4073 BEAST_EXPECT(mpt.getBalance(issuer) == 3'998);
4074 }
4075
4076 auto const test = [&](auto&& issue1, auto&& issue2) {
4077 Env env{*this, features};
4078
4079 // The fee that's charged for transactions.
4080 auto const fee = env.current()->fees().base;
4081
4082 env.fund(XRP(100'000), gw1);
4083 env.close();
4084
4085 auto const usd =
4086 issue1({.env = env, .token = "USD", .issuer = gw1, .transferFee = 25'000});
4087 using TUsd = std::decay_t<decltype(usd)>;
4088 {
4089 auto const ann = Account("ann");
4090 auto const bob = Account("bob");
4091 env.fund(XRP(100) + reserve(env, 2) + (fee * 2), ann, bob);
4092 env.close();
4093
4094 if constexpr (std::is_same_v<TUsd, MPT>)
4095 {
4096 auto musd = MPTTester(env, gw1, usd);
4097 musd.authorize({.account = ann});
4098 musd.authorize({.account = bob});
4099 }
4100 else
4101 {
4102 env(trust(ann, usd(20'000)));
4103 env(trust(bob, usd(20'000)));
4104 env.close();
4105 }
4106
4107 env(pay(gw1, bob, usd(12'500)));
4108 env.close();
4109
4110 // bob offers to sell USD(100) for XRP. alice takes bob's
4111 // offer. Notice that although bob only offered USD(100),
4112 // USD(125) was removed from his account due to the gateway fee.
4113 //
4114 // A comparable payment would look like this:
4115 // env (pay (bob, alice, USD(100)), Sendmax(USD(125)))
4116 env(offer(bob, XRP(1), usd(10'000)));
4117 env.close();
4118
4119 env(offer(ann, usd(10'000), XRP(1)));
4120 env.close();
4121
4122 env.require(Balance(ann, usd(10'000)));
4123 env.require(Balance(ann, XRP(99) + reserve(env, 2)));
4124 env.require(Offers(ann, 0));
4125
4126 env.require(Balance(bob, usd(0)));
4127 env.require(Balance(bob, XRP(101) + reserve(env, 2)));
4128 env.require(Offers(bob, 0));
4129 }
4130 {
4131 // Reverse the order, so the offer in the books is to sell XRP
4132 // in return for USD. Gateway rate should still apply
4133 // identically.
4134 auto const che = Account("che");
4135 auto const deb = Account("deb");
4136 env.fund(XRP(100) + reserve(env, 2) + (fee * 2), che, deb);
4137 env.close();
4138
4139 if constexpr (std::is_same_v<TUsd, MPT>)
4140 {
4141 auto musd = MPTTester(env, gw1, usd);
4142 musd.authorize({.account = che});
4143 musd.authorize({.account = deb});
4144 }
4145 else
4146 {
4147 env(trust(che, usd(20'000)));
4148 env(trust(deb, usd(20'000)));
4149 env.close();
4150 }
4151
4152 env(pay(gw1, deb, usd(12'500)));
4153 env.close();
4154
4155 env(offer(che, usd(10'000), XRP(1)));
4156 env.close();
4157
4158 env(offer(deb, XRP(1), usd(10'000)));
4159 env.close();
4160
4161 env.require(Balance(che, usd(10'000)));
4162 env.require(Balance(che, XRP(99) + reserve(env, 2)));
4163 env.require(Offers(che, 0));
4164
4165 env.require(Balance(deb, usd(0)));
4166 env.require(Balance(deb, XRP(101) + reserve(env, 2)));
4167 env.require(Offers(deb, 0));
4168 }
4169 {
4170 auto const eve = Account("eve");
4171 auto const fyn = Account("fyn");
4172
4173 env.fund(XRP(20'000) + (fee * 2), eve, fyn);
4174 env.close();
4175
4176 if constexpr (std::is_same_v<TUsd, MPT>)
4177 {
4178 auto musd = MPTTester(env, gw1, usd);
4179 musd.authorize({.account = eve});
4180 musd.authorize({.account = fyn});
4181 }
4182 else
4183 {
4184 env(trust(eve, usd(20'000)));
4185 env(trust(fyn, usd(20'000)));
4186 env.close();
4187 }
4188
4189 env(pay(gw1, eve, usd(10'000)));
4190 env(pay(gw1, fyn, usd(10'000)));
4191 env.close();
4192
4193 // This test verifies that the amount removed from an offer
4194 // accounts for the transfer fee that is removed from the
4195 // account but not from the remaining offer.
4196 env(offer(eve, usd(1'000), XRP(4'000)));
4197 env.close();
4198 std::uint32_t const eveOfferSeq = env.seq(eve) - 1;
4199
4200 env(offer(fyn, XRP(2'000), usd(500)));
4201 env.close();
4202
4203 env.require(Balance(eve, usd(10'500)));
4204 env.require(Balance(eve, XRP(18'000)));
4205 auto const evesOffers = offersOnAccount(env, eve);
4206 BEAST_EXPECT(evesOffers.size() == 1);
4207 if (!evesOffers.empty())
4208 {
4209 auto const& evesOffer = *evesOffers.front();
4210 BEAST_EXPECT(evesOffer[sfLedgerEntryType] == ltOFFER);
4211 BEAST_EXPECT(evesOffer[sfTakerGets] == XRP(2'000));
4212 BEAST_EXPECT(evesOffer[sfTakerPays] == usd(500));
4213 }
4214 env(offerCancel(eve, eveOfferSeq)); // For later tests
4215
4216 env.require(Balance(fyn, usd(9'375)));
4217 env.require(Balance(fyn, XRP(22'000)));
4218 env.require(Offers(fyn, 0));
4219 }
4220 // Start messing with two non-native currencies.
4221 auto const gw2 = Account("gateway2");
4222
4223 env.fund(XRP(100'000), gw2);
4224 env.close();
4225
4226 auto const eur =
4227 issue2({.env = env, .token = "EUR", .issuer = gw2, .transferFee = 50'000});
4228 using TEur = std::decay_t<decltype(eur)>;
4229 {
4230 // Remove XRP from the equation. Give the two currencies two
4231 // different transfer rates so we can see both transfer rates
4232 // apply in the same transaction.
4233 auto const gay = Account("gay");
4234 auto const hal = Account("hal");
4235 env.fund(reserve(env, 3) + (fee * 3), gay, hal);
4236 env.close();
4237
4238 if constexpr (std::is_same_v<TUsd, MPT>)
4239 {
4240 auto musd = MPTTester(env, gw1, usd);
4241 musd.authorize({.account = gay});
4242 musd.authorize({.account = hal});
4243 }
4244 else
4245 {
4246 env(trust(gay, usd(20'000)));
4247 env(trust(hal, usd(20'000)));
4248 env.close();
4249 }
4250 if constexpr (std::is_same_v<TEur, MPT>)
4251 {
4252 auto meur = MPTTester(env, gw2, eur);
4253 meur.authorize({.account = gay});
4254 meur.authorize({.account = hal});
4255 }
4256 else
4257 {
4258 env(trust(gay, eur(20'000)));
4259 env(trust(hal, eur(20'000)));
4260 env.close();
4261 }
4262
4263 env(pay(gw1, gay, usd(12'500)));
4264 env(pay(gw2, hal, eur(150)));
4265 env.close();
4266
4267 env(offer(gay, eur(100), usd(10'000)));
4268 env.close();
4269
4270 env(offer(hal, usd(10'000), eur(100)));
4271 env.close();
4272
4273 env.require(Balance(gay, usd(0)));
4274 env.require(Balance(gay, eur(100)));
4275 env.require(Balance(gay, reserve(env, 3)));
4276 env.require(Offers(gay, 0));
4277
4278 env.require(Balance(hal, usd(10'000)));
4279 env.require(Balance(hal, eur(0)));
4280 env.require(Balance(hal, reserve(env, 3)));
4281 env.require(Offers(hal, 0));
4282 }
4283
4284 {
4285 // Make sure things work right when we're auto-bridging as well.
4286 auto const ova = Account("ova");
4287 auto const pat = Account("pat");
4288 auto const qae = Account("qae");
4289 env.fund(XRP(2) + reserve(env, 3) + (fee * 3), ova, pat, qae);
4290 env.close();
4291
4292 // o ova has USD but wants XRP.
4293 // o pat has XRP but wants EUR.
4294 // o qae has EUR but wants USD.
4295 if constexpr (std::is_same_v<TUsd, MPT>)
4296 {
4297 auto musd = MPTTester(env, gw1, usd);
4298 musd.authorize({.account = ova});
4299 musd.authorize({.account = pat});
4300 musd.authorize({.account = qae});
4301 }
4302 else
4303 {
4304 env(trust(ova, usd(20'000)));
4305 env(trust(pat, usd(20'000)));
4306 env(trust(qae, usd(20'000)));
4307 env.close();
4308 }
4309 if constexpr (std::is_same_v<TEur, MPT>)
4310 {
4311 auto meur = MPTTester(env, gw2, eur);
4312 meur.authorize({.account = ova});
4313 meur.authorize({.account = pat});
4314 meur.authorize({.account = qae});
4315 }
4316 else
4317 {
4318 env(trust(ova, eur(20'000)));
4319 env(trust(pat, eur(20'000)));
4320 env(trust(qae, eur(20'000)));
4321 env.close();
4322 }
4323
4324 env(pay(gw1, ova, usd(12'500)));
4325 env(pay(gw2, qae, eur(150)));
4326 env.close();
4327
4328 env(offer(ova, XRP(2), usd(10'000)));
4329 env(offer(pat, eur(100), XRP(2)));
4330 env.close();
4331
4332 env(offer(qae, usd(10'000), eur(100)));
4333 env.close();
4334
4335 env.require(Balance(ova, usd(0)));
4336 env.require(Balance(ova, eur(0)));
4337 env.require(Balance(ova, XRP(4) + reserve(env, 3)));
4338
4339 // In pre-flow code ova's offer is left empty in the ledger.
4340 auto const ovasOffers = offersOnAccount(env, ova);
4341 if (!ovasOffers.empty())
4342 {
4343 BEAST_EXPECT(ovasOffers.size() == 1);
4344 auto const& ovasOffer = *ovasOffers.front();
4345
4346 BEAST_EXPECT(ovasOffer[sfLedgerEntryType] == ltOFFER);
4347 BEAST_EXPECT(ovasOffer[sfTakerGets] == usd(0));
4348 BEAST_EXPECT(ovasOffer[sfTakerPays] == XRP(0));
4349 }
4350
4351 env.require(Balance(pat, usd(0)));
4352 env.require(Balance(pat, eur(100)));
4353 env.require(Balance(pat, XRP(0) + reserve(env, 3)));
4354 env.require(Offers(pat, 0));
4355
4356 env.require(Balance(qae, usd(10'000)));
4357 env.require(Balance(qae, eur(0)));
4358 env.require(Balance(qae, XRP(2) + reserve(env, 3)));
4359 env.require(Offers(qae, 0));
4360 }
4361 };
4363
4364 // Payment trIn: MPT transfer fee must be charged when the payment
4365 // destination is the MPT issuer and MPT crosses the DEX (1-hop).
4366 // Bug: rate() returned parity because strandDst_ == MPT issuer.
4367 // Fix: parity only when this asset IS the final delivered asset.
4368 {
4369 auto const gw = Account("gw_tr1");
4370 auto const alice = Account("alice_tr1");
4371 auto const bob = Account("bob_tr1");
4372
4373 Env env{*this, features};
4374 env.fund(XRP(10'000), gw, alice, bob);
4375 env.close();
4376
4377 MPT const usd = MPTTester(
4378 {.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 25'000});
4379
4380 // alice needs MPT(1250): MPT(1000) to bob's offer + MPT(250) transfer fee (25%)
4381 env(pay(gw, alice, usd(1'250)));
4382 // bob's offer: give XRP(1000), want MPT(1000)
4383 env(offer(bob, usd(1'000), XRP(1'000)));
4384 env.close();
4385
4386 // alice pays gw (MPT issuer) XRP(1000) using MPT as source
4387 // strand: alice -> [MPT/XRP BookStep] -> gw
4388 // strandDst_ = gw = MPT issuer, strandDeliver_ = XRP
4389 // trIn = rate(MPT, gw): fix charges 25% (MPT != strandDeliver_)
4390 env(pay(alice, gw, XRP(1'000)), Path(~XRP), Sendmax(usd(1'250)));
4391 env.close();
4392
4393 // alice consumed all MPT(1250): MPT(1000) to bob + MPT(250) fee
4394 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
4395 // bob received MPT(1000) net
4396 BEAST_EXPECT(env.balance(bob, usd) == usd(1'000));
4397 }
4398
4399 // Payment trIn (2-hop): MPT transfer fee must be charged when MPT is
4400 // intermediate and the destination is the MPT issuer.
4401 // BookStep2(MPT/XRP) prevStep=BookStep1 returns redeems direction
4402 // (ownerPaysTransferFee_=false for Payment), so trIn applies.
4403 // Bug: parity because strandDst_ == MPT issuer.
4404 // Fix: 25% fee because MPT != strandDeliver_(XRP).
4405 {
4406 auto const gw = Account("gw_tr2");
4407 auto const gw2 = Account("gw2_tr2");
4408 auto const alice = Account("alice_tr2");
4409 auto const bob = Account("bob_tr2");
4410 auto const carol = Account("carol_tr2");
4411
4412 Env env{*this, features};
4413 env.fund(XRP(10'000), gw, gw2, alice, bob, carol);
4414 env.close();
4415
4416 MPT const musd = MPTTester(
4417 {.env = env, .issuer = gw, .holders = {bob, carol}, .transferFee = 25'000});
4418 auto const gusd = gw2["USD"];
4419
4420 env(trust(alice, gusd(10'000)));
4421 env(trust(bob, gusd(10'000)));
4422 env.close();
4423
4424 env(pay(gw2, alice, gusd(1'000)));
4425 env(pay(gw, bob, musd(1'000)));
4426 env.close();
4427
4428 // bob's offer: give MPT(1000), want GUSD(1000)
4429 env(offer(bob, gusd(1'000), musd(1'000)));
4430 // carol's offer: give XRP(800), want MPT(800)
4431 env(offer(carol, musd(800), XRP(800)));
4432 env.close();
4433
4434 // Payment: alice GUSD -> [BookStep1: GUSD/MUSD] -> [BookStep2: MUSD/XRP] -> gw XRP
4435 // strandDst_ = gw = MPT issuer, strandDeliver_ = XRP
4436 // BookStep2 trIn: fix = 1.25 -> upstream needs MUSD(1000) for carol's MUSD(800) offer
4437 // => alice must provide full GUSD(1000) to bob's offer; without fix alice only pays
4438 // GUSD(800)
4439 env(pay(alice, gw, XRP(800)), Path(~musd), Sendmax(gusd(1'000)));
4440 env.close();
4441
4442 // alice spent all GUSD(1000); bug would leave GUSD(200) unspent
4443 BEAST_EXPECT(env.balance(alice, gusd) == gusd(0));
4444 // bob gave MPT(1000) and received GUSD(1000)
4445 BEAST_EXPECT(env.balance(bob, musd) == musd(0));
4446 // carol received MPT(800) net (MPT(200) went to gw as fee)
4447 BEAST_EXPECT(env.balance(carol, musd) == musd(800));
4448 }
4449 }
4450
4451 void
4453 {
4454 testcase("Transfer Rate Overflow Offer");
4455
4456 using namespace jtx;
4457
4458 auto const issuer = Account("issuer");
4459 auto const taker = Account("taker");
4460
4461 {
4462 Env env{*this, features};
4463 env.fund(XRP(10'000), issuer, taker);
4464 env.close();
4465
4466 auto constexpr takerFunds = 2'000'000'000'000'000'000LL;
4467 MPTTester const token{{
4468 .env = env,
4469 .issuer = issuer,
4470 .holders = {taker},
4471 .transferFee = 50'000,
4472 .pay = takerFunds,
4473 .maxAmt = kMaxMpTokenAmount,
4474 }};
4475
4476 // Covers OfferCreate::flowCross() sendMax calculation. A large
4477 // non-issuer MPT offer with a transfer fee used to overflow in
4478 // multiplyRound() before the offer could be placed.
4479 auto constexpr offerAmount = 1'230'000'000'000'000'000LL;
4480 auto const takerSeq = env.seq(taker);
4481 env(offer(taker, XRP(1), token(offerAmount)));
4482 env.close();
4483
4484 BEAST_EXPECT(
4485 env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq))) != nullptr);
4486 BEAST_EXPECT(env.balance(taker, token) == token(takerFunds));
4487 }
4488
4489 // Each scenario below targets a BookStep/OfferStream overflow path.
4490 // The expected behavior is the same in all cases: remove the unusable
4491 // book tip offer and let the taker's crossing offer remain rather than
4492 // returning tecINTERNAL with the poison offer still on-ledger.
4493 {
4494 Env env{*this, features};
4495 env.fund(XRP(10'000), issuer, taker);
4496 env.close();
4497
4498 MPTTester const token{
4499 {.env = env, .issuer = issuer, .holders = {taker}, .transferFee = 10'000}};
4500
4501 // Covers BookStep::forEachOffer() offer preparation, where
4502 // ownerGives = mulRatio(ofrAmt.out, transferRateOut) used to
4503 // overflow for an oversized MPT output with a transfer fee and
4504 // the ask was removed. The issuer's funds are what it can still
4505 // issue, so the ask is now clipped to that before the gross-up
4506 // and is crossed like any partially funded offer.
4507 std::int64_t const askAmount = 8'500'000'000'000'000'000LL;
4508 auto const askSeq = env.seq(issuer);
4509 env(offer(issuer, XRP(1), token(askAmount)));
4510 env.close();
4511
4512 auto const askKeylet = keylet::offer(issuer.id(), SeqProxy::rawSequence(askSeq));
4513 BEAST_EXPECT(env.le(askKeylet) != nullptr);
4514
4515 auto const takerSeq = env.seq(taker);
4516 env(offer(taker, token(100), XRP(100)));
4517 env.close();
4518
4519 BEAST_EXPECT(env.balance(taker, token) == token(100));
4520 BEAST_EXPECT(
4521 env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq))) == nullptr);
4522 auto const sle = env.le(askKeylet);
4523 if (BEAST_EXPECT(sle))
4524 BEAST_EXPECT((*sle)[sfTakerGets] == token(askAmount - 100));
4525 }
4526
4527 {
4528 auto const gwA = Account("gatewayA");
4529 auto const gwB = Account("gatewayB");
4530 auto const alice = Account("alice");
4531 auto const mallory = Account("mallory");
4532
4533 Env env{*this, features};
4534 env.fund(XRP(10'000), gwA, gwB, alice, mallory);
4535 env.close();
4536
4537 MPTTester const tokenA{
4538 {.env = env, .issuer = gwA, .holders = {alice, mallory}, .transferFee = 50'000}};
4539
4540 MPTTester const tokenB{{.env = env, .issuer = gwB, .holders = {alice, mallory}}};
4541
4542 env(pay(gwA, alice, tokenA(1'000)));
4543
4544 // Covers BookStep::forEachOffer() offer preparation, where
4545 // stpAmt.in = mulRatio(ofrAmt.in, transferRateIn) overflowed.
4546 // The MPT/MPT amounts keep the offer quality reachable while
4547 // applying tokenA's transfer rate overflows the input side. Such
4548 // an offer can no longer rest (see the fee gross-up scenarios
4549 // below), so with nothing to cross it is tecKILLED.
4550 std::int64_t const poisonPays = 6'148'914'691'236'517'205LL;
4551 std::int64_t const poisonGets = 34'000'000'000'000'000LL;
4552 env(pay(gwB, mallory, tokenB(poisonGets)));
4553
4554 auto const poisonSeq = env.seq(mallory);
4555 env(offer(mallory, tokenA(poisonPays), tokenB(poisonGets)), Ter(tecKILLED));
4556 env.close();
4557
4558 auto const poisonKeylet = keylet::offer(mallory.id(), SeqProxy::rawSequence(poisonSeq));
4559 BEAST_EXPECT(env.le(poisonKeylet) == nullptr);
4560
4561 auto const aliceSeq = env.seq(alice);
4562 env(offer(alice, tokenB(1), tokenA(100)));
4563 env.close();
4564
4565 BEAST_EXPECT(env.le(poisonKeylet) == nullptr);
4566 BEAST_EXPECT(
4567 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceSeq))) != nullptr);
4568 }
4569
4570 {
4571 // Companion to the transfer-rate overflow cases above. The taker
4572 // buys ~1.84e18 MPT for XRP(1) against a same-magnitude issuer
4573 // ask, so BookStep::revImp()'s limitStepOut() reduces the ask by
4574 // one unit: mulRound(MPT limit, rate, XRP) with a 63-bit MPT
4575 // operand and an XRP result. That used to take the legacy
4576 // 16-digit path and overflow; forEachOffer's catch then removed
4577 // the ask and the taker got tecKILLED (its own rate is
4578 // unrepresentable, so nothing rested). With Number arithmetic for
4579 // any MPT operand the ask is crossed like any other offer.
4580 Env env{*this, features};
4581 env.fund(XRP(10'000), issuer, taker);
4582 env.close();
4583
4584 MPT const token = MPTTester(
4585 {.env = env, .issuer = issuer, .holders = {taker}, .maxAmt = kMaxMpTokenAmount});
4586
4587 env(pay(issuer, taker, token(1)));
4588 env.close();
4589
4590 auto const funded = 1'844'674'407'370'955'162LL;
4591 auto const offerOut = funded + 1;
4592
4593 auto const askSeq = env.seq(issuer);
4594 env(offer(issuer, XRP(1), token(offerOut)));
4595 env.close();
4596
4597 auto const askKeylet = keylet::offer(issuer.id(), SeqProxy::rawSequence(askSeq));
4598 BEAST_EXPECT(env.le(askKeylet) != nullptr);
4599
4600 auto const issuerXRPBefore = env.balance(issuer, XRP);
4601 auto const takerXRPBefore = env.balance(taker, XRP);
4602 auto const takerSeq = env.seq(taker);
4603 auto const fee = env.current()->fees().base;
4604 env(offer(taker, token(funded), XRP(1)));
4605 env.close();
4606
4607 // The taker's bid is filled in full at the ask's price:
4608 // funded / (funded + 1) XRP rounds up to the whole XRP(1), so the
4609 // ask is consumed and nothing rests on either side.
4610 BEAST_EXPECT(env.le(askKeylet) == nullptr);
4611 BEAST_EXPECT(
4612 env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq))) == nullptr);
4613 BEAST_EXPECT(env.balance(issuer, XRP) == issuerXRPBefore + XRP(1));
4614 BEAST_EXPECT(env.balance(taker, XRP) == takerXRPBefore - XRP(1) - fee);
4615 BEAST_EXPECT(env.balance(taker, token) == token(1 + funded));
4616 BEAST_EXPECT(env.seq(taker) == takerSeq + 1);
4617 }
4618
4619 {
4620 auto const maker = Account("maker");
4621
4622 Env env{*this, features};
4623 env.fund(XRP(10'000), issuer, maker, taker);
4624 env.close();
4625
4626 MPT const token = MPTTester({
4627 .env = env,
4628 .issuer = issuer,
4629 .holders = {maker, taker},
4630 .maxAmt = kMaxMpTokenAmount,
4631 });
4632
4633 // Covers OfferStream::step() filtering. The ask is mostly funded;
4634 // reducing it to the owner's actual funds inside
4635 // shouldRmSmallIncreasedQOffer() (an MPT operand with an XRP
4636 // result) used to overflow and remove the ask before BookStep saw
4637 // it. It is now a normal partially funded offer.
4638 auto const funded = 1'844'674'407'370'955'162LL;
4639 auto const offerOut = funded + 1;
4640 env(pay(issuer, maker, token(funded)));
4641
4642 auto const askSeq = env.seq(maker);
4643 env(offer(maker, XRP(1), token(offerOut)));
4644 env.close();
4645
4646 auto const askKeylet = keylet::offer(maker.id(), SeqProxy::rawSequence(askSeq));
4647 BEAST_EXPECT(env.le(askKeylet) != nullptr);
4648
4649 auto const takerSeq = env.seq(taker);
4650 auto const takerXRPBefore = env.balance(taker, XRP);
4651 auto const fee = env.current()->fees().base;
4652 env(offer(taker, token(1), XRP(1)));
4653 env.close();
4654
4655 // One token at the ask's price is a fraction of a drop, rounded up
4656 // to one drop. The taker's bid is filled and the ask rests reduced
4657 // by that token and that drop.
4658 BEAST_EXPECT(
4659 env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq))) == nullptr);
4660 auto const ask = env.le(askKeylet);
4661 if (BEAST_EXPECT(ask))
4662 {
4663 BEAST_EXPECT((*ask)[sfTakerPays] == XRP(1) - drops(1));
4664 BEAST_EXPECT((*ask)[sfTakerGets] == token(offerOut - 1));
4665 }
4666 BEAST_EXPECT(env.balance(maker, token) == token(funded - 1));
4667 BEAST_EXPECT(env.balance(taker, token) == token(1));
4668 BEAST_EXPECT(env.balance(taker, XRP) == takerXRPBefore - drops(1) - fee);
4669 }
4670
4671 {
4672 // A bid can't be placed if its fee-grossed TakerPays overflows,
4673 // but the issuer can raise a mutable transfer fee after the bid
4674 // rests. Then stpAmt.in = mulRatio(ofrAmt.in, transferRateIn)
4675 // overflows in BookStep::forEachOffer() and the bid is removed.
4676 // Run with trace-level logging so removeOffer() emits its
4677 // "Removing offer with overflowing amount calculation" trace
4678 // line, which is skipped when logging is above trace severity.
4679 auto const gwA = Account("gatewayA");
4680 auto const gwB = Account("gatewayB");
4681 auto const alice = Account("alice");
4682 auto const mallory = Account("mallory");
4683
4684 std::string logs;
4685 {
4686 Env env{
4687 *this,
4688 envconfig(),
4689 features,
4692 env.fund(XRP(10'000), gwA, gwB, alice, mallory);
4693 env.close();
4694
4695 MPTTester tokenA{{.env = env, .issuer = gwA, .holders = {alice, mallory}}};
4696 MPTTester const tokenB{{.env = env, .issuer = gwB, .holders = {alice, mallory}}};
4697
4698 std::int64_t const bidPays = 6'148'914'691'236'517'205LL;
4699 std::int64_t const bidGets = 34'000'000'000'000'000LL;
4700 env(pay(gwA, alice, tokenA(10'000)));
4701 env(pay(gwB, mallory, tokenB(bidGets)));
4702 env.close();
4703
4704 auto const bidSeq = env.seq(mallory);
4705 env(offer(mallory, tokenA(bidPays), tokenB(bidGets)));
4706 env.close();
4707 auto const bidKeylet = keylet::offer(mallory.id(), SeqProxy::rawSequence(bidSeq));
4708 BEAST_EXPECT(env.le(bidKeylet) != nullptr);
4709
4710 tokenA.set({.account = gwA, .transferFee = 50'000});
4711 env.close();
4712
4713 auto const aliceSeq = env.seq(alice);
4714 env(offer(alice, tokenB(1), tokenA(1'000)));
4715 env.close();
4716
4717 BEAST_EXPECT(env.le(bidKeylet) == nullptr);
4718 BEAST_EXPECT(
4719 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceSeq))) != nullptr);
4720 }
4721 BEAST_EXPECT(logs.contains("Removing offer with overflowing amount calculation"));
4722 }
4723
4724 auto const maxAmt = static_cast<std::int64_t>(kMaxMpTokenAmount);
4725 // floor(maxAmt / 1.1): the largest amount whose 10% fee gross-up fits.
4726 std::int64_t const maxGross = 8'384'883'669'867'978'006LL;
4727
4728 // An MPT amount grossed up by its transfer fee may not fit in an MPT
4729 // amount.
4730 //
4731 // TakerGets: flowCross() grosses up the taker's own TakerGets for
4732 // sendMax, and that multiply used to throw (tecINTERNAL). It is now
4733 // capped at the balance and the offer rests. A Payment consumes such an
4734 // offer normally (the owner's side isn't grossed up there), and so
4735 // does an OfferCreate taker: BookStep clips ownerGives to the owner's
4736 // funds before grossing up.
4737 //
4738 // TakerPays: every redeeming taker grosses up the bid's whole TakerPays
4739 // in BookStep, so no taker can take it and it would be removed on the
4740 // first attempt. Such a bid may still cross, but its remainder isn't
4741 // placed: tecKILLED if nothing crossed, like an offer with an
4742 // unrepresentable quality.
4743 {
4744 // The reported case: alice holds the whole supply and sells it for
4745 // a little XRP or USD. The offers rest.
4746 auto const gw = Account("gw");
4747 auto const usd = gw["USD"];
4748 auto const alice = Account("alice");
4749 auto const bob = Account("bob");
4750
4751 Env env{*this, features};
4752 env.fund(XRP(100'000), issuer, alice, bob, gw);
4753 env.close();
4754
4755 MPTTester const token{{
4756 .env = env,
4757 .issuer = issuer,
4758 .holders = {alice, bob},
4759 .transferFee = 10'000,
4760 .maxAmt = kMaxMpTokenAmount,
4761 }};
4762 env(pay(issuer, alice, token(maxAmt)));
4763 env.close();
4764
4765 // A bid for the whole supply can't rest: the taker would pay the
4766 // fee on top of it. Nothing to cross yet, so tecKILLED.
4767 env(offer(bob, token(maxAmt), XRP(1)), Ter(tecKILLED));
4768 env(offer(bob, token(maxGross + 1), XRP(1)), Ter(tecKILLED));
4769 env.close();
4770 BEAST_EXPECT(env.ownerCount(bob) == 1);
4771
4772 auto const seq1 = env.seq(alice);
4773 env(offer(alice, XRP(1), token(maxAmt)));
4774 auto const seq2 = env.seq(alice);
4775 env(offer(alice, usd(1), token(maxAmt)));
4776 auto const seq3 = env.seq(alice);
4777 env(offer(alice, XRP(1), token(maxGross + 1)));
4778 env.close();
4779 for (auto const seq : {seq1, seq2, seq3})
4780 {
4781 BEAST_EXPECT(
4782 env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(seq))) != nullptr);
4783 }
4784 BEAST_EXPECT(env.balance(alice, token) == token(maxAmt));
4785 BEAST_EXPECT(env.ownerCount(alice) == 4);
4786 }
4787
4788 {
4789 // The resting whole-supply ask is consumed by a Payment (the fee
4790 // is charged in the endpoint step, not on the owner's side) and
4791 // by an OfferCreate taker. alice can't fund the fee on the whole
4792 // offer, so BookStep clips it to her funds before grossing up,
4793 // instead of grossing up the whole offer, which overflows.
4794 auto const alice = Account("alice");
4795 auto const bob = Account("bob");
4796 auto const carol = Account("carol");
4797
4798 Env env{*this, features};
4799 env.fund(XRP(100'000), issuer, alice, bob, carol);
4800 env.close();
4801
4802 MPTTester const token{{
4803 .env = env,
4804 .issuer = issuer,
4805 .holders = {alice, bob, carol},
4806 .transferFee = 10'000,
4807 .maxAmt = kMaxMpTokenAmount,
4808 }};
4809 MPT const mpt = token;
4810 env(pay(issuer, alice, token(maxAmt)));
4811 env.close();
4812
4813 // One drop buys 1e9 units.
4814 auto const askSeq = env.seq(alice);
4815 env(offer(alice, drops(9'223'372'036), token(maxAmt)));
4816 env.close();
4817 auto const askKeylet = keylet::offer(alice.id(), SeqProxy::rawSequence(askSeq));
4818 BEAST_EXPECT(env.le(askKeylet) != nullptr);
4819
4820 std::int64_t const small = 1'000'000'000LL;
4821 env(pay(bob, carol, token(small)),
4822 Path(~mpt),
4823 Sendmax(XRP(100)),
4824 Txflags(tfNoRippleDirect | tfPartialPayment));
4825 env.close();
4826 BEAST_EXPECT(env.balance(carol, token) == token(small));
4827 BEAST_EXPECT(env.balance(alice, token) == token(maxAmt - small - (small / 10)));
4828 {
4829 auto const sle = env.le(askKeylet);
4830 if (BEAST_EXPECT(sle))
4831 BEAST_EXPECT((*sle)[sfTakerGets] == token(maxAmt - small - (small / 10)));
4832 }
4833
4834 auto const bidSeq = env.seq(bob);
4835 env(offer(bob, token(small), drops(2)));
4836 env.close();
4837 BEAST_EXPECT(env.balance(bob, token) == token(small));
4838 BEAST_EXPECT(env.balance(alice, token) == token(maxAmt - (2 * (small + (small / 10)))));
4839 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bidSeq))) == nullptr);
4840 {
4841 auto const sle = env.le(askKeylet);
4842 if (BEAST_EXPECT(sle))
4843 {
4844 BEAST_EXPECT((*sle)[sfTakerGets] == token(maxAmt - (2 * small) - (small / 10)));
4845 }
4846 }
4847 }
4848
4849 {
4850 // A holder's ask far above its funds: the fee gross-up of the
4851 // whole offer (9e18 × 1.1) overflows, but the funded slice
4852 // (1e12 / 1.1) doesn't. BookStep clips to the funds first, so the
4853 // ask is crossed instead of removed.
4854 auto const alice = Account("alice");
4855 auto const bob = Account("bob");
4856
4857 Env env{*this, features};
4858 env.fund(XRP(100'000), issuer, alice, bob);
4859 env.close();
4860
4861 MPTTester const token{{
4862 .env = env,
4863 .issuer = issuer,
4864 .holders = {alice, bob},
4865 .transferFee = 10'000,
4866 .maxAmt = kMaxMpTokenAmount,
4867 }};
4868 std::int64_t const aliceFunds = 1'000'000'000'000LL;
4869 env(pay(issuer, alice, token(aliceFunds)));
4870 env.close();
4871
4872 // One drop buys 1e9 units.
4873 std::int64_t const askAmount = 9'000'000'000'000'000'000LL;
4874 auto const askSeq = env.seq(alice);
4875 env(offer(alice, drops(9'000'000'000), token(askAmount)));
4876 env.close();
4877 auto const askKeylet = keylet::offer(alice.id(), SeqProxy::rawSequence(askSeq));
4878 BEAST_EXPECT(env.le(askKeylet) != nullptr);
4879
4880 std::int64_t const small = 1'000'000'000LL;
4881 auto const bidSeq = env.seq(bob);
4882 env(offer(bob, token(small), drops(2)));
4883 env.close();
4884 BEAST_EXPECT(env.balance(bob, token) == token(small));
4885 BEAST_EXPECT(env.balance(alice, token) == token(aliceFunds - small - (small / 10)));
4886 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bidSeq))) == nullptr);
4887 auto const sle = env.le(askKeylet);
4888 if (BEAST_EXPECT(sle))
4889 BEAST_EXPECT((*sle)[sfTakerGets] == token(askAmount - small));
4890 }
4891
4892 {
4893 // Control: an ask at the largest amount whose gross-up fits is
4894 // taken normally. bob buys 1e9 for a couple of drops and alice
4895 // pays 1e9 plus the 1e8 fee.
4896 auto const alice = Account("alice");
4897 auto const bob = Account("bob");
4898
4899 Env env{*this, features};
4900 env.fund(XRP(100'000), issuer, alice, bob);
4901 env.close();
4902
4903 MPTTester const token{{
4904 .env = env,
4905 .issuer = issuer,
4906 .holders = {alice, bob},
4907 .transferFee = 10'000,
4908 .maxAmt = kMaxMpTokenAmount,
4909 }};
4910 env(pay(issuer, alice, token(maxAmt)));
4911 env.close();
4912
4913 auto const okSeq = env.seq(alice);
4914 env(offer(alice, drops(maxGross / 1'000'000'000), token(maxGross)));
4915 env.close();
4916 auto const okKeylet = keylet::offer(alice.id(), SeqProxy::rawSequence(okSeq));
4917 BEAST_EXPECT(env.le(okKeylet) != nullptr);
4918
4919 std::int64_t const small = 1'000'000'000LL;
4920 env(offer(bob, token(small), drops(2)));
4921 env.close();
4922 BEAST_EXPECT(env.balance(bob, token) == token(small));
4923 BEAST_EXPECT(env.balance(alice, token) == token(maxAmt - small - (small / 10)));
4924 auto const sle = env.le(okKeylet);
4925 if (BEAST_EXPECT(sle))
4926 BEAST_EXPECT((*sle)[sfTakerGets] == token(maxGross - small));
4927 }
4928
4929 {
4930 // With a resting bid, the whole-supply ask crosses it and the
4931 // remainder rests. MPT/MPT so the remainder's quality is
4932 // representable (a 63-bit MPT over a few drops is not).
4933 auto const gwA = Account("gatewayA");
4934 auto const gwB = Account("gatewayB");
4935 auto const alice = Account("alice");
4936 auto const bob = Account("bob");
4937
4938 Env env{*this, features};
4939 env.fund(XRP(10'000), gwA, gwB, alice, bob);
4940 env.close();
4941
4942 MPTTester const tokenA{{
4943 .env = env,
4944 .issuer = gwA,
4945 .holders = {alice, bob},
4946 .transferFee = 10'000,
4947 .maxAmt = kMaxMpTokenAmount,
4948 }};
4949 MPTTester const tokenB{{.env = env, .issuer = gwB, .holders = {alice, bob}}};
4950
4951 std::int64_t const small = 1'000'000'000LL;
4952 std::int64_t const bobPays = 20'000'000LL;
4953 std::int64_t const alicePays = 110'000'000'000'000'000LL;
4954 env(pay(gwA, alice, tokenA(maxAmt)));
4955 env(pay(gwB, bob, tokenB(bobPays)));
4956 env.close();
4957
4958 env(offer(bob, tokenA(small), tokenB(bobPays)));
4959 env.close();
4960
4961 auto const aliceSeq = env.seq(alice);
4962 env(offer(alice, tokenB(alicePays), tokenA(maxAmt)));
4963 env.close();
4964 BEAST_EXPECT(env.balance(bob, tokenA) == tokenA(small));
4965 BEAST_EXPECT(env.balance(alice, tokenA) == tokenA(maxAmt - small - (small / 10)));
4966 BEAST_EXPECT(env.balance(alice, tokenB) == tokenB(bobPays));
4967 auto const sle = env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(aliceSeq)));
4968 if (BEAST_EXPECT(sle))
4969 {
4970 BEAST_EXPECT((*sle)[sfTakerPays] == tokenB(alicePays - bobPays));
4971 // TakerGets is scaled by the offer's own quality (about 83.85
4972 // tokenA per tokenB), so it drops by about 1.68e9.
4973 auto const gets = (*sle)[sfTakerGets].mpt().value();
4974 BEAST_EXPECT(gets > maxAmt - (2 * small) && gets <= maxAmt - small);
4975 }
4976 }
4977
4978 {
4979 // The issuer's ask for the whole supply rests too; flowCross()
4980 // doesn't gross up the issuer's own sendMax at all.
4981 Env env{*this, features};
4982 env.fund(XRP(10'000), issuer, taker);
4983 env.close();
4984
4985 MPTTester const token{{
4986 .env = env,
4987 .issuer = issuer,
4988 .holders = {taker},
4989 .transferFee = 10'000,
4990 .maxAmt = kMaxMpTokenAmount,
4991 }};
4992
4993 auto const issuerSeq = env.seq(issuer);
4994 env(offer(issuer, XRP(1), token(maxAmt)));
4995 env.close();
4996 BEAST_EXPECT(
4997 env.le(keylet::offer(issuer.id(), SeqProxy::rawSequence(issuerSeq))) != nullptr);
4998 }
4999
5000 {
5001 // An issuer offer above MaximumAmount is not rejected either. It
5002 // is a partially funded offer, and fills up to the remaining
5003 // issuance capacity.
5004 Env env{*this, features};
5005 env.fund(XRP(10'000), issuer, taker);
5006 env.close();
5007
5008 MPTTester const token{
5009 {.env = env, .issuer = issuer, .holders = {taker}, .maxAmt = 1'000}};
5010
5011 auto const issuerSeq = env.seq(issuer);
5012 env(offer(issuer, XRP(2), token(2'000)));
5013 env.close();
5014 auto const issuerKeylet = keylet::offer(issuer.id(), SeqProxy::rawSequence(issuerSeq));
5015 BEAST_EXPECT(env.le(issuerKeylet) != nullptr);
5016
5017 auto const takerXRPBefore = env.balance(taker, XRP);
5018 auto const fee = env.current()->fees().base;
5019 auto const takerSeq = env.seq(taker);
5020 env(offer(taker, token(2'000), XRP(2)));
5021 env.close();
5022
5023 // 1,000 units for XRP(1); the exhausted issuer offer is removed and
5024 // the taker's remainder rests.
5025 BEAST_EXPECT(env.balance(taker, token) == token(1'000));
5026 BEAST_EXPECT(env.balance(taker, XRP) == takerXRPBefore - fee - XRP(1));
5027 BEAST_EXPECT(env.le(issuerKeylet) == nullptr);
5028 auto const sle = env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq)));
5029 if (BEAST_EXPECT(sle))
5030 BEAST_EXPECT((*sle)[sfTakerPays] == token(1'000));
5031 }
5032
5033 {
5034 // No fee: the whole supply can be offered.
5035 Env env{*this, features};
5036 env.fund(XRP(10'000), issuer, taker);
5037 env.close();
5038
5039 MPTTester const token{{
5040 .env = env,
5041 .issuer = issuer,
5042 .holders = {taker},
5043 .pay = kMaxMpTokenAmount,
5044 .maxAmt = kMaxMpTokenAmount,
5045 }};
5046
5047 auto const takerSeq = env.seq(taker);
5048 env(offer(taker, XRP(1), token(maxAmt)));
5049 env.close();
5050 BEAST_EXPECT(
5051 env.le(keylet::offer(taker.id(), SeqProxy::rawSequence(takerSeq))) != nullptr);
5052 }
5053
5054 {
5055 // TakerPays side, MPT/MPT book: bob buys the whole tokenA supply
5056 // (10% fee) for tokenB. Rejected; the largest amount that fits is
5057 // accepted.
5058 auto const gwA = Account("gatewayA");
5059 auto const gwB = Account("gatewayB");
5060 auto const alice = Account("alice");
5061 auto const bob = Account("bob");
5062
5063 Env env{*this, features};
5064 env.fund(XRP(10'000), gwA, gwB, alice, bob);
5065 env.close();
5066
5067 MPTTester const tokenA{{
5068 .env = env,
5069 .issuer = gwA,
5070 .holders = {alice, bob},
5071 .transferFee = 10'000,
5072 .maxAmt = kMaxMpTokenAmount,
5073 }};
5074 MPTTester const tokenB{{.env = env, .issuer = gwB, .holders = {alice, bob}}};
5075
5076 std::int64_t const bobGets = 100'000'000'000'000'000LL;
5077 env(pay(gwB, bob, tokenB(bobGets)));
5078 env.close();
5079
5080 env(offer(bob, tokenA(maxAmt), tokenB(bobGets)), Ter(tecKILLED));
5081 env(offer(bob, tokenA(maxGross + 1), tokenB(bobGets)), Ter(tecKILLED));
5082 auto const bobSeq = env.seq(bob);
5083 env(offer(bob, tokenA(maxGross), tokenB(bobGets)));
5084 env.close();
5085 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
5086 env(offerCancel(bob, bobSeq));
5087 env.close();
5088
5089 // With a resting ask the rejected bid crosses it (bob pays no fee
5090 // as the buyer; alice, the seller, pays 10% on top), and bob's
5091 // remainder isn't placed.
5092 env(pay(gwA, alice, tokenA(1'100)));
5093 env.close();
5094 env(offer(alice, tokenB(1), tokenA(1'000)));
5095 env.close();
5096 auto const crossSeq = env.seq(bob);
5097 env(offer(bob, tokenA(maxAmt), tokenB(bobGets)));
5098 env.close();
5099 BEAST_EXPECT(env.balance(bob, tokenA) == tokenA(1'000));
5100 BEAST_EXPECT(env.balance(bob, tokenB) == tokenB(bobGets - 1));
5101 BEAST_EXPECT(env.balance(alice, tokenA) == tokenA(0));
5102 BEAST_EXPECT(env.balance(alice, tokenB) == tokenB(1));
5103 BEAST_EXPECT(
5104 env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(crossSeq))) == nullptr);
5105 }
5106
5107 {
5108 // If the crossing consumes enough of the bid, the remainder's
5109 // gross-up fits and the remainder rests.
5110 auto const gwA = Account("gatewayA");
5111 auto const gwB = Account("gatewayB");
5112 auto const alice = Account("alice");
5113 auto const bob = Account("bob");
5114
5115 Env env{*this, features};
5116 env.fund(XRP(10'000), gwA, gwB, alice, bob);
5117 env.close();
5118
5119 MPTTester const tokenA{{
5120 .env = env,
5121 .issuer = gwA,
5122 .holders = {alice, bob},
5123 .transferFee = 10'000,
5124 .maxAmt = kMaxMpTokenAmount,
5125 }};
5126 MPTTester const tokenB{{.env = env, .issuer = gwB, .holders = {alice, bob}}};
5127
5128 // bob bids the whole tokenA supply at about 83.85 tokenA per
5129 // tokenB. alice asks 1.5e18 tokenA at 100 per tokenB.
5130 std::int64_t const bobGets = 110'000'000'000'000'000LL;
5131 std::int64_t const aliceGets = 1'500'000'000'000'000'000LL;
5132 std::int64_t const alicePays = 15'000'000'000'000'000LL;
5133 env(pay(gwA, alice, tokenA(maxAmt)));
5134 env(pay(gwB, bob, tokenB(bobGets)));
5135 env.close();
5136
5137 env(offer(alice, tokenB(alicePays), tokenA(aliceGets)));
5138 env.close();
5139
5140 auto const bobSeq = env.seq(bob);
5141 env(offer(bob, tokenA(maxAmt), tokenB(bobGets)));
5142 env.close();
5143 BEAST_EXPECT(env.balance(bob, tokenA) == tokenA(aliceGets));
5144 BEAST_EXPECT(
5145 env.balance(alice, tokenA) == tokenA(maxAmt - aliceGets - (aliceGets / 10)));
5146 BEAST_EXPECT(env.balance(alice, tokenB) == tokenB(alicePays));
5147 // Remainder: TakerPays drops by what bob received, to 7.72e18,
5148 // whose 10% gross-up fits; TakerGets is rescaled by the bid's
5149 // quality to about 9.21e16.
5150 auto const sle = env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq)));
5151 if (BEAST_EXPECT(sle))
5152 {
5153 BEAST_EXPECT((*sle)[sfTakerPays] == tokenA(maxAmt - aliceGets));
5154 auto const gets = (*sle)[sfTakerGets].mpt().value();
5155 BEAST_EXPECT(gets > 92'000'000'000'000'000LL && gets < 92'200'000'000'000'000LL);
5156 }
5157 }
5158 }
5159
5160 void
5162 {
5163 // The following test verifies some correct but slightly surprising
5164 // behavior in offer crossing. The scenario:
5165 //
5166 // o An entity has created one or more offers.
5167 // o The entity creates another offer that can be directly crossed
5168 // (not autobridged) by the previously created offer(s).
5169 // o Rather than self crossing the offers, delete the old offer(s).
5170 //
5171 // See a more complete explanation in the comments for
5172 // BookOfferCrossingStep::limitSelfCrossQuality().
5173 //
5174 // Note that, in this particular example, one offer causes several
5175 // crossable offers (worth considerably more than the new offer)
5176 // to be removed from the book.
5177 using namespace jtx;
5178
5179 auto const gw = Account("gateway");
5180
5181 Env env{*this, features};
5182
5183 // The fee that's charged for transactions.
5184 auto const fee = env.current()->fees().base;
5185 auto const startBalance = XRP(1'000'000);
5186
5187 env.fund(startBalance + (fee * 5), gw);
5188 env.close();
5189
5190 MPT const usd = MPTTester({.env = env, .issuer = gw});
5191
5192 env(offer(gw, usd(60), XRP(600)));
5193 env.close();
5194 env(offer(gw, usd(60), XRP(600)));
5195 env.close();
5196 env(offer(gw, usd(60), XRP(600)));
5197 env.close();
5198
5199 // three offers + MPTokenIssuance
5200 env.require(Owners(gw, 4));
5201 env.require(Balance(gw, startBalance + fee));
5202
5203 auto gwOffers = offersOnAccount(env, gw);
5204 BEAST_EXPECT(gwOffers.size() == 3);
5205 for (auto const& offerPtr : gwOffers)
5206 {
5207 auto const& offer = *offerPtr;
5208 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5209 BEAST_EXPECT(offer[sfTakerGets] == XRP(600));
5210 BEAST_EXPECT(offer[sfTakerPays] == usd(60));
5211 }
5212
5213 // Since this offer crosses the first offers, the previous offers
5214 // will be deleted and this offer will be put on the order book.
5215 env(offer(gw, XRP(1'000), usd(100)));
5216 env.close();
5217 env.require(Owners(gw, 2));
5218 env.require(Offers(gw, 1));
5219 env.require(Balance(gw, startBalance));
5220
5221 gwOffers = offersOnAccount(env, gw);
5222 BEAST_EXPECT(gwOffers.size() == 1);
5223 for (auto const& offerPtr : gwOffers)
5224 {
5225 auto const& offer = *offerPtr;
5226 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5227 BEAST_EXPECT(offer[sfTakerGets] == usd(100));
5228 BEAST_EXPECT(offer[sfTakerPays] == XRP(1'000));
5229 }
5230 }
5231
5232 void
5234 {
5235 using namespace jtx;
5236
5237 auto const gw1 = Account("gateway1");
5238 auto const gw2 = Account("gateway2");
5239 auto const alice = Account("alice");
5240
5241 auto const test = [&](auto&& issue1, auto&& issue2) {
5242 Env env{*this, features};
5243
5244 env.fund(XRP(1'000'000), gw1, gw2);
5245 env.close();
5246
5247 auto const usd = issue1({.env = env, .token = "USD", .issuer = gw1});
5248 using TUsd = std::decay_t<decltype(usd)>;
5249 auto const eur = issue2({.env = env, .token = "EUR", .issuer = gw2});
5250 using TEur = std::decay_t<decltype(eur)>;
5251
5252 // The fee that's charged for transactions.
5253 auto const f = env.current()->fees().base;
5254
5255 // Test cases
5256 struct TestData
5257 {
5258 std::string acct; // Account operated on
5259 STAmount fundXRP; // XRP acct funded with
5260 STAmount fundUSD; // USD acct funded with
5261 STAmount fundEUR; // EUR acct funded with
5262 TER firstOfferTec; // tec code on first offer
5263 TER secondOfferTec; // tec code on second offer
5264 };
5265
5266 // clang-format off
5267 TestData const tests[]{
5268 // acct fundXRP fundUSD fundEUR firstOfferTec secondOfferTec
5269 {"ann", reserve(env, 3) + f * 4, usd(1000), eur(1000), tesSUCCESS, tesSUCCESS},
5270 {"bev", reserve(env, 3) + f * 4, usd( 1), eur(1000), tesSUCCESS, tesSUCCESS},
5271 {"cam", reserve(env, 3) + f * 4, usd(1000), eur( 1), tesSUCCESS, tesSUCCESS},
5272 {"deb", reserve(env, 3) + f * 4, usd( 0), eur( 1), tesSUCCESS, tecUNFUNDED_OFFER},
5273 {"eve", reserve(env, 3) + f * 4, usd( 1), eur( 0), tecUNFUNDED_OFFER, tesSUCCESS},
5274 {"flo", reserve(env, 3) + 0, usd(1000), eur(1000), tecINSUF_RESERVE_OFFER, tecINSUF_RESERVE_OFFER},
5275 };
5276 //clang-format on
5277
5278 for (auto const& t : tests)
5279 {
5280 auto const acct = Account{t.acct};
5281 env.fund(t.fundXRP, acct);
5282 env.close();
5283
5284 if constexpr (std::is_same_v<TUsd, MPT>)
5285 {
5286 auto musd = MPTTester(env, gw1, usd);
5287 musd.authorize({.account = acct});
5288 }
5289 else
5290 {
5291 env(trust(acct, usd(1'000)));
5292 env.close();
5293 }
5294 if constexpr (std::is_same_v<TEur, MPT>)
5295 {
5296 auto meur = MPTTester(env, gw2, eur);
5297 meur.authorize({.account = acct});
5298 }
5299 else
5300 {
5301 env(trust(acct, eur(1'000)));
5302 env.close();
5303 }
5304
5305 if (t.fundUSD > usd(0))
5306 env(pay(gw1, acct, t.fundUSD));
5307 if (t.fundEUR > eur(0))
5308 env(pay(gw2, acct, t.fundEUR));
5309 env.close();
5310
5311 env(offer(acct, usd(500), eur(600)), Ter(t.firstOfferTec));
5312 env.close();
5313 std::uint32_t const firstOfferSeq = env.seq(acct) - 1;
5314
5315 int offerCount = t.firstOfferTec == tesSUCCESS ? 1 : 0;
5316 env.require(Owners(acct, 2 + offerCount));
5317 env.require(Balance(acct, t.fundUSD));
5318 env.require(Balance(acct, t.fundEUR));
5319
5320 auto acctOffers = offersOnAccount(env, acct);
5321 BEAST_EXPECT(acctOffers.size() == offerCount);
5322 for (auto const& offerPtr : acctOffers)
5323 {
5324 auto const& offer = *offerPtr;
5325 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5326 BEAST_EXPECT(offer[sfTakerGets] == eur(600));
5327 BEAST_EXPECT(offer[sfTakerPays] == usd(500));
5328 }
5329
5330 env(offer(acct, eur(600), usd(500)), Ter(t.secondOfferTec));
5331 env.close();
5332 std::uint32_t const secondOfferSeq = env.seq(acct) - 1;
5333
5334 offerCount = t.secondOfferTec == tesSUCCESS ? 1 : offerCount;
5335 env.require(Owners(acct, 2 + offerCount));
5336 env.require(Balance(acct, t.fundUSD));
5337 env.require(Balance(acct, t.fundEUR));
5338
5339 acctOffers = offersOnAccount(env, acct);
5340 BEAST_EXPECT(acctOffers.size() == offerCount);
5341 for (auto const& offerPtr : acctOffers)
5342 {
5343 auto const& offer = *offerPtr;
5344 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5345 if (offer[sfSequence] == firstOfferSeq)
5346 {
5347 BEAST_EXPECT(offer[sfTakerGets] == eur(600));
5348 BEAST_EXPECT(offer[sfTakerPays] == usd(500));
5349 }
5350 else
5351 {
5352 BEAST_EXPECT(offer[sfTakerGets] == usd(500));
5353 BEAST_EXPECT(offer[sfTakerPays] == eur(600));
5354 }
5355 }
5356
5357 // Remove any offers from acct for the next pass.
5358 env(offerCancel(acct, firstOfferSeq));
5359 env.close();
5360 env(offerCancel(acct, secondOfferSeq));
5361 env.close();
5362 }
5363 };
5365 }
5366
5367 void
5369 {
5370 testcase("Self Cross Offer");
5371 testSelfCrossOffer1(features);
5372 testSelfCrossOffer2(features);
5373 }
5374
5375 void
5377 {
5378 // Folks who issue their own currency have, in effect, as many
5379 // funds as they are trusted for. This test used to fail because
5380 // self-issuing was not properly checked. Verify that it works
5381 // correctly now.
5382 using namespace jtx;
5383
5384 Env env{*this, features};
5385
5386 auto const alice = Account("alice");
5387 auto const bob = Account("bob");
5388 auto const f = env.current()->fees().base;
5389
5390 env.fund(XRP(50'000) + f, alice, bob);
5391 env.close();
5392
5393 MPT const usd = MPTTester({.env = env, .issuer = bob});
5394
5395 env(offer(alice, usd(5'000), XRP(50'000)));
5396 env.close();
5397
5398 // This offer should take alice's offer up to Alice's reserve.
5399 env(offer(bob, XRP(50'000), usd(5'000)));
5400 env.close();
5401
5402 // alice's offer should have been removed, since she's down to her
5403 // XRP reserve.
5404 env.require(Balance(alice, XRP(250)));
5405 env.require(Owners(alice, 1));
5406 env.require(MPTokens(alice, 1));
5407
5408 // However bob's offer should be in the ledger, since it was not
5409 // fully crossed.
5410 auto const bobOffers = offersOnAccount(env, bob);
5411 BEAST_EXPECT(bobOffers.size() == 1);
5412 for (auto const& offerPtr : bobOffers)
5413 {
5414 auto const& offer = *offerPtr;
5415 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5416 BEAST_EXPECT(offer[sfTakerGets] == usd(25));
5417 BEAST_EXPECT(offer[sfTakerPays] == XRP(250));
5418 }
5419 }
5420
5421 void
5423 {
5424 // The offer crossing code expects that a DirectStep is always
5425 // preceded by a BookStep. In one instance the default path
5426 // was not matching that assumption. Here we recreate that case
5427 // so we can prove the bug stays fixed.
5428 testcase("Direct to Direct path");
5429
5430 using namespace jtx;
5431 auto const ann = Account("ann");
5432 auto const bob = Account("bob");
5433 auto const cam = Account("cam");
5434
5435 auto const test = [&](auto&& issue1, auto&& issue2) {
5436 Env env{*this, features};
5437
5438 auto const fee = env.current()->fees().base;
5439 env.fund(reserve(env, 4) + (fee * 5), ann, bob, cam);
5440 env.close();
5441
5442 auto const aBux = issue1(
5443 {.env = env, .token = "AUX", .issuer = ann, .holders = {cam}});
5444 auto const bBux = issue2(
5445 {.env = env,
5446 .token = "BUX",
5447 .issuer = bob,
5448 .holders = {ann, cam},});
5449
5450 env(pay(ann, cam, aBux(35)));
5451 env(pay(bob, cam, bBux(35)));
5452
5453 env(offer(bob, aBux(30), bBux(30)));
5454 env.close();
5455
5456 // cam puts an offer on the books that her upcoming offer could
5457 // cross. But this offer should be deleted, not crossed, by her
5458 // upcoming offer.
5459 env(offer(cam, aBux(29), bBux(30), tfPassive));
5460 env.close();
5461 env.require(Balance(cam, aBux(35)));
5462 env.require(Balance(cam, bBux(35)));
5463 env.require(Offers(cam, 1));
5464
5465 // This offer caused the assert.
5466 env(offer(cam, bBux(30), aBux(30)));
5467 env.close();
5468
5469 env.require(Balance(bob, aBux(30)));
5470 env.require(Balance(cam, aBux(5)));
5471 env.require(Balance(cam, bBux(65)));
5472 env.require(Offers(cam, 0));
5473 };
5475 }
5476
5477 void
5479 {
5480 // The Flow offer crossing code used to assert if an offer was made
5481 // for more XRP than the offering account held. This unit test
5482 // reproduces that failing case.
5483 testcase("Self crossing low quality offer");
5484
5485 using namespace jtx;
5486
5487 Env env{*this, features};
5488
5489 auto const ann = Account("ann");
5490 auto const gw = Account("gateway");
5491
5492 auto const fee = env.current()->fees().base;
5493 env.fund(reserve(env, 2) + drops(9999640) + fee, ann);
5494 env.fund(reserve(env, 2) + (fee * 4), gw);
5495 env.close();
5496
5497 MPT const btc = MPTTester(
5498 {.env = env, .issuer = gw, .holders = {ann}, .transferFee = 2'000});
5499
5500 env(pay(gw, ann, btc(2'856)));
5501 env.close();
5502
5503 env(offer(ann, drops(365'611'702'030), btc(5'713)));
5504 env.close();
5505
5506 // This offer caused the assert.
5507 env(offer(ann, btc(687), drops(20'000'000'000)),
5509 }
5510
5511 void
5513 {
5514 // The Flow offer crossing code had a case where it was not rounding
5515 // the offer crossing correctly after a partial crossing. The
5516 // failing case was found on the network. Here we add the case to
5517 // the unit tests.
5518 testcase("Offer In Scaling");
5519
5520 using namespace jtx;
5521
5522 Env env{*this, features};
5523
5524 auto const gw = Account("gateway");
5525 auto const alice = Account("alice");
5526 auto const bob = Account("bob");
5527
5528 auto const fee = env.current()->fees().base;
5529 env.fund(reserve(env, 2) + drops(400'000'000'000) + fee, alice, bob);
5530 env.fund(reserve(env, 2) + (fee * 4), gw);
5531 env.close();
5532
5533 MPT const cny = MPTTester({.env = env, .issuer = gw, .holders = {bob}});
5534
5535 env(pay(gw, bob, cny(3'000'000)));
5536 env.close();
5537
5538 env(offer(bob, drops(5'400'000'000), cny(2'160'540)));
5539 env.close();
5540
5541 // This offer did not round result of partial crossing correctly.
5542 env(offer(alice, cny(135'620'001), drops(339'000'000'000)));
5543 env.close();
5544
5545 auto const aliceOffers = offersOnAccount(env, alice);
5546 BEAST_EXPECT(aliceOffers.size() == 1);
5547 for (auto const& offerPtr : aliceOffers)
5548 {
5549 auto const& offer = *offerPtr;
5550 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5551 BEAST_EXPECT(offer[sfTakerGets] == drops(333'599'446'582));
5552 BEAST_EXPECT(offer[sfTakerPays] == cny(13'3459'461));
5553 }
5554 }
5555
5556 void
5558 {
5559 // After adding the previous case, there were still failing rounding
5560 // cases in Flow offer crossing. This one was because the gateway
5561 // transfer rate was not being correctly handled.
5562 testcase("Offer In Scaling With Xfer Rate");
5563
5564 using namespace jtx;
5565 auto const gw = Account("gateway");
5566 auto const alice = Account("alice");
5567 auto const bob = Account("bob");
5568
5569 auto const test = [&](auto&& issue1, auto&& issue2) {
5570 Env env{*this, features};
5571
5572 auto const fee = env.current()->fees().base;
5573 env.fund(
5574 reserve(env, 2) + drops(400'000'000'000) + fee,
5575 alice,
5576 bob);
5577 env.fund(reserve(env, 2) + (fee * 4), gw);
5578 env.close();
5579
5580 auto const jpy = issue1(
5581 {.env = env,
5582 .token = "JPY",
5583 .issuer = gw,
5584 .holders = {alice},
5586 .transferFee = 2'000,});
5587 auto const btc = issue2(
5588 {.env = env,
5589 .token = "BTC",
5590 .issuer = gw,
5591 .holders = {bob},
5593 .transferFee = 2'000,});
5594
5595 env(pay(gw, alice, jpy(3'699'034'802'280'317)));
5596 env(pay(gw, bob, btc(115'672'255'914'031'100)));
5597 env.close();
5598
5599 env(offer(
5600 bob, jpy(1'241'913'390'770'747), btc(1'969'825'690'469'254)));
5601 env.close();
5602
5603 // This offer did not round result of partial crossing correctly.
5604 env(offer(
5605 alice, btc(5'507'568'706'427'876), jpy(3'472'696'773'391'072)));
5606 env.close();
5607
5608 auto const aliceOffers = offersOnAccount(env, alice);
5609 BEAST_EXPECT(aliceOffers.size() == 1);
5610 for (auto const& offerPtr : aliceOffers)
5611 {
5612 auto const& offer = *offerPtr;
5613 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
5614 // This test is similar to corresponding Offer_test, except
5615 // that JPY is scaled by 10**12 and BTC is scaled by 10**17.
5616 // There is a difference in the expected results.
5617 // Offer_test expects values
5618 // takerGets:2230.682446713524, takerPays: 0.035378
5619 // MPT test has the same order of magnitude for the scaled
5620 // values and the first 5 digits match. Is the difference due to
5621 // int arithmetics?
5622 BEAST_EXPECT(offer[sfTakerGets] == jpy(2'230'659'191'281'247));
5623 BEAST_EXPECT(offer[sfTakerPays] == btc(3'537'743'015'958'622));
5624 }
5625 };
5627 }
5628
5629 void
5631 {
5632 testcase("Self Pay Xfer Fee");
5633 // The old offer crossing code does not charge a transfer fee
5634 // if alice pays alice. That's different from how payments work.
5635 // Payments always charge a transfer fee even if the money is staying
5636 // in the same hands.
5637 //
5638 // What's an example where alice pays alice? There are three actors:
5639 // gw, alice, and bob.
5640 //
5641 // 1. gw issues BTC and USD. gw charges a 0.2% transfer fee.
5642 //
5643 // 2. alice makes an offer to buy XRP and sell USD.
5644 // 3. bob makes an offer to buy BTC and sell XRP.
5645 //
5646 // 4. alice now makes an offer to sell BTC and buy USD.
5647 //
5648 // This last offer crosses using auto-bridging.
5649 // o alice's last offer sells BTC to...
5650 // o bob' offer which takes alice's BTC and sells XRP to...
5651 // o alice's first offer which takes bob's XRP and sells USD to...
5652 // o alice's last offer.
5653 //
5654 // So alice sells USD to herself.
5655 //
5656 // There are six cases that we need to test:
5657 // o alice crosses her own offer on the first leg (BTC).
5658 // o alice crosses her own offer on the second leg (USD).
5659 // o alice crosses her own offers on both legs.
5660 // All three cases need to be tested:
5661 // o In reverse (alice has enough BTC to cover her offer) and
5662 // o Forward (alice owns less BTC than is in her final offer.
5663 //
5664 // It turns out that two of the forward cases fail for a different
5665 // reason. They are therefore commented out here, But they are
5666 // revisited in the testSelfPayUnlimitedFunds() unit test.
5667
5668 using namespace jtx;
5669 auto const gw = Account("gw");
5670
5671 auto const test = [&](auto&& issue1, auto&& issue2) {
5672 Env env{*this, features};
5673 auto const baseFee = env.current()->fees().base.drops();
5674
5675 auto const startXrpBalance = XRP(4'000'000);
5676
5677 env.fund(startXrpBalance, gw);
5678 env.close();
5679
5680 auto const btc = issue1(
5681 {.env = env,
5682 .token = "BTC",
5683 .issuer = gw,
5684 .transferFee = 25'000,});
5685 using TBtc = std::decay_t<decltype(btc)>;
5686 env.close();
5687 auto const usd = issue2(
5688 {.env = env,
5689 .token = "USD",
5690 .issuer = gw,
5691 .transferFee = 25'000,});
5692 using TUsd = std::decay_t<decltype(usd)>;
5693 env.close();
5694
5695 // Test cases
5696 struct Actor
5697 {
5698 Account acct;
5699 int offers{}; // offers on account after crossing
5700 PrettyAmount xrp; // final expected after crossing
5701 PrettyAmount btc; // final expected after crossing
5702 PrettyAmount usd; // final expected after crossing
5703 };
5704 struct TestData
5705 {
5706 // The first three integers give the *index* in actors
5707 // to assign each of the three roles. By using indices it is
5708 // easy for alice to own the offer in the first leg, the second
5709 // leg, or both.
5710 std::size_t self{};
5711 std::size_t leg0{};
5712 std::size_t leg1{};
5713 PrettyAmount btcStart;
5714 std::vector<Actor> actors;
5715 };
5716
5717 // clang-format off
5718 TestData const tests[]{
5719 // btcStart --------------------- actor[0] --------------------- -------------------- actor[1] -------------------
5720 {0, 0, 1, btc(200), {{"ann", 0, drops(3900000'000000 - (4 * baseFee)), btc(200), usd(3000)}, {"abe", 0, drops(4100000'000000 - (3 * baseFee)), btc( 0), usd(750)}}}, // no BTC xfer fee
5721 {0, 1, 0, btc(200), {{"bev", 0, drops(4100000'000000 - (4 * baseFee)), btc( 75), usd(2000)}, {"bob", 0, drops(3900000'000000 - (3 * baseFee)), btc(100), usd( 0)}}}, // no USD xfer fee
5722 {0, 0, 0, btc(200), {{"cam", 0, drops(4000000'000000 - (5 * baseFee)), btc(200), usd(2000)} }}, // no xfer fee
5723 {0, 1, 0, btc( 50), {{"deb", 1, drops(4040000'000000 - (4 * baseFee)), btc( 0), usd(2000)}, {"dan", 1, drops(3960000'000000 - (3 * baseFee)), btc( 40), usd( 0)}}}, // no USD xfer fee
5724 };
5725 // clang-format on
5726
5727 for (auto const& t : tests)
5728 {
5729 Account const& self = t.actors[t.self].acct;
5730 Account const& leg0 = t.actors[t.leg0].acct;
5731 Account const& leg1 = t.actors[t.leg1].acct;
5732
5733 for (auto const& actor : t.actors)
5734 {
5735 env.fund(XRP(4'000'000), actor.acct);
5736 env.close();
5737
5738 if constexpr (std::is_same_v<TBtc, MPT>)
5739 {
5740 auto mbtc = MPTTester(env, gw, btc);
5741 mbtc.authorize({.account = actor.acct});
5742 }
5743 else
5744 {
5745 env(trust(actor.acct, btc(400)));
5746 env.close();
5747 }
5748 if constexpr (std::is_same_v<TUsd, MPT>)
5749 {
5750 auto musd = MPTTester(env, gw, usd);
5751 musd.authorize({.account = actor.acct});
5752 }
5753 else
5754 {
5755 env(trust(actor.acct, usd(8000)));
5756 env.close();
5757 }
5758 env.close();
5759 }
5760
5761 env(pay(gw, self, t.btcStart));
5762 env(pay(gw, self, usd(2'000)));
5763 if (self.id() != leg1.id())
5764 env(pay(gw, leg1, usd(2'000)));
5765 env.close();
5766
5767 // Get the initial offers in place. Remember their sequences
5768 // so we can delete them later.
5769 env(offer(leg0, btc(100), XRP(100'000), tfPassive));
5770 env.close();
5771 std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1;
5772
5773 env(offer(leg1, XRP(100'000), usd(1'000), tfPassive));
5774 env.close();
5775 std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1;
5776
5777 // This is the offer that matters.
5778 env(offer(self, usd(1'000), btc(100)));
5779 env.close();
5780 std::uint32_t const selfOfferSeq = env.seq(self) - 1;
5781
5782 // Verify results.
5783 for (auto const& actor : t.actors)
5784 {
5785 // Sometimes Taker crossing gets lazy about deleting offers.
5786 // Treat an empty offer as though it is deleted.
5787 auto actorOffers = offersOnAccount(env, actor.acct);
5788 auto const offerCount = std::distance(
5789 actorOffers.begin(),
5791 return (*offer)[sfTakerGets].signum() == 0;
5792 }).begin());
5793 BEAST_EXPECT(offerCount == actor.offers);
5794
5795 env.require(Balance(actor.acct, actor.xrp));
5796 env.require(Balance(actor.acct, actor.btc));
5797 env.require(Balance(actor.acct, actor.usd));
5798 }
5799 // Remove any offers that might be left hanging around. They
5800 // could bollix up later loops.
5801 env(offerCancel(leg0, leg0OfferSeq));
5802 env.close();
5803 env(offerCancel(leg1, leg1OfferSeq));
5804 env.close();
5805 env(offerCancel(self, selfOfferSeq));
5806 env.close();
5807 }
5808 };
5810 }
5811
5812 void
5814 {
5815 testcase("Self Pay Unlimited Funds");
5816 // The Taker offer crossing code recognized when Alice was paying
5817 // Alice the same denomination. In this case, as long as Alice
5818 // has a little bit of that denomination, it treats Alice as though
5819 // she has unlimited funds in that denomination.
5820 //
5821 // Huh? What kind of sense does that make?
5822 //
5823 // One way to think about it is to break a single payment into a
5824 // series of very small payments executed sequentially but very
5825 // quickly. Alice needs to pay herself 1 USD, but she only has
5826 // 0.01 USD. Alice says, "Hey Alice, let me pay you a penny."
5827 // Alice does this, taking the penny out of her pocket and then
5828 // putting it back in her pocket. Then she says, "Hey Alice,
5829 // I found another penny. I can pay you another penny." Repeat
5830 // these steps 100 times and Alice has paid herself 1 USD even though
5831 // she only owns 0.01 USD.
5832 //
5833 // That's all very nice, but the payment code does not support this
5834 // optimization. In part that's because the payment code can
5835 // operate on a whole batch of offers. As a matter of fact, it can
5836 // deal in two consecutive batches of offers. It would take a great
5837 // deal of sorting out to figure out which offers in the two batches
5838 // had the same owner and give them special processing. And,
5839 // honestly, it's a weird little corner case.
5840 //
5841 // So, since Flow offer crossing uses the payments engine, Flow
5842 // offer crossing no longer supports this optimization.
5843 //
5844 // The following test shows the difference in the behaviors between
5845 // Taker offer crossing and Flow offer crossing.
5846
5847 using namespace jtx;
5848 auto const gw = Account("gw");
5849
5850 auto const test = [&](auto&& issue1, auto&& issue2) {
5851 Env env{*this, features};
5852 auto const baseFee = env.current()->fees().base.drops();
5853
5854 auto const startXrpBalance = XRP(4'000'000);
5855
5856 env.fund(startXrpBalance, gw);
5857 env.close();
5858
5859 auto const btc = issue1(
5860 {.env = env, .token = "BTC", .issuer = gw, .limit = 40, .transferFee = 25'000});
5861 using TBtc = std::decay_t<decltype(btc)>;
5862 auto const usd = issue2(
5863 {.env = env, .token = "USD", .issuer = gw, .limit = 8'000, .transferFee = 25'000});
5864 using TUsd = std::decay_t<decltype(usd)>;
5865 env.close();
5866
5867 // Test cases
5868 struct Actor
5869 {
5870 Account acct;
5871 int offers{}; // offers on account after crossing
5872 PrettyAmount xrp; // final expected after crossing
5873 PrettyAmount btc; // final expected after crossing
5874 PrettyAmount usd; // final expected after crossing
5875 };
5876 struct TestData
5877 {
5878 // The first three integers give the *index* in actors
5879 // to assign each of the three roles. By using indices it is
5880 // easy for alice to own the offer in the first leg, the second
5881 // leg, or both.
5882 std::size_t self{};
5883 std::size_t leg0{};
5884 std::size_t leg1{};
5885 PrettyAmount btcStart;
5886 std::vector<Actor> actors;
5887 };
5888
5889 // clang-format off
5890 TestData const flowTests[]{
5891 // btcStart ------------------- actor[0] -------------------- ------------------- actor[1] --------------------
5892 {0, 0, 1, btc(5), {{"gay", 1, drops(3950000'000000 - (4 * baseFee)), btc(5), usd (2500)}, {"gar", 1, drops(4050000'000000 - (3 * baseFee)), btc(0), usd(1375)}}}, // no BTC xfer fee
5893 {0, 0, 0, btc(5), {{"hye", 2, drops(4000000'000000 - (5 * baseFee)), btc(5), usd (2000)} }}, // no xfer fee
5894 };
5895 // clang-format on
5896
5897 for (auto const& t : flowTests)
5898 {
5899 Account const& self = t.actors[t.self].acct;
5900 Account const& leg0 = t.actors[t.leg0].acct;
5901 Account const& leg1 = t.actors[t.leg1].acct;
5902
5903 for (auto const& actor : t.actors)
5904 {
5905 env.fund(XRP(4'000'000), actor.acct);
5906 env.close();
5907
5908 if constexpr (std::is_same_v<TBtc, MPT>)
5909 {
5910 auto mbtc = MPTTester(env, gw, btc);
5911 mbtc.authorize({.account = actor.acct});
5912 }
5913 else
5914 {
5915 env(trust(actor.acct, btc(40)));
5916 env.close();
5917 }
5918 if constexpr (std::is_same_v<TUsd, MPT>)
5919 {
5920 auto musd = MPTTester(env, gw, usd);
5921 musd.authorize({.account = actor.acct});
5922 }
5923 else
5924 {
5925 env(trust(actor.acct, usd(8'000)));
5926 env.close();
5927 }
5928 }
5929
5930 env(pay(gw, self, t.btcStart));
5931 env(pay(gw, self, usd(2'000)));
5932 if (self.id() != leg1.id())
5933 env(pay(gw, leg1, usd(2'000)));
5934 env.close();
5935
5936 // Get the initial offers in place. Remember their sequences
5937 // so we can delete them later.
5938 env(offer(leg0, btc(10), XRP(100'000), tfPassive));
5939 env.close();
5940 std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1;
5941
5942 env(offer(leg1, XRP(100'000), usd(1'000), tfPassive));
5943 env.close();
5944 std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1;
5945
5946 // This is the offer that matters.
5947 env(offer(self, usd(1'000), btc(10)));
5948 env.close();
5949 std::uint32_t const selfOfferSeq = env.seq(self) - 1;
5950
5951 // Verify results.
5952 for (auto const& actor : t.actors)
5953 {
5954 // Sometimes Taker offer crossing gets lazy about deleting
5955 // offers. Treat an empty offer as though it is deleted.
5956 auto actorOffers = offersOnAccount(env, actor.acct);
5957 auto const offerCount = std::distance(
5958 actorOffers.begin(),
5960 return (*offer)[sfTakerGets].signum() == 0;
5961 }).begin());
5962 BEAST_EXPECT(offerCount == actor.offers);
5963
5964 env.require(Balance(actor.acct, actor.xrp));
5965 env.require(Balance(actor.acct, actor.btc));
5966 env.require(Balance(actor.acct, actor.usd));
5967 }
5968 // Remove any offers that might be left hanging around. They
5969 // could bollix up later loops.
5970 env(offerCancel(leg0, leg0OfferSeq));
5971 env.close();
5972 env(offerCancel(leg1, leg1OfferSeq));
5973 env.close();
5974 env(offerCancel(self, selfOfferSeq));
5975 env.close();
5976 }
5977 };
5979 }
5980
5981 void
5983 {
5984 testcase("lsfRequireAuth");
5985
5986 using namespace jtx;
5987
5988 Env env{*this, features};
5989
5990 auto const gw = Account("gw");
5991 auto const alice = Account("alice");
5992 auto const bob = Account("bob");
5993
5994 env.fund(XRP(400'000), gw, alice, bob);
5995 env.close();
5996
5997 // GW requires authorization for holders of its IOUs
5998 auto gwMUSD =
5999 MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth});
6000 MPT const gwUSD = gwMUSD;
6001
6002 // Have gw authorize bob and alice
6003 gwMUSD.authorize({.account = alice});
6004 gwMUSD.authorize({.account = gw, .holder = alice});
6005 gwMUSD.authorize({.account = bob});
6006 gwMUSD.authorize({.account = gw, .holder = bob});
6007 // Alice is able to place the offer since the GW has authorized her
6008 env(offer(alice, gwUSD(40), XRP(4'000)));
6009 env.close();
6010
6011 env.require(Offers(alice, 1));
6012 env.require(Balance(alice, gwUSD(0)));
6013
6014 env(pay(gw, bob, gwUSD(50)));
6015 env.close();
6016
6017 env.require(Balance(bob, gwUSD(50)));
6018
6019 // Bob's offer should cross Alice's
6020 env(offer(bob, XRP(4'000), gwUSD(40)));
6021 env.close();
6022
6023 env.require(Offers(alice, 0));
6024 env.require(Balance(alice, gwUSD(40)));
6025
6026 env.require(Offers(bob, 0));
6027 env.require(Balance(bob, gwUSD(10)));
6028 }
6029
6030 void
6032 {
6033 testcase("Missing Auth");
6034 // 1. gw creates MPTokenIssuance, which requires authorization.
6035 // alice creates an offer to acquire USD/gw, an asset for which
6036 // she does not own MPToken. This offer fails since alice
6037 // doesn't own MPToken and authorization is required.
6038 //
6039 // 2. Next, alice creates MPT, but it's not authorized.
6040 // alice attempts to create an offer and again fails.
6041 //
6042 // 3. Finally, gw authorizes alice to own USD/gw.
6043 // At this point alice successfully
6044 // creates and crosses an offer for USD/gw.
6045
6046 using namespace jtx;
6047
6048 Env env{*this, features};
6049
6050 auto const gw = Account("gw");
6051 auto const alice = Account("alice");
6052 auto const bob = Account("bob");
6053
6054 env.fund(XRP(400'000), gw, alice, bob);
6055 env.close();
6056
6057 auto gwMUSD =
6058 MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth});
6059 MPT const gwUSD = gwMUSD;
6060
6061 // alice can't create an offer because alice doesn't own
6062 // MPToken and MPTokenIssuance requires authorization
6063 env(offer(alice, gwUSD(40), XRP(4'000)), Ter(tecNO_AUTH));
6064 env.close();
6065
6066 env.require(Offers(alice, 0));
6067 env.require(Balance(alice, gwUSD(kNone)));
6068
6069 gwMUSD.authorize({.account = bob});
6070 gwMUSD.authorize({.account = gw, .holder = bob});
6071
6072 env(pay(gw, bob, gwUSD(50)));
6073 env.close();
6074 env.require(Balance(bob, gwUSD(50)));
6075
6076 // bob can create an offer since bob owns MPToken
6077 // and it is authorized.
6078 env(offer(bob, XRP(4'000), gwUSD(40)));
6079 env.close();
6080 std::uint32_t const bobOfferSeq = env.seq(bob) - 1;
6081
6082 env.require(Offers(alice, 0));
6083
6084 // alice creates MPToken, which is still not authorized. alice
6085 // should still not be able to create an offer for USD/gw.
6086 gwMUSD.authorize({.account = alice});
6087
6088 env(offer(alice, gwUSD(40), XRP(4'000)), Ter(tecNO_AUTH));
6089 env.close();
6090
6091 env.require(Offers(alice, 0));
6092 env.require(Balance(alice, gwUSD(0)));
6093
6094 env.require(Offers(bob, 1));
6095 env.require(Balance(bob, gwUSD(50)));
6096
6097 // Delete bob's offer so alice can create an offer without crossing.
6098 env(offerCancel(bob, bobOfferSeq));
6099 env.close();
6100 env.require(Offers(bob, 0));
6101
6102 // Finally, gw authorizes alice. Now alice's
6103 // offer should succeed.
6104 gwMUSD.authorize({.account = gw, .holder = alice});
6105
6106 env(offer(alice, gwUSD(40), XRP(4'000)));
6107 env.close();
6108
6109 env.require(Offers(alice, 1));
6110
6111 // Now bob creates his offer again. alice's offer should cross.
6112 env(offer(bob, XRP(4'000), gwUSD(40)));
6113 env.close();
6114
6115 env.require(Offers(alice, 0));
6116 env.require(Balance(alice, gwUSD(40)));
6117
6118 env.require(Offers(bob, 0));
6119 env.require(Balance(bob, gwUSD(10)));
6120 }
6121
6122 void
6124 {
6125 testcase("Self Auth");
6126
6127 using namespace jtx;
6128
6129 Env env{*this, features};
6130
6131 auto const gw = Account("gw");
6132 auto const alice = Account("alice");
6133
6134 env.fund(XRP(400'000), gw, alice);
6135 env.close();
6136
6137 auto gwMUSD =
6138 MPTTester({.env = env, .issuer = gw, .flags = kMptDexFlags | tfMPTRequireAuth});
6139 MPT const gwUSD = gwMUSD;
6140
6141 // Test that gw can create an offer to buy gw's currency.
6142 env(offer(gw, gwUSD(40), XRP(4'000)));
6143 env.close();
6144 std::uint32_t const gwOfferSeq = env.seq(gw) - 1;
6145 env.require(Offers(gw, 1));
6146
6147 // Cancel gw's offer
6148 env(offerCancel(gw, gwOfferSeq));
6149 env.close();
6150 env.require(Offers(gw, 0));
6151
6152 // Before DepositPreauth an account with lsfRequireAuth set could not
6153 // create an offer to buy their own currency. After DepositPreauth
6154 // they can.
6155 env(offer(gw, gwUSD(40), XRP(4'000)));
6156 env.close();
6157
6158 env.require(Offers(gw, 1));
6159
6160 // The rest of the test verifies DepositPreauth behavior.
6161
6162 // Create/authorize alice's MPToken
6163 gwMUSD.authorize({.account = alice});
6164 gwMUSD.authorize({.account = gw, .holder = alice});
6165
6166 env(pay(gw, alice, gwUSD(50)));
6167 env.close();
6168
6169 env.require(Balance(alice, gwUSD(50)));
6170
6171 // alice's offer should cross gw's
6172 env(offer(alice, XRP(4'000), gwUSD(40)));
6173 env.close();
6174
6175 env.require(Offers(alice, 0));
6176 env.require(Balance(alice, gwUSD(10)));
6177
6178 env.require(Offers(gw, 0));
6179 }
6180
6181 void
6183 {
6184 // Show that an offer who's issuer has been deleted cannot be crossed.
6185 using namespace jtx;
6186
6187 testcase("Deleted offer issuer");
6188
6189 auto const mpTokenExists =
6190 [](jtx::Env const& env, AccountID const& account, MPTID const& issuanceID) -> bool {
6191 return bool(env.le(keylet::mptoken(issuanceID, account)));
6192 };
6193
6194 Account const alice("alice");
6195 Account const becky("becky");
6196 Account const carol("carol");
6197 Account const gw("gateway");
6198
6199 Env env{*this, features};
6200
6201 env.fund(XRP(10'000), alice, becky, carol, noripple(gw));
6202
6203 auto musd = MPTTester({.env = env, .issuer = gw});
6204 MPT const usd = musd;
6205
6206 musd.authorize({.account = becky});
6207 BEAST_EXPECT(mpTokenExists(env, becky, usd.issuanceID));
6208 env(pay(gw, becky, usd(5)));
6209 env.close();
6210
6211 auto mbux = MPTTester({.env = env, .issuer = alice});
6212 MPT const bux = mbux;
6213
6214 // Make offers that produce USD and can be crossed two ways:
6215 // direct XRP -> USD
6216 // direct BUX -> USD
6217 env(offer(becky, XRP(2), usd(2)), Txflags(tfPassive));
6218 std::uint32_t const beckyBuxUsdSeq{env.seq(becky)};
6219 env(offer(becky, bux(3), usd(3)), Txflags(tfPassive));
6220 env.close();
6221
6222 // becky keeps the offers, but removes MPT.
6223 env(pay(becky, gw, usd(5)));
6224 musd.authorize({.account = becky, .flags = tfMPTUnauthorize});
6225
6226 BEAST_EXPECT(!mpTokenExists(env, becky, usd.issuanceID));
6227 BEAST_EXPECT(isOffer(env, becky, XRP(2), usd(2)));
6228 BEAST_EXPECT(isOffer(env, becky, bux(3), usd(3)));
6229
6230 // Have to delete MPTokenIssuance in order to delete
6231 // the issuer account.
6232 musd.destroy({});
6233
6234 // Delete gw's account.
6235 {
6236 // The ledger sequence needs to far enough ahead of the account
6237 // sequence before the account can be deleted.
6238 int const delta = [&env, &gw, openLedgerSeq = env.current()->seq()] -> int {
6239 std::uint32_t const gwSeq{env.seq(gw)};
6240 if (gwSeq + 255 > openLedgerSeq)
6241 return gwSeq - openLedgerSeq + 255;
6242 return 0;
6243 }();
6244
6245 for (int i = 0; i < delta; ++i)
6246 env.close();
6247
6248 // Account deletion has a high fee. Account for that.
6249 env(acctdelete(gw, alice), Fee(drops(env.current()->fees().increment)));
6250 env.close();
6251
6252 // Verify that gw's account root is gone from the ledger.
6253 BEAST_EXPECT(!env.closed()->exists(keylet::account(gw.id())));
6254 }
6255
6256 // alice crosses becky's first offer. The offer create fails because
6257 // the USD issuer is not in the ledger.
6258 env(offer(alice, usd(2), XRP(2)), Ter(tecNO_ISSUER));
6259 env.close();
6260 env.require(Offers(alice, 0));
6261 BEAST_EXPECT(isOffer(env, becky, XRP(2), usd(2)));
6262 BEAST_EXPECT(isOffer(env, becky, bux(3), usd(3)));
6263
6264 // alice crosses becky's second offer. Again, the offer create fails
6265 // because the USD issuer is not in the ledger.
6266 env(offer(alice, usd(3), bux(3)), Ter(tecNO_ISSUER));
6267 env.require(Offers(alice, 0));
6268 BEAST_EXPECT(isOffer(env, becky, XRP(2), usd(2)));
6269 BEAST_EXPECT(isOffer(env, becky, bux(3), usd(3)));
6270
6271 // Cancel becky's BUX -> USD offer so we can try auto-bridging.
6272 env(offerCancel(becky, beckyBuxUsdSeq));
6273 env.close();
6274 BEAST_EXPECT(!isOffer(env, becky, bux(3), usd(3)));
6275
6276 // alice creates an offer that can be auto-bridged with becky's
6277 // remaining offer.
6278 mbux.authorize({.account = carol});
6279 env(pay(alice, carol, bux(2)));
6280
6281 env(offer(alice, bux(2), XRP(2)));
6282 env.close();
6283
6284 // carol attempts the auto-bridge. Again, the offer create fails
6285 // because the USD issuer is not in the ledger.
6286 env(offer(carol, usd(2), bux(2)), Ter(tecNO_ISSUER));
6287 env.close();
6288 BEAST_EXPECT(isOffer(env, alice, bux(2), XRP(2)));
6289 BEAST_EXPECT(isOffer(env, becky, XRP(2), usd(2)));
6290 }
6291
6292 // Helper function that returns offers on an account sorted by sequence.
6295 {
6297 std::ranges::sort(offers, [](SLE::ConstRef rhs, SLE::ConstRef lhs) {
6298 return (*rhs)[sfSequence] < (*lhs)[sfSequence];
6299 });
6300 return offers;
6301 }
6302
6303 void
6305 {
6306 testcase("Ticket Offers");
6307
6308 using namespace jtx;
6309
6310 // Two goals for this test.
6311 //
6312 // o Verify that offers can be created using tickets.
6313 //
6314 // o Show that offers in the _same_ order book remain in
6315 // chronological order regardless of sequence/ticket numbers.
6316 Env env{*this, features};
6317 auto const gw = Account{"gateway"};
6318 auto const alice = Account{"alice"};
6319 auto const bob = Account{"bob"};
6320
6321 env.fund(XRP(10'000), gw, alice, bob);
6322 env.close();
6323
6324 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
6325
6326 env(pay(gw, alice, usd(200)));
6327 env.close();
6328
6329 // Create four offers from the same account with identical quality
6330 // so they go in the same order book. Each offer goes in a different
6331 // ledger so the chronology is clear.
6332 std::uint32_t const offerId0{env.seq(alice)};
6333 env(offer(alice, XRP(50), usd(50)));
6334 env.close();
6335
6336 // Create two tickets.
6337 std::uint32_t const ticketSeq{env.seq(alice) + 1};
6338 env(ticket::create(alice, 2));
6339 env.close();
6340
6341 // Create another sequence-based offer.
6342 std::uint32_t const offerId1{env.seq(alice)};
6343 BEAST_EXPECT(offerId1 == offerId0 + 4);
6344 env(offer(alice, XRP(50), usd(50)));
6345 env.close();
6346
6347 // Create two ticket based offers in reverse order.
6348 std::uint32_t const offerId2{ticketSeq + 1};
6349 env(offer(alice, XRP(50), usd(50)), ticket::Use(offerId2));
6350 env.close();
6351
6352 // Create the last offer.
6353 std::uint32_t const offerId3{ticketSeq};
6354 env(offer(alice, XRP(50), usd(50)), ticket::Use(offerId3));
6355 env.close();
6356
6357 // Verify that all of alice's offers are present.
6358 {
6359 auto offers = sortedOffersOnAccount(env, alice);
6360 BEAST_EXPECT(offers.size() == 4);
6361 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId0);
6362 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId3);
6363 BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId2);
6364 BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerId1);
6365 env.require(Balance(alice, usd(200)));
6366 env.require(Owners(alice, 5));
6367 }
6368
6369 // Cross alice's first offer.
6370 env(offer(bob, usd(50), XRP(50)));
6371 env.close();
6372
6373 // Verify that the first offer alice created was consumed.
6374 {
6375 auto offers = sortedOffersOnAccount(env, alice);
6376 BEAST_EXPECT(offers.size() == 3);
6377 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId3);
6378 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId2);
6379 BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId1);
6380 }
6381
6382 // Cross alice's second offer.
6383 env(offer(bob, usd(50), XRP(50)));
6384 env.close();
6385
6386 // Verify that the second offer alice created was consumed.
6387 {
6388 auto offers = sortedOffersOnAccount(env, alice);
6389 BEAST_EXPECT(offers.size() == 2);
6390 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId3);
6391 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId2);
6392 }
6393
6394 // Cross alice's third offer.
6395 env(offer(bob, usd(50), XRP(50)));
6396 env.close();
6397
6398 // Verify that the third offer alice created was consumed.
6399 {
6400 auto offers = sortedOffersOnAccount(env, alice);
6401 BEAST_EXPECT(offers.size() == 1);
6402 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId3);
6403 }
6404
6405 // Cross alice's last offer.
6406 env(offer(bob, usd(50), XRP(50)));
6407 env.close();
6408
6409 // Verify that the third offer alice created was consumed.
6410 {
6411 auto const offers = sortedOffersOnAccount(env, alice);
6412 BEAST_EXPECT(offers.empty());
6413 }
6414 env.require(Balance(alice, usd(0)));
6415 env.require(Owners(alice, 1));
6416 env.require(Balance(bob, usd(200)));
6417 env.require(Owners(bob, 1));
6418 }
6419
6420 void
6422 {
6423 testcase("Ticket Cancel Offers");
6424
6425 using namespace jtx;
6426
6427 // Verify that offers created with or without tickets can be canceled
6428 // by transactions with or without tickets.
6429 Env env{*this, features};
6430 auto const gw = Account{"gateway"};
6431 auto const alice = Account{"alice"};
6432
6433 env.fund(XRP(10'000), gw, alice);
6434 env.close();
6435
6436 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}});
6437
6438 env.require(Owners(alice, 1), Tickets(alice, 0));
6439
6440 env(pay(gw, alice, usd(200)));
6441 env.close();
6442
6443 // Create the first of four offers using a sequence.
6444 std::uint32_t const offerSeqId0{env.seq(alice)};
6445 env(offer(alice, XRP(50), usd(50)));
6446 env.close();
6447 env.require(Owners(alice, 2), Tickets(alice, 0));
6448
6449 // Create four tickets.
6450 std::uint32_t const ticketSeq{env.seq(alice) + 1};
6451 env(ticket::create(alice, 4));
6452 env.close();
6453 env.require(Owners(alice, 6), Tickets(alice, 4));
6454
6455 // Create the second (also sequence-based) offer.
6456 std::uint32_t const offerSeqId1{env.seq(alice)};
6457 BEAST_EXPECT(offerSeqId1 == offerSeqId0 + 6);
6458 env(offer(alice, XRP(50), usd(50)));
6459 env.close();
6460
6461 // Create the third (ticket-based) offer.
6462 std::uint32_t const offerTixId0{ticketSeq + 1};
6463 env(offer(alice, XRP(50), usd(50)), ticket::Use(offerTixId0));
6464 env.close();
6465
6466 // Create the last offer.
6467 std::uint32_t const offerTixId1{ticketSeq};
6468 env(offer(alice, XRP(50), usd(50)), ticket::Use(offerTixId1));
6469 env.close();
6470
6471 // Verify that all of alice's offers are present.
6472 {
6473 auto offers = sortedOffersOnAccount(env, alice);
6474 BEAST_EXPECT(offers.size() == 4);
6475 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId0);
6476 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId1);
6477 BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerTixId0);
6478 BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerSeqId1);
6479 env.require(Balance(alice, usd(200)));
6480 env.require(Owners(alice, 7));
6481 }
6482
6483 // Use a ticket to cancel an offer created with a sequence.
6484 env(offerCancel(alice, offerSeqId0), ticket::Use(ticketSeq + 2));
6485 env.close();
6486
6487 // Verify that offerSeqId_0 was canceled.
6488 {
6489 auto offers = sortedOffersOnAccount(env, alice);
6490 BEAST_EXPECT(offers.size() == 3);
6491 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId1);
6492 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId0);
6493 BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerSeqId1);
6494 }
6495
6496 // Use a ticket to cancel an offer created with a ticket.
6497 env(offerCancel(alice, offerTixId0), ticket::Use(ticketSeq + 3));
6498 env.close();
6499
6500 // Verify that offerTixId_0 was canceled.
6501 {
6502 auto offers = sortedOffersOnAccount(env, alice);
6503 BEAST_EXPECT(offers.size() == 2);
6504 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId1);
6505 BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerSeqId1);
6506 }
6507
6508 // All of alice's tickets should now be used up.
6509 env.require(Owners(alice, 3), Tickets(alice, 0));
6510
6511 // Use a sequence to cancel an offer created with a ticket.
6512 env(offerCancel(alice, offerTixId1));
6513 env.close();
6514
6515 // Verify that offerTixId_1 was canceled.
6516 {
6517 auto offers = sortedOffersOnAccount(env, alice);
6518 BEAST_EXPECT(offers.size() == 1);
6519 BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId1);
6520 }
6521
6522 // Use a sequence to cancel an offer created with a sequence.
6523 env(offerCancel(alice, offerSeqId1));
6524 env.close();
6525
6526 // Verify that offerSeqId_1 was canceled.
6527 // All of alice's tickets should now be used up.
6528 env.require(Owners(alice, 1), Tickets(alice, 0), Offers(alice, 0));
6529 }
6530
6531 void
6533 {
6534 testcase("fixFillOrKill");
6535 using namespace jtx;
6536 Account const issuer("issuer");
6537 Account const maker("maker");
6538 Account const taker("taker");
6539
6540 auto const test = [&](auto&& issue1, auto&& issue2) {
6541 Env env(*this, features);
6542
6543 env.fund(XRP(1'000), issuer);
6544 env.fund(XRP(1'000), maker, taker);
6545 env.close();
6546
6547 auto const usd =
6548 issue1({.env = env, .token = "USD", .issuer = issuer, .holders = {maker, taker}});
6549 auto const eur =
6550 issue2({.env = env, .token = "EUR", .issuer = issuer, .holders = {maker, taker}});
6551
6552 env(pay(issuer, maker, usd(1'000)));
6553 env(pay(issuer, taker, usd(1'000)));
6554 env(pay(issuer, maker, eur(1'000)));
6555 env.close();
6556
6557 auto makerUSDBalance = env.balance(maker, usd).value();
6558 auto takerUSDBalance = env.balance(taker, usd).value();
6559 auto makerEURBalance = env.balance(maker, eur).value();
6560 auto takerEURBalance = env.balance(taker, eur).value();
6561 auto makerXRPBalance = env.balance(maker, XRP).value();
6562 auto takerXRPBalance = env.balance(taker, XRP).value();
6563
6564 // tfFillOrKill, TakerPays must be filled
6565 {
6566 env(offer(maker, XRP(100), usd(100)));
6567 env.close();
6568
6569 env(offer(taker, usd(100), XRP(101)), Txflags(tfFillOrKill));
6570 env.close();
6571
6572 makerXRPBalance -= txFee(env, 1);
6573 takerXRPBalance -= txFee(env, 1);
6574 makerUSDBalance -= usd(100);
6575 takerUSDBalance += usd(100);
6576 makerXRPBalance += XRP(100).value();
6577 takerXRPBalance -= XRP(100).value();
6578 BEAST_EXPECT(expectOffers(env, taker, 0));
6579
6580 env(offer(maker, usd(100), XRP(100)));
6581 env.close();
6582
6583 env(offer(taker, XRP(100), usd(101)), Txflags(tfFillOrKill));
6584 env.close();
6585
6586 makerXRPBalance -= txFee(env, 1);
6587 takerXRPBalance -= txFee(env, 1);
6588 makerUSDBalance += usd(100);
6589 takerUSDBalance -= usd(100);
6590 makerXRPBalance -= XRP(100).value();
6591 takerXRPBalance += XRP(100).value();
6592 BEAST_EXPECT(expectOffers(env, taker, 0));
6593
6594 env(offer(maker, usd(100), eur(100)));
6595 env.close();
6596
6597 env(offer(taker, eur(100), usd(101)), Txflags(tfFillOrKill));
6598 env.close();
6599
6600 makerXRPBalance -= txFee(env, 1);
6601 takerXRPBalance -= txFee(env, 1);
6602 makerUSDBalance += usd(100);
6603 takerUSDBalance -= usd(100);
6604 makerEURBalance -= eur(100);
6605 takerEURBalance += eur(100);
6606 BEAST_EXPECT(expectOffers(env, taker, 0));
6607 }
6608
6609 // tfFillOrKill + tfSell, TakerGets must be filled
6610 {
6611 env(offer(maker, XRP(101), usd(101)));
6612 env.close();
6613
6614 env(offer(taker, usd(100), XRP(101)), Txflags(tfFillOrKill | tfSell));
6615 env.close();
6616
6617 makerUSDBalance -= usd(101);
6618 takerUSDBalance += usd(101);
6619 makerXRPBalance += XRP(101).value() - txFee(env, 1);
6620 takerXRPBalance -= XRP(101).value() + txFee(env, 1);
6621 BEAST_EXPECT(expectOffers(env, taker, 0));
6622
6623 env(offer(maker, usd(101), XRP(101)));
6624 env.close();
6625
6626 env(offer(taker, XRP(100), usd(101)), Txflags(tfFillOrKill | tfSell));
6627 env.close();
6628
6629 makerUSDBalance += usd(101);
6630 takerUSDBalance -= usd(101);
6631 makerXRPBalance -= XRP(101).value() + txFee(env, 1);
6632 takerXRPBalance += XRP(101).value() - txFee(env, 1);
6633 BEAST_EXPECT(expectOffers(env, taker, 0));
6634
6635 env(offer(maker, usd(101), eur(101)));
6636 env.close();
6637
6638 env(offer(taker, eur(100), usd(101)), Txflags(tfFillOrKill | tfSell));
6639 env.close();
6640
6641 makerUSDBalance += usd(101);
6642 takerUSDBalance -= usd(101);
6643 makerEURBalance -= eur(101);
6644 takerEURBalance += eur(101);
6645 makerXRPBalance -= txFee(env, 1);
6646 takerXRPBalance -= txFee(env, 1);
6647 BEAST_EXPECT(expectOffers(env, taker, 0));
6648 }
6649
6650 // Fail regardless of fixFillOrKill amendment
6651 for (auto const flags : {tfFillOrKill, tfFillOrKill + tfSell})
6652 {
6653 env(offer(maker, XRP(100), usd(100)));
6654 env.close();
6655
6656 env(offer(taker, usd(100), XRP(99)), Txflags(flags), Ter(tecKILLED));
6657 env.close();
6658
6659 makerXRPBalance -= txFee(env, 1);
6660 takerXRPBalance -= txFee(env, 1);
6661 BEAST_EXPECT(expectOffers(env, taker, 0));
6662
6663 env(offer(maker, usd(100), XRP(100)));
6664 env.close();
6665
6666 env(offer(taker, XRP(100), usd(99)), Txflags(flags), Ter(tecKILLED));
6667 env.close();
6668
6669 makerXRPBalance -= txFee(env, 1);
6670 takerXRPBalance -= txFee(env, 1);
6671 BEAST_EXPECT(expectOffers(env, taker, 0));
6672
6673 env(offer(maker, usd(100), eur(100)));
6674 env.close();
6675
6676 env(offer(taker, eur(100), usd(99)), Txflags(flags), Ter(tecKILLED));
6677 env.close();
6678
6679 makerXRPBalance -= txFee(env, 1);
6680 takerXRPBalance -= txFee(env, 1);
6681 BEAST_EXPECT(expectOffers(env, taker, 0));
6682 }
6683
6684 BEAST_EXPECT(
6685 env.balance(maker, usd) == makerUSDBalance &&
6686 env.balance(taker, usd) == takerUSDBalance &&
6687 env.balance(maker, eur) == makerEURBalance &&
6688 env.balance(taker, eur) == takerEURBalance &&
6689 env.balance(maker, XRP) == makerXRPBalance &&
6690 env.balance(taker, XRP) == takerXRPBalance);
6691 };
6693 }
6694
6695 void
6697 {
6698 testcase("Tick Size");
6699
6700 using namespace jtx;
6701
6702 auto const gw = Account{"gateway"};
6703 auto const alice = Account{"alice"};
6704
6705 auto const getIOU = [&](Env& env) -> PrettyAsset {
6706 static int kI = 0;
6707 std::string const name = "IO" + std::to_string(kI++);
6708 auto const iou = gw[name];
6709 env(trust(alice, iou(1'000)));
6710 env(pay(gw, alice, iou(100)));
6711 env.close();
6712 return iou;
6713 };
6714 auto const getMPT = [&](Env& env) -> PrettyAsset {
6715 MPT const mpt =
6716 MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000'000'000});
6717 return mpt;
6718 };
6719 auto const getXRP = [&](Env& env) -> PrettyAsset { return XRP; };
6720
6721 using ToAsset = std::function<PrettyAsset(Env&)>;
6722 struct TestInfo
6723 {
6724 ToAsset toAsset1;
6725 ToAsset toAsset2;
6726 int val1;
6727 int val2;
6728 };
6729 // XRP/MPT, MPT/XRP, MPT/MPT offers are not adjusted for TickSize
6730 // IOU/IOU, XRP/IOU, IOU/XRP offers have TickSize logic unchanged
6731 // IOU/MPT, MPT/IOU have TickSize logic applied to adjust IOU only
6733 {.toAsset1 = getIOU, .toAsset2 = getIOU, .val1 = 10, .val2 = 30},
6734 {.toAsset1 = getIOU, .toAsset2 = getXRP, .val1 = 10, .val2 = 30'000'000},
6735 {.toAsset1 = getXRP, .toAsset2 = getIOU, .val1 = 10'000'000, .val2 = 30},
6736 {.toAsset1 = getMPT, .toAsset2 = getXRP, .val1 = 10'000'000, .val2 = 30'000'000},
6737 {.toAsset1 = getXRP, .toAsset2 = getMPT, .val1 = 10'000'000, .val2 = 30'000'000},
6738 {.toAsset1 = getIOU, .toAsset2 = getMPT, .val1 = 10, .val2 = 30'000'000},
6739 {.toAsset1 = getMPT, .toAsset2 = getIOU, .val1 = 10'000'000, .val2 = 30},
6740 {.toAsset1 = getMPT, .toAsset2 = getMPT, .val1 = 10'000'000, .val2 = 30'000'000},
6741 };
6742 for (TestInfo const& t : tests)
6743 {
6744 Env env{*this, features};
6745 env.fund(XRP(10'000), gw, alice);
6746 env.close();
6747
6748 auto const xts = t.toAsset1(env);
6749 auto const xxx = t.toAsset2(env);
6750
6751 auto const tokenType = [](PrettyAsset const& asset) -> std::string {
6752 return asset.raw().visit(
6753 [&](Issue const& issue) { return issue.native() ? "XRPIssue" : "Issue"; },
6754 [&](MPTIssue const&) { return "MPTIssue"; });
6755 };
6756
6757 testcase << "offer: " << tokenType(xts) << "/" << tokenType(xxx);
6758
6759 {
6760 // Gateway sets its tick size to 5
6761 auto txn = noop(gw);
6762 txn[sfTickSize.fieldName] = 5;
6763 env(txn);
6764 BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5);
6765 }
6766
6767 env(offer(alice, xts(t.val1), xxx(t.val2)));
6768 env(offer(alice, xts(t.val2), xxx(t.val1)));
6769 env(offer(alice, xts(t.val1), xxx(t.val2)), Json(jss::Flags, tfSell));
6770 env(offer(alice, xts(t.val2), xxx(t.val1)), Json(jss::Flags, tfSell));
6771
6773 forEachItem(*env.current(), alice, [&](SLE::ConstRef sle) {
6774 if (sle->getType() == ltOFFER)
6775 {
6776 offers.emplace(
6777 (*sle)[sfSequence],
6778 std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets]));
6779 }
6780 });
6781
6782 // first offer
6783 auto it = offers.begin();
6784 BEAST_EXPECT(it != offers.end());
6785 if (xxx.native() && !xts.holds<MPTIssue>())
6786 {
6787 BEAST_EXPECT(
6788 it->second.first == xts(t.val1) && it->second.second == XRPAmount(29'999'400));
6789 }
6790 else if (!xxx.integral())
6791 {
6792 BEAST_EXPECT(
6793 it->second.first == xts(t.val1) && it->second.second < xxx(t.val2) &&
6794 it->second.second > STAmount(xxx, 29'9994, -4));
6795 }
6796 else
6797 {
6798 BEAST_EXPECT(it->second.first == xts(t.val1) && it->second.second == xxx(t.val2));
6799 }
6800
6801 // second offer
6802 ++it;
6803 BEAST_EXPECT(it != offers.end());
6804 BEAST_EXPECT(it->second.first == xts(t.val2) && it->second.second == xxx(t.val1));
6805
6806 // third offer
6807 ++it;
6808 BEAST_EXPECT(it != offers.end());
6809 if (xts.native() && !xxx.holds<MPTIssue>())
6810 {
6811 BEAST_EXPECT(
6812 it->second.first == XRPAmount(10'000'200) && it->second.second == xxx(t.val2));
6813 }
6814 else if (!xts.integral())
6815 {
6816 BEAST_EXPECT(
6817 it->second.first == STAmount(xts, 10'0002, -4) &&
6818 it->second.second == xxx(t.val2));
6819 }
6820 else
6821 {
6822 BEAST_EXPECT(it->second.first == xts(t.val1) && it->second.second == xxx(t.val2));
6823 }
6824
6825 // fourth offer
6826 // exact TakerPays is XTS(1/.033333)
6827 ++it;
6828 BEAST_EXPECT(it != offers.end());
6829 BEAST_EXPECT(it->second.first == xts(t.val2) && it->second.second == xxx(t.val1));
6830
6831 BEAST_EXPECT(++it == offers.end());
6832 }
6833 }
6834
6835 void
6837 {
6838 // An MPT offer whose quality is not representable must not REST -- on
6839 // both the buy and sell sides, with or without a TickSize on the IOU
6840 // issuer. Here nothing crosses it, so the whole offer is the remainder
6841 // and the result is tecKILLED with nothing placed.
6842 //
6843 // getRate(TakerGets, TakerPays) returns 0 when the rate overflows: a
6844 // large MPT TakerPays (XLS-0082 allows up to 2^63-1) over a small IOU
6845 // TakerGets. Such an offer would otherwise (a) rest in the quality-0
6846 // book directory, whose index equals getBookBase(), which BookTip's
6847 // strict successor scan never returns -- so it can never be crossed yet
6848 // still consumes the owner's reserve; and (b) on a TickSize market,
6849 // drive the tick-rounding path in applyGuts to divide by a zero rate,
6850 // throwing and surfacing as tefEXCEPTION. A normally-priced offer in the
6851 // same market is unaffected.
6852 //
6853 // Under MPTokensV2 divide() keeps a large MPT quotient in range, so a
6854 // large MPT is only unrepresentable against a tiny IOU: its rate is
6855 // then beyond the IOU exponent range. The inverse underflows, so no
6856 // counterparty offer can rest either, and nothing crosses.
6857 testcase("MPT Offer Zero Rate");
6858
6859 using namespace jtx;
6860
6861 auto const kBigMpt = 5'000'000'000'000'000'000LL;
6862
6863 auto const runScenario = [&](bool withTickSize) {
6864 Env env{*this, features};
6865 auto const gw = Account{"gateway"};
6866 auto const alice = Account{"alice"};
6867 env.fund(XRP(10'000), gw, alice);
6868 env.close();
6869
6870 auto const usd = gw["USD"];
6871 env(trust(alice, usd(1'000)));
6872 env(pay(gw, alice, usd(100)));
6873 env.close();
6874
6875 // The smallest IOU amount, 1e-81. kBigMpt over it is ~5e99.
6876 STAmount const tiny{usd.issue(), STAmount::kMinValue, STAmount::kMinOffset};
6877
6878 if (withTickSize)
6879 {
6880 auto txn = noop(gw);
6881 txn[sfTickSize.fieldName] = 5;
6882 env(txn);
6883 env.close();
6884 BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5);
6885 }
6886
6887 // gw issues a DEX-tradable MPT (CanTrade | CanTransfer by default)
6888 // and authorizes alice to hold it.
6889 MPT const mpt = MPTTester(
6890 {.env = env, .issuer = gw, .holders = {alice}, .maxAmt = kMaxMpTokenAmount});
6891
6892 // Buy side: TakerPays = large MPT, TakerGets = the smallest IOU.
6893 // getRate() overflows to 0 and nothing crosses -> killed, no
6894 // offer placed and no reserve consumed.
6895 BEAST_EXPECT(getRate(tiny, mpt(kBigMpt)) == 0);
6896 env(offer(alice, mpt(kBigMpt), tiny), Ter(tecKILLED));
6897 env.close();
6898 BEAST_EXPECT(offersOnAccount(env, alice).empty());
6899
6900 // Sell side (tfSell): killed regardless of the flag, since the
6901 // rate is computed from the raw amounts either way.
6902 env(offer(alice, mpt(kBigMpt), tiny, tfSell), Ter(tecKILLED));
6903 env.close();
6904 BEAST_EXPECT(offersOnAccount(env, alice).empty());
6905
6906 // The same MPT against 1 USD used to be unrepresentable too
6907 // (quotient above 2^64); it now rests at its true quality.
6908 BEAST_EXPECT(
6909 amountFromQuality(getRate(usd(1), mpt(kBigMpt))) ==
6910 STAmount(noIssue(), Number{mpt(kBigMpt).value()} / Number{usd(1).value()}));
6911 env(offer(alice, mpt(kBigMpt), usd(1)), Ter(tesSUCCESS));
6912 env.close();
6913 BEAST_EXPECT(offersOnAccount(env, alice).size() == 1);
6914
6915 // Control: a normally-priced offer in the same market still
6916 // places (and the tick-size rounding path still works when
6917 // withTickSize is set).
6918 env(offer(alice, mpt(10'000'000), usd(30)), Ter(tesSUCCESS));
6919 env.close();
6920 BEAST_EXPECT(offersOnAccount(env, alice).size() == 2);
6921 };
6922
6923 // Without a TickSize: previously placed as a dead, never-crossable
6924 // quality-0 entry that still consumed reserve.
6925 runScenario(/*withTickSize=*/false);
6926 // With a TickSize: previously threw and surfaced as tefEXCEPTION. The
6927 // rounding is now skipped when the rate is unrepresentable.
6928 runScenario(/*withTickSize=*/true);
6929 }
6930
6931 void
6933 {
6934 // A rate-0 offer is reachable without MPT: for XRP/IOU the "too
6935 // good" underflow path makes getRate() return 0 when a tiny IOU
6936 // TakerPays is divided by an XRP TakerGets.
6937 //
6938 // Without featureMPTokensV2 the offer is accepted and placed, but
6939 // rests in the quality-0 book directory (whose index == getBookBase),
6940 // which BookTip's strict successor scan never returns -- so it can
6941 // never be crossed, even by a willing, better-priced counterparty.
6942 // With featureMPTokensV2 the same offer crosses nothing and is not
6943 // placed, so it is killed.
6944 testcase("Zero Rate XRP/IOU Offer");
6945
6946 using namespace jtx;
6947
6948 auto const gw = Account{"gateway"};
6949 auto const alice = Account{"alice"};
6950 auto const bob = Account{"bob"};
6951 auto const usd = gw["USD"];
6952
6953 // Smallest-magnitude IOU: mantissa kMinValue, exponent kMinOffset
6954 // (= 1e-81). divide(tinyUsd, XRP(1000)) underflows below kMinOffset
6955 // and canonicalizes to 0, so getRate() returns 0.
6956 auto const tinyUsd = STAmount{usd, UINT64_C(1'000'000'000'000'000), -96};
6957
6958 auto const setup = [&](Env& env) {
6959 env.fund(XRP(100'000), gw, alice, bob);
6960 env.close();
6961 env(trust(alice, usd(1'000)));
6962 env(trust(bob, usd(1'000)));
6963 env(pay(gw, bob, usd(100)));
6964 env.close();
6965 };
6966
6967 // featureMPTokensV2 disabled: legacy behavior -- placed but inert.
6968 {
6969 Env env{*this, features - featureMPTokensV2};
6970 setup(env);
6971
6972 // TakerPays = tiny IOU, TakerGets = XRP -> rate 0.
6973 BEAST_EXPECT(getRate(XRP(1'000), tinyUsd) == 0);
6974 env(offer(alice, tinyUsd, XRP(1'000)), Ter(tesSUCCESS));
6975 env.close();
6976
6977 auto const aliceOffers = offersOnAccount(env, alice);
6978 BEAST_EXPECT(aliceOffers.size() == 1);
6979 // Placed in the quality-0 book directory.
6980 BEAST_EXPECT(getQuality((*aliceOffers.front())[sfBookDirectory]) == 0);
6981
6982 // A complementary offer that would cross a usable offer at this
6983 // (astronomically good) price does NOT cross it, because the
6984 // quality-0 directory is never visited: both offers rest.
6985 env(offer(bob, XRP(1'000), usd(10)), Ter(tesSUCCESS));
6986 env.close();
6987 BEAST_EXPECT(offersOnAccount(env, alice).size() == 1);
6988 BEAST_EXPECT(offersOnAccount(env, bob).size() == 1);
6989 }
6990
6991 // featureMPTokensV2 disabled, with a TickSize on the IOU issuer: the
6992 // tick-rounding path divides by the zero rate and throws, surfacing as
6993 // tefEXCEPTION. Legacy behavior, and it must stay that way -- the
6994 // guard that skips the rounding is gated on the amendment, since
6995 // changing this without a gate would fork a pre-amendment ledger.
6996 {
6997 Env env{*this, features - featureMPTokensV2};
6998 setup(env);
6999
7000 auto txn = noop(gw);
7001 txn[sfTickSize.fieldName] = 5;
7002 env(txn);
7003 env.close();
7004 BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5);
7005
7006 BEAST_EXPECT(getRate(XRP(1'000), tinyUsd) == 0);
7007 env(offer(alice, tinyUsd, XRP(1'000)), Ter(tefEXCEPTION));
7008 env.close();
7009 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7010 }
7011
7012 // featureMPTokensV2 enabled: nothing crosses, so the remainder is the
7013 // whole offer and it is killed rather than placed.
7014 {
7015 Env env{*this, features};
7016 setup(env);
7017
7018 BEAST_EXPECT(getRate(XRP(1000), tinyUsd) == 0);
7019 env(offer(alice, tinyUsd, XRP(1000)), Ter(tecKILLED));
7020 env.close();
7021 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7022 }
7023
7024 // featureMPTokensV2 enabled, with a counterparty already on the book:
7025 // the same unrepresentable quality now CROSSES. This is the reviewer's
7026 // objection with no MPT anywhere in it -- the old preflight check
7027 // rejected this outright even though it fills completely and rests
7028 // nothing.
7029 {
7030 Env env{*this, features};
7031 setup(env);
7032
7033 // Bob rests first: he gives usd(10) to receive XRP(1'000).
7034 auto const bobSeq = env.seq(bob);
7035 env(offer(bob, XRP(1'000), usd(10)), Ter(tesSUCCESS));
7036 env.close();
7037 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
7038
7039 // Alice offers up to XRP(1'000) for a dust amount of USD -- rate
7040 // 0, at a price bob's offer improves on enormously.
7041 BEAST_EXPECT(getRate(XRP(1'000), tinyUsd) == 0);
7042 env(offer(alice, tinyUsd, XRP(1'000)), Ter(tesSUCCESS));
7043 env.close();
7044
7045 // Alice asked for dust and got exactly that, so her offer is
7046 // fully satisfied and never reaches the book. Bob's offer is
7047 // barely touched and stays. The old preflight check rejected this
7048 // transaction outright, with no MPT involved anywhere.
7049 BEAST_EXPECT(env.balance(alice, usd).value() == tinyUsd);
7050 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
7051 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7052 }
7053 }
7054
7055 void
7057 {
7058 // When an offer on the book is partially crossed, the payment engine
7059 // auto-creates a new ledger object (MPToken or IOU trustline) for the
7060 // offer owner to hold the incoming asset. This happens inside
7061 // BookStep::forEachOffer (MPT: checkCreateMPT) and BookStep::consumeOffer
7062 // (IOU: directSendNoFeeIOU -> trustCreate) without a reserve sufficiency
7063 // check. The offer owner can therefore end up with more objects than
7064 // their XRP balance can reserve for, consistent with IOU behavior.
7065
7066 testcase("Auto-Create Object Without Reserve Check During Partial Crossing");
7067
7068 using namespace jtx;
7069
7070 auto const gw = Account{"gateway"};
7071 auto const alice = Account{"alice"};
7072 auto const carol = Account{"carol"};
7073 auto const bob = Account{"bob"};
7074
7075 auto const test = [&](auto&& getToken, auto&& execTx) {
7076 // MPT/IOU: carol's existing offer buys MPT/IOU by selling XRP.
7077 // carol has no MPToken/Trustline for this issuance. When alice partially crosses
7078 // carol's offer, an MPToken/Trustline is auto-created for carol without checking
7079 // that she can afford the extra reserve slot.
7080 Env env{*this, features};
7081
7082 auto const f = env.current()->fees().base;
7083 auto const r = reserve(env, 0);
7084 auto const inc = reserve(env, 1) - r;
7085
7086 env.fund(XRP(10'000), gw, alice, bob);
7087
7088 // getToken:
7089 // - Create MPT with CanTransfer + CanTrade; authorize alice as holder.
7090 // - Create IOU trustline
7091 auto const token = getToken(env);
7092
7093 // carol: reserve(0) + 1 increment + fee covers placing one offer.
7094 // After the offer tx she has exactly reserve(1) + XRP(30).
7095 // XRP(30) < inc (50 XRP), so receiving a second object will put her
7096 // below reserve(2).
7097 if (BEAST_EXPECT(inc > XRP(30)))
7098 env.fund(r + inc + f + XRP(30), carol);
7099
7100 // carol's offer goes on the book (no counterpart yet).
7101 // TakerPays=Token(30): carol will receive Token when crossed.
7102 // TakerGets=XRP(30): carol will give XRP when crossed.
7103 env(offer(carol, token(30), XRP(30)));
7104 env.require(Owners(carol, 1));
7105
7106 // Execute offer create or cross-currency payment
7107 // alice partially crosses carol's offer.
7108 // alice sends Token(15) to carol and receives XRP(15).
7109 // Token:
7110 // - MPT: checkCreateMPT auto-creates an MPToken for carol (no reserve check).
7111 // - IOU: directSendNoFeeIOU auto-creates an Trustline for carol (no reserve check).
7112 execTx(env, token);
7113
7114 // Carol now owns 2 objects (remaining offer + new MPToken) even
7115 // though her XRP balance is only reserve(1) + XRP(15), which is
7116 // below reserve(2) = reserve(1) + inc.
7117 auto const carolBalance = r + inc + XRP(15);
7118 env.require(Owners(carol, 2), Balance(carol, token(15)), Balance(carol, carolBalance));
7119 BEAST_EXPECT(carolBalance < r + 2 * inc); // below reserve(2)
7120 };
7121 std::function<PrettyAsset(Env&)> const getIOU = [&](Env& env) -> PrettyAsset {
7122 env.trust(gw["USD"](1'000), alice);
7123 env(pay(gw, alice, gw["USD"](100)));
7124 return gw["USD"];
7125 };
7126 std::function<PrettyAsset(Env&)> const getMPT = [&](Env& env) -> PrettyAsset {
7127 MPT const mpT1 = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 100});
7128 return mpT1;
7129 };
7130 for (auto&& getToken : {getIOU, getMPT})
7131 {
7132 test(getToken, [&](Env& env, PrettyAsset const& token) {
7133 // alice partially crosses carol's offer.
7134 // alice sends Token(15) to carol and receives XRP(15).
7135 // Token is MPT: checkCreateMPT auto-creates an MPToken for carol (no reserve
7136 // check). Token is IOU: directSendNoFeeIOU auto-creates a trustline for carol (no
7137 // reserve check).
7138 env(offer(alice, XRP(15), token(15)));
7139 });
7140 test(getToken, [&](Env& env, PrettyAsset const& token) {
7141 // Similar to above but with cross-currency payment.
7142 env(pay(alice, bob, XRP(15)),
7143 Sendmax(token(15)),
7144 Path(~XRP),
7145 Txflags(tfNoRippleDirect | tfPartialPayment));
7146 });
7147 }
7148 }
7149
7150 void
7152 {
7153 // A bid for a large MPT amount paid in IOU partially crosses a small
7154 // ask. flowCross then recomputes the remainder with
7155 // mulRound(afterCross.out [MPT], rate, IOU): an MPT operand with a
7156 // non-MPT result. That took the legacy 16-digit path and overflowed
7157 // once TakerPays * rateMantissa exceeded ~1.8e33, failing the
7158 // transaction with tecINTERNAL (fee charged, cross rolled back,
7159 // nothing placed). Any MPT operand now uses Number arithmetic, so the
7160 // cross settles.
7161 testcase("MPT Offer large remainder after partial cross");
7162
7163 using namespace jtx;
7164
7165 // alice bids `pays` MPT for `gets` USD; bob asks 1,000 MPT at the same
7166 // price. Alice's remainder rests with TakerGets `remainderGets`.
7167 auto const test = [&](std::int64_t pays,
7168 std::int64_t gets,
7169 std::int64_t askGets,
7170 std::int64_t remainderGets) {
7171 Env env{*this, features};
7172 Account const gw{"gw"};
7173 Account const alice{"alice"};
7174 Account const bob{"bob"};
7175 env.fund(XRP(10'000), gw, alice, bob);
7176 env.close();
7177
7178 auto const usd = gw["USD"];
7179 env(trust(alice, usd(2 * gets)));
7180 env(trust(bob, usd(2 * gets)));
7181 env(pay(gw, alice, usd(2 * gets)));
7182
7183 MPT const mpt = MPTTester(
7184 {.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = kMaxMpTokenAmount});
7185 env(pay(gw, bob, mpt(1'000)));
7186 auto const askSeq = env.seq(bob);
7187 env(offer(bob, usd(askGets), mpt(1'000)));
7188 env.close();
7189
7190 auto const bidSeq = env.seq(alice);
7191 env(offer(alice, mpt(pays), usd(gets)));
7192 env.close();
7193
7194 BEAST_EXPECT(env.balance(alice, mpt) == mpt(1'000));
7195 BEAST_EXPECT(env.balance(bob, mpt) == mpt(0));
7196 BEAST_EXPECT(env.balance(bob, usd) == usd(askGets));
7197 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(askSeq))) == nullptr);
7198 auto const bid = env.le(keylet::offer(alice.id(), SeqProxy::rawSequence(bidSeq)));
7199 if (BEAST_EXPECT(bid))
7200 {
7201 BEAST_EXPECT((*bid)[sfTakerPays] == mpt(pays - 1'000));
7202 BEAST_EXPECT((*bid)[sfTakerGets] == usd(remainderGets));
7203 }
7204 };
7205
7206 // 1e18 MPT at 9e-3 USD per unit: the remainder's mulRound overflowed
7207 // the legacy path (1e18 * 9e15 > 1.8e33) but its rate is
7208 // representable, so it rests at the exact 9e-3.
7209 test(1'000'000'000'000'000'000LL, 9'000'000'000'000'000LL, 9, 8'999'999'999'999'991LL);
7210 // 5e18 MPT at 1e-3 USD per unit: the remainder's quotient in divide()
7211 // is above 2^64. It used to make getRate() return 0 and the remainder
7212 // was not placed; it now rests.
7213 test(5'000'000'000'000'000'000LL, 5'000'000'000'000'000LL, 1, 4'999'999'999'999'999LL);
7214 }
7215
7216 void
7218 {
7219 // carol sells 5e17 MPT for 1,000 USD but holds only 4.8e17 MPT.
7220 // BookStep reduces the offer by her funds with
7221 // mulRoundStrict(funds [MPT], rate, USD): an MPT operand with an IOU
7222 // result. On the legacy 16-digit path the product (9.6e18) fit in
7223 // uint64 but not int64 and wrapped to a negative USD amount without
7224 // throwing. Sending it failed, the strand went dry, and the offer was
7225 // never removed, so every crossing or payment through the book failed.
7226 // Any MPT operand now uses Number arithmetic and the offer is taken.
7227 testcase("Partially funded large MPT ask");
7228
7229 using namespace jtx;
7230
7231 for (bool const payment : {false, true})
7232 {
7233 Env env{*this, features};
7234 Account const gw{"gw"};
7235 Account const bob{"bob"};
7236 Account const carol{"carol"};
7237 Account const dan{"dan"};
7238 env.fund(XRP(10'000), gw, bob, carol, dan);
7239 env.close();
7240
7241 auto const usd = gw["USD"];
7242 env(trust(bob, usd(10'000)));
7243 env(trust(carol, usd(10'000)));
7244 env(pay(gw, bob, usd(5'000)));
7245
7246 MPT const s = MPTTester({
7247 .env = env,
7248 .issuer = gw,
7249 .holders = {bob, carol, dan},
7250 .maxAmt = kMaxMpTokenAmount,
7251 });
7252 env(pay(gw, carol, s(480'000'000'000'000'000LL)));
7253 env.close();
7254
7255 auto const carolSeq = env.seq(carol);
7256 env(offer(carol, usd(1'000), s(500'000'000'000'000'000LL)));
7257 env.close();
7258
7259 if (payment)
7260 {
7261 env(pay(bob, dan, s(1'000'000'000'000'000LL)),
7262 Path(~s),
7263 Sendmax(usd(100)),
7264 Txflags(tfPartialPayment));
7265 env.close();
7266 BEAST_EXPECT(env.balance(dan, s) == s(1'000'000'000'000'000LL));
7267 }
7268 else
7269 {
7270 env(offer(bob, s(1'000'000'000'000'000LL), usd(2)));
7271 env.close();
7272 BEAST_EXPECT(env.balance(bob, s) == s(1'000'000'000'000'000LL));
7273 BEAST_EXPECT(expectOffers(env, bob, 0));
7274 }
7275
7276 BEAST_EXPECT(env.balance(bob, usd) == usd(4'998));
7277 BEAST_EXPECT(env.balance(carol, usd) == usd(2));
7278 BEAST_EXPECT(env.balance(carol, s) == s(479'000'000'000'000'000LL));
7279 auto const ask = env.le(keylet::offer(carol.id(), SeqProxy::rawSequence(carolSeq)));
7280 if (BEAST_EXPECT(ask))
7281 {
7282 BEAST_EXPECT((*ask)[sfTakerGets] == s(499'000'000'000'000'000LL));
7283 BEAST_EXPECT((*ask)[sfTakerPays] == usd(998));
7284 }
7285 }
7286 }
7287
7288 void
7290 {
7291 testcase("book_offers uses MPT issuer capacity, transfer fees, and locks");
7292
7293 using namespace jtx;
7294
7295 Account const issuer{"issuer"};
7296 Account const maker{"maker"};
7297 Account const buyer{"buyer"};
7298
7299 // Issuer-owned MPT offers are funded only by remaining issuance
7300 // capacity. Once ordinary issuance consumes the cap, book_offers must
7301 // report the stale issuer offer as zero-funded.
7302 {
7303 Env env{*this, features};
7304
7305 env.fund(XRP(10'000), issuer, maker, buyer);
7306 env.close();
7307
7308 MPTTester musd(
7309 {.env = env, .issuer = issuer, .holders = {maker, buyer}, .maxAmt = 100});
7310 MPT const usd = musd;
7311
7312 auto const issuerOfferSeq = env.seq(issuer);
7313 env(offer(issuer, XRP(100), usd(100)));
7314
7315 musd.pay(issuer, maker, 100);
7316
7317 auto const issuance = env.le(keylet::mptokenIssuance(usd.mpt()));
7318 if (!BEAST_EXPECT(issuance))
7319 return;
7320 BEAST_EXPECT(issuance->getFieldU64(sfOutstandingAmount) == 100);
7321 BEAST_EXPECT(issuance->getFieldU64(sfMaximumAmount) == 100);
7322
7323 env(offer(maker, XRP(200), usd(100)));
7324
7325 json::Value const jrr = getBookOffers(env, XRP, usd);
7326 json::Value const& bookOffers = jrr[jss::offers];
7327 BEAST_EXPECT(bookOffers.isArray());
7328 if (!BEAST_EXPECT(bookOffers.size() >= 2))
7329 return;
7330
7331 json::Value const& issuerOffer = bookOffers[0u];
7332 BEAST_EXPECT(issuerOffer[sfAccount.jsonName] == issuer.human());
7333 BEAST_EXPECT(issuerOffer[sfSequence.jsonName] == issuerOfferSeq);
7334 BEAST_EXPECT(issuerOffer[jss::owner_funds] == "0");
7335 BEAST_EXPECT(issuerOffer.isMember(jss::taker_gets_funded));
7336 BEAST_EXPECT(issuerOffer[jss::taker_gets_funded][jss::value] == "0");
7337 BEAST_EXPECT(issuerOffer.isMember(jss::taker_pays_funded));
7338 BEAST_EXPECT(issuerOffer[jss::taker_pays_funded] == "0");
7339 }
7340
7341 // Multiple issuer-owned MPT offers share the same bounded self-issue
7342 // capacity. The second offer exercises the cached running balance path
7343 // after the first offer has consumed part of the issuer's capacity.
7344 {
7345 Env env{*this, features};
7346
7347 env.fund(XRP(10'000), issuer, buyer);
7348 env.close();
7349
7350 MPTTester const musd({.env = env, .issuer = issuer, .holders = {buyer}, .maxAmt = 150});
7351 MPT const usd = musd;
7352
7353 auto const firstIssuerOfferSeq = env.seq(issuer);
7354 env(offer(issuer, XRP(100), usd(100)));
7355 auto const secondIssuerOfferSeq = env.seq(issuer);
7356 env(offer(issuer, XRP(100), usd(100)));
7357
7358 json::Value const jrr = getBookOffers(env, XRP, usd);
7359 json::Value const& bookOffers = jrr[jss::offers];
7360 BEAST_EXPECT(bookOffers.isArray());
7361 if (!BEAST_EXPECT(bookOffers.size() >= 2))
7362 return;
7363
7364 json::Value const& firstOffer = bookOffers[0u];
7365 BEAST_EXPECT(firstOffer[sfAccount.jsonName] == issuer.human());
7366 BEAST_EXPECT(firstOffer[sfSequence.jsonName] == firstIssuerOfferSeq);
7367 BEAST_EXPECT(firstOffer[jss::owner_funds] == "150");
7368 BEAST_EXPECT(!firstOffer.isMember(jss::taker_gets_funded));
7369 BEAST_EXPECT(!firstOffer.isMember(jss::taker_pays_funded));
7370
7371 json::Value const& secondOffer = bookOffers[1u];
7372 BEAST_EXPECT(secondOffer[sfAccount.jsonName] == issuer.human());
7373 BEAST_EXPECT(secondOffer[sfSequence.jsonName] == secondIssuerOfferSeq);
7374 BEAST_EXPECT(!secondOffer.isMember(jss::owner_funds));
7375 BEAST_EXPECT(secondOffer.isMember(jss::taker_gets_funded));
7376 BEAST_EXPECT(secondOffer[jss::taker_gets_funded][jss::value] == "50");
7377 BEAST_EXPECT(secondOffer.isMember(jss::taker_pays_funded));
7378 BEAST_EXPECT(secondOffer[jss::taker_pays_funded] == "50000000");
7379 }
7380
7381 auto const checkTransferFeeBookOffers = [&](std::uint16_t transferFee, auto&& checkOffers) {
7382 Env env{*this, features};
7383
7384 env.fund(XRP(10'000), issuer, maker, buyer);
7385 env.close();
7386
7387 MPTTester const musd({
7388 .env = env,
7389 .issuer = issuer,
7390 .holders = {maker, buyer},
7391 .transferFee = transferFee,
7392 .pay = 3'000,
7393 });
7394 MPT const usd = musd;
7395 if (transferFee != 0)
7396 BEAST_EXPECT(musd.checkTransferFee(transferFee));
7397
7398 auto const firstOfferSeq = env.seq(maker);
7399 env(offer(maker, XRP(1'500), usd(1'500)));
7400 auto const secondOfferSeq = env.seq(maker);
7401 env(offer(maker, XRP(1'500), usd(1'500)));
7402
7403 json::Value const jrr = getBookOffers(env, XRP, usd);
7404 json::Value const& bookOffers = jrr[jss::offers];
7405 BEAST_EXPECT(bookOffers.isArray());
7406 if (!BEAST_EXPECT(bookOffers.size() == 2))
7407 return;
7408
7409 checkOffers(bookOffers, firstOfferSeq, secondOfferSeq);
7410 };
7411
7412 // With no MPT transfer fee, two identical maker offers backed by 3000
7413 // owner funds are both fully funded for 1500 MPT.
7414 checkTransferFeeBookOffers(
7415 0,
7416 [&](json::Value const& bookOffers,
7417 std::uint32_t firstOfferSeq,
7418 std::uint32_t secondOfferSeq) {
7419 for (auto const i : {0u, 1u})
7420 {
7421 json::Value const& offer = bookOffers[i];
7422 BEAST_EXPECT(offer[sfAccount.jsonName] == maker.human());
7423 BEAST_EXPECT(
7424 offer[sfSequence.jsonName] == (i == 0u ? firstOfferSeq : secondOfferSeq));
7425 BEAST_EXPECT(!offer.isMember(jss::taker_gets_funded));
7426 BEAST_EXPECT(!offer.isMember(jss::taker_pays_funded));
7427 }
7428 BEAST_EXPECT(bookOffers[0u][jss::owner_funds] == "3000");
7429 });
7430
7431 // With a 50% MPT transfer fee, the first identical maker offer consumes
7432 // 2250 owner funds, so the second offer can deliver only 500 MPT.
7433 checkTransferFeeBookOffers(
7434 50'000,
7435 [&](json::Value const& bookOffers,
7436 std::uint32_t firstOfferSeq,
7437 std::uint32_t secondOfferSeq) {
7438 json::Value const& firstOffer = bookOffers[0u];
7439 BEAST_EXPECT(firstOffer[sfAccount.jsonName] == maker.human());
7440 BEAST_EXPECT(firstOffer[sfSequence.jsonName] == firstOfferSeq);
7441 BEAST_EXPECT(firstOffer[jss::owner_funds] == "3000");
7442 BEAST_EXPECT(!firstOffer.isMember(jss::taker_gets_funded));
7443 BEAST_EXPECT(!firstOffer.isMember(jss::taker_pays_funded));
7444
7445 json::Value const& secondOffer = bookOffers[1u];
7446 BEAST_EXPECT(secondOffer[sfAccount.jsonName] == maker.human());
7447 BEAST_EXPECT(secondOffer[sfSequence.jsonName] == secondOfferSeq);
7448 // A 50% MPT transfer fee leaves only 750 owner funds after
7449 // the first offer. That can fund 500 MPT delivered to the
7450 // taker on the same second offer that was fully funded without
7451 // the transfer fee.
7452 BEAST_EXPECT(secondOffer.isMember(jss::taker_gets_funded));
7453 BEAST_EXPECT(secondOffer[jss::taker_gets_funded][jss::value] == "500");
7454 BEAST_EXPECT(secondOffer.isMember(jss::taker_pays_funded));
7455 BEAST_EXPECT(secondOffer[jss::taker_pays_funded] == "500000000");
7456 });
7457
7458 // The running balance charged for an earlier offer must round the
7459 // owner's fee-grossed cost up, as BookStep does. With the smallest fee
7460 // (rate 1.00001), a maker holding 3 MPT with two 1-MPT offers pays 2
7461 // for the first, leaving 1: not enough for the second. Rounding to
7462 // nearest charged 1 and reported the second offer as fully funded.
7463 {
7464 Env env{*this, features};
7465 env.fund(XRP(10'000), issuer, maker, buyer);
7466 env.close();
7467
7468 MPT const usd = MPTTester({
7469 .env = env,
7470 .issuer = issuer,
7471 .holders = {maker, buyer},
7472 .transferFee = 1,
7473 .pay = 3,
7474 });
7475
7476 auto const firstOfferSeq = env.seq(maker);
7477 env(offer(maker, XRP(1), usd(1)));
7478 auto const secondOfferSeq = env.seq(maker);
7479 env(offer(maker, XRP(1), usd(1)));
7480 env.close();
7481
7482 json::Value const jrr = getBookOffers(env, XRP, usd);
7483 json::Value const& bookOffers = jrr[jss::offers];
7484 BEAST_EXPECT(bookOffers.isArray());
7485 if (BEAST_EXPECT(bookOffers.size() == 2))
7486 {
7487 json::Value const& firstOffer = bookOffers[0u];
7488 BEAST_EXPECT(firstOffer[sfSequence.jsonName] == firstOfferSeq);
7489 BEAST_EXPECT(firstOffer[jss::owner_funds] == "3");
7490 BEAST_EXPECT(!firstOffer.isMember(jss::taker_gets_funded));
7491 BEAST_EXPECT(!firstOffer.isMember(jss::taker_pays_funded));
7492
7493 json::Value const& secondOffer = bookOffers[1u];
7494 BEAST_EXPECT(secondOffer[sfSequence.jsonName] == secondOfferSeq);
7495 BEAST_EXPECT(secondOffer.isMember(jss::taker_gets_funded));
7496 BEAST_EXPECT(secondOffer[jss::taker_gets_funded][jss::value] == "0");
7497 BEAST_EXPECT(secondOffer.isMember(jss::taker_pays_funded));
7498 BEAST_EXPECT(secondOffer[jss::taker_pays_funded] == "0");
7499 }
7500
7501 // Execution on the same ledger state agrees: the buyer gets 1 MPT
7502 // from the first offer, the maker pays 2, and the second offer
7503 // delivers nothing. (.pay funded the buyer with 3 as well.)
7504 env(offer(buyer, usd(2), XRP(2)));
7505 env.close();
7506 BEAST_EXPECT(env.balance(buyer, usd) == usd(3 + 1));
7507 BEAST_EXPECT(env.balance(maker, usd) == usd(3 - 2));
7508 }
7509
7510 // A large MPT balance used to overflow the fee adjustment. divide()
7511 // assumes an IOU mantissa, always normalized into [1e15, 1e16), and
7512 // scales the numerator by 1e17. An MPT mantissa is the raw int64
7513 // balance, so past ~1.8e17 the scaled quotient leaves uint64 range and
7514 // throws -- failing the whole RPC with "internal", so one offer owner
7515 // blanked the entire book for every caller.
7516 //
7517 // The quotient itself always fits, because the branch only runs when
7518 // the rate exceeds parity. The cases below pin that at the edges of
7519 // the domain rather than leaving it to inspection.
7520 auto const checkLargeOwnerFunds =
7521 [&](std::uint16_t transferFee, std::int64_t funds, char const* expectedFunded) {
7522 Env env{*this, features};
7523 env.fund(XRP(10'000), issuer, maker, buyer);
7524 env.close();
7525
7526 MPT const usd = MPTTester({
7527 .env = env,
7528 .issuer = issuer,
7529 .holders = {maker, buyer},
7530 .transferFee = transferFee,
7531 .maxAmt = kMaxMpTokenAmount,
7532 });
7533 env(pay(issuer, maker, usd(funds)));
7534 env.close();
7535
7536 auto const offerSeq = env.seq(maker);
7537 env(offer(maker, XRP(100), usd(funds)));
7538 env.close();
7539
7540 json::Value const jrr = getBookOffers(env, XRP, usd);
7541 BEAST_EXPECT(!jrr.isMember(jss::error));
7542 json::Value const& bookOffers = jrr[jss::offers];
7543 BEAST_EXPECT(bookOffers.isArray());
7544 if (!BEAST_EXPECT(bookOffers.size() == 1))
7545 return;
7546
7547 json::Value const& offer = bookOffers[0u];
7548 BEAST_EXPECT(offer[sfAccount.jsonName] == maker.human());
7549 BEAST_EXPECT(offer[sfSequence.jsonName] == offerSeq);
7550 BEAST_EXPECT(offer[jss::owner_funds] == std::to_string(funds));
7551 BEAST_EXPECT(offer[jss::taker_gets_funded][jss::value] == expectedFunded);
7552 };
7553
7554 // Above the ~2.77e17 boundary at the maximum transfer rate of 1.5:
7555 // 3e17 of owner funds covers 2e17 delivered.
7556 checkLargeOwnerFunds(kMaxTransferFee, 300'000'000'000'000'000LL, "200000000000000000");
7557 // Large balance at the maximum rate. Kept at 6e18 so that 6e18 * 1.5
7558 // stays representable: offer crossing's rate-preservation path
7559 // overflows above that, which is a separate defect from this one.
7560 checkLargeOwnerFunds(kMaxTransferFee, 6'000'000'000'000'000'000LL, "4000000000000000000");
7561 // Near-maximum balance at the smallest rate above parity. This is the
7562 // largest quotient the branch can produce, and the case the old code
7563 // failed earliest on -- its overflow boundary is lowest, ~1.8e17, when
7564 // the rate is closest to parity.
7565 checkLargeOwnerFunds(1, 9'000'000'000'000'000'000LL, "8999910000899991000");
7566
7567 // An MPT global lock makes book_offers report the locked MPT book
7568 // liquidity as zero-funded instead of funded.
7569 {
7570 Env env{*this, features};
7571
7572 env.fund(XRP(10'000), issuer, maker, buyer);
7573 env.close();
7574
7575 MPTTester musd({
7576 .env = env,
7577 .issuer = issuer,
7578 .holders = {maker, buyer},
7579 .pay = 100,
7580 .flags = kMptDexFlags | tfMPTCanLock,
7581 });
7582 MPT const usd = musd;
7583
7584 auto const offerSeq = env.seq(maker);
7585 env(offer(maker, XRP(100), usd(100)));
7586 env.close();
7587
7588 {
7589 json::Value const jrr = getBookOffers(env, XRP, usd);
7590 json::Value const& bookOffers = jrr[jss::offers];
7591 BEAST_EXPECT(bookOffers.isArray());
7592 if (!BEAST_EXPECT(bookOffers.size() == 1))
7593 return;
7594
7595 json::Value const& offer = bookOffers[0u];
7596 BEAST_EXPECT(offer[sfAccount.jsonName] == maker.human());
7597 BEAST_EXPECT(offer[sfSequence.jsonName] == offerSeq);
7598 BEAST_EXPECT(offer[jss::owner_funds] == "100");
7599 BEAST_EXPECT(!offer.isMember(jss::taker_gets_funded));
7600 BEAST_EXPECT(!offer.isMember(jss::taker_pays_funded));
7601 }
7602
7603 musd.set({.flags = tfMPTLock});
7604
7605 {
7606 // The lock does not remove the offer from the ledger;
7607 // book_offers must report it as zero-funded liquidity.
7608 auto const bookOffers = getBookOffers(env, XRP, usd)[jss::offers];
7609 BEAST_EXPECT(bookOffers.isArray() && bookOffers.size() == 1);
7610
7611 json::Value const& offer = bookOffers[0u];
7612 BEAST_EXPECT(offer[sfAccount] == maker.human());
7613 BEAST_EXPECT(offer[sfSequence] == offerSeq);
7614 BEAST_EXPECT(offer[jss::owner_funds] == "0");
7615 BEAST_EXPECT(offer.isMember(jss::taker_gets_funded));
7616 BEAST_EXPECT(offer[jss::taker_gets_funded][jss::value] == "0");
7617 BEAST_EXPECT(offer.isMember(jss::taker_pays_funded));
7618 BEAST_EXPECT(offer[jss::taker_pays_funded] == "0");
7619 }
7620 }
7621 }
7622
7623 // getBookBase hashes raw concatenations of fixed-width fields, so the
7624 // (Issue,MPT) preimage `currency(20)||mptID(24)||account(20)` and the
7625 // (MPT,Issue) preimage `mptID(24)||currency(20)||account(20)` are both
7626 // 64 bytes and collide when the bytes align. An attacker picks the IOU
7627 // currency, reuses an IOU issuer, and grinds an MPT issuer / sequence;
7628 // the per-branch discriminator in getBookBase blocks this.
7629 void
7631 {
7632 testcase("getBookBase: (Issue,MPT) vs (MPT,Issue) preimage collision");
7633
7634 // Construction recipe:
7635 // issuerB last 4 bytes == seq_A; mptID_B = BE(5) || issuerB
7636 // currencyA == mptID_B[0..19] = BE(5) || issuerB[0..15]
7637 // issuerA == currencyB (both 20-byte all-0xBB)
7638 // sharedIOUIssuer == acct_A == acct_B
7639 AccountID issuerB;
7640 AccountID issuerA;
7641 Currency currencyB;
7642 Currency currencyA;
7643 AccountID sharedIOUIssuer;
7644 BEAST_EXPECT(issuerB.parseHex("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA00000007"));
7645 BEAST_EXPECT(issuerA.parseHex("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"));
7646 BEAST_EXPECT(currencyB.parseHex("BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"));
7647 BEAST_EXPECT(currencyA.parseHex("00000005AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
7648 BEAST_EXPECT(sharedIOUIssuer.parseHex("CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"));
7649
7650 Book const bookA{
7651 Asset{Issue{currencyA, sharedIOUIssuer}},
7652 Asset{MPTIssue{0x00000007u, issuerA}},
7653 std::nullopt};
7654 Book const bookB{
7655 Asset{MPTIssue{0x00000005u, issuerB}},
7656 Asset{Issue{currencyB, sharedIOUIssuer}},
7657 std::nullopt};
7658
7659 BEAST_EXPECT(bookA != bookB);
7660 BEAST_EXPECT(getBookBase(bookA) != getBookBase(bookB));
7661 }
7662
7663 // (MPT,MPT) bodies are 48 bytes and can't length-match the 64-byte
7664 // mixed branches, but tag them too for symmetry/future-proofing; this
7665 // test also pins the directional asymmetry of an (MPT,MPT) book.
7666 void
7668 {
7669 testcase("getBookBase: (MPT,MPT) distinguishes from mixed branches");
7670
7671 AccountID issuerX;
7672 AccountID issuerY;
7673 Currency currency;
7674 AccountID iouIssuer;
7675 BEAST_EXPECT(issuerX.parseHex("1111111111111111111111111111111111111111"));
7676 BEAST_EXPECT(issuerY.parseHex("2222222222222222222222222222222222222222"));
7677 BEAST_EXPECT(currency.parseHex("3333333333333333333333333333333333333333"));
7678 BEAST_EXPECT(iouIssuer.parseHex("4444444444444444444444444444444444444444"));
7679
7680 Asset const mptX{MPTIssue{1u, issuerX}};
7681 Asset const mptY{MPTIssue{2u, issuerY}};
7682 Book const mptBook{mptX, mptY, std::nullopt};
7683 Book const mixedBook{mptX, Asset{Issue{currency, iouIssuer}}, std::nullopt};
7684 Book const reversedMptBook{mptY, mptX, std::nullopt};
7685
7686 BEAST_EXPECT(getBookBase(mptBook) != getBookBase(mixedBook));
7687 BEAST_EXPECT(getBookBase(mptBook) != getBookBase(reversedMptBook));
7688 }
7689
7690 void
7692 {
7693 testcase("getBookBase: domain does not reopen MPT preimage collisions");
7694
7695 // The type tag is a front prefix and the domain is a 32-byte suffix, so a
7696 // domain'd book must (a) stay distinct from its public counterpart and
7697 // (b) preserve the mixed-branch tag distinction that the public case has.
7698 AccountID issuerX, issuerY, iouIssuer;
7699 Currency currency;
7700 BEAST_EXPECT(issuerX.parseHex("1111111111111111111111111111111111111111"));
7701 BEAST_EXPECT(issuerY.parseHex("2222222222222222222222222222222222222222"));
7702 BEAST_EXPECT(currency.parseHex("3333333333333333333333333333333333333333"));
7703 BEAST_EXPECT(iouIssuer.parseHex("4444444444444444444444444444444444444444"));
7704
7705 UInt256 const domainA = UInt256::fromVoid(
7706 "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD"
7707 "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD");
7708
7709 Asset const mptX{MPTIssue{1u, issuerX}};
7710 Asset const iou{Issue{currency, iouIssuer}};
7711
7712 // (a) same pair, public vs domain'd -> distinct directories.
7713 Book const publicBook{mptX, iou, std::nullopt};
7714 Book const domainBook{mptX, iou, domainA};
7715 BEAST_EXPECT(getBookBase(publicBook) != getBookBase(domainBook));
7716
7717 // (b) mixed-branch tag distinction still holds *with* a domain set:
7718 // (MPT,Issue) vs (Issue,MPT), both domain'd, must not collide.
7719 Book const mi{mptX, iou, domainA};
7720 Book const im{iou, mptX, domainA};
7721 BEAST_EXPECT(mi != im);
7722 BEAST_EXPECT(getBookBase(mi) != getBookBase(im));
7723 }
7724
7725 void
7727 {
7728 // A large MPT taker crosses a resting offer in full. Alice's rate
7729 // (kBigMpt per XRP) used to exceed 2^64 in divide(), so getRate()
7730 // returned 0 on her side while bob's side was representable. Under
7731 // MPTokensV2 both sides are representable.
7732 testcase("MPT Offer large rate - crosses in full");
7733
7734 using namespace jtx;
7735
7736 // divide() scales the XRP denominator up to a 1e15 mantissa, so the
7737 // quotient is kBigMpt * 1e17 / 1e15, above 2^64.
7738 auto const kBigMpt = 200'000'000'000'000'000LL;
7739
7740 // Both scenarios are the same trade against the same resting offer,
7741 // and both execute identically (at bob's price). They differ only in
7742 // the price alice quotes.
7743 auto const runScenario = [&](STAmount const& aliceQuote) {
7744 Env env{*this, features};
7745 auto const gw = Account{"gateway"};
7746 auto const alice = Account{"alice"};
7747 auto const bob = Account{"bob"};
7748 env.fund(XRP(10'000), gw, alice, bob);
7749 env.close();
7750
7751 MPT const mpt = MPTTester(
7752 {.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = kMaxMpTokenAmount});
7753
7754 env(pay(gw, bob, mpt(kBigMpt)));
7755 env.close();
7756
7757 // Bob rests the sell side: TakerPays = XRP(1), TakerGets =
7758 // kBigMpt. getRate(TakerGets, TakerPays) is representable in this
7759 // direction, so preflight admits it and it rests at a normal
7760 // quality.
7761 BEAST_EXPECT(getRate(mpt(kBigMpt), XRP(1)) != 0);
7762 auto const bobSeq = env.seq(bob);
7763 env(offer(bob, XRP(1), mpt(kBigMpt)), Ter(tesSUCCESS));
7764 env.close();
7765 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
7766
7767 // Alice takes it from the other side: TakerPays = kBigMpt,
7768 // TakerGets = her quote.
7769 BEAST_EXPECT(
7770 amountFromQuality(getRate(aliceQuote, mpt(kBigMpt))) ==
7771 STAmount(noIssue(), Number{mpt(kBigMpt).value()} / Number{aliceQuote}));
7772
7773 auto const bobXrpBefore = env.balance(bob).value().xrp();
7774 env(offer(alice, mpt(kBigMpt), aliceQuote), Ter(tesSUCCESS));
7775 env.close();
7776
7777 // Alice's offer crosses bob's in full, so it never rests.
7778 BEAST_EXPECT(env.balance(alice, mpt) == mpt(kBigMpt));
7779 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) == nullptr);
7780 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7781 // And it executes at bob's 1 XRP, whatever alice quoted.
7782 BEAST_EXPECT(env.balance(bob).value().xrp() == bobXrpBefore + XRP(1).value().xrp());
7783 };
7784
7785 // Alice quotes bob's exact price.
7786 runScenario(XRP(1));
7787 // Alice quotes a price worse for herself. Same execution as above:
7788 // she pays 1 XRP for kBigMpt.
7789 runScenario(XRP(2));
7790 }
7791
7792 void
7794 {
7795 // A large MPT taker crosses PARTIALLY. The crossed portion executes at
7796 // the resting price, and the residual rests at its true quality. Its
7797 // rate used to exceed 2^64 in divide(), so getRate() returned 0 and
7798 // the residual was dropped.
7799 testcase("MPT Offer large rate - partial cross");
7800
7801 using namespace jtx;
7802
7803 auto const kBigMpt = 200'000'000'000'000'000LL;
7804
7805 Env env{*this, features};
7806 auto const gw = Account{"gateway"};
7807 auto const alice = Account{"alice"};
7808 auto const bob = Account{"bob"};
7809 env.fund(XRP(10'000), gw, alice, bob);
7810 env.close();
7811
7812 MPT const mpt = MPTTester(
7813 {.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = kMaxMpTokenAmount});
7814
7815 env(pay(gw, bob, mpt(kBigMpt)));
7816 env.close();
7817
7818 // Bob rests a sell of kBigMpt for XRP(1) -- representable on his side.
7819 auto const bobSeq = env.seq(bob);
7820 env(offer(bob, XRP(1), mpt(kBigMpt)), Ter(tesSUCCESS));
7821 env.close();
7822 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
7823
7824 // Alice asks for twice what bob has, at the same price. Her quotient
7825 // is above 2^64: mantissa ratio 4e17 / 2e15 = 200 > ~184.47.
7826 BEAST_EXPECT(getRate(XRP(2), mpt(2 * kBigMpt)) != 0);
7827
7828 auto const aliceXrpBefore = env.balance(alice).value().xrp();
7829 auto const fee = env.current()->fees().base;
7830
7831 env(offer(alice, mpt(2 * kBigMpt), XRP(2)), Ter(tesSUCCESS));
7832 env.close();
7833
7834 // The half that crossed executed at bob's price...
7835 BEAST_EXPECT(env.balance(alice, mpt) == mpt(kBigMpt));
7836 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) == nullptr);
7837 BEAST_EXPECT(
7838 env.balance(alice).value().xrp() == aliceXrpBefore - XRP(1).value().xrp() - fee);
7839 // ...and the half that did not rests at the same price.
7840 auto const aliceOffers = offersOnAccount(env, alice);
7841 if (BEAST_EXPECT(aliceOffers.size() == 1))
7842 {
7843 auto const& remainder = *aliceOffers.front();
7844 BEAST_EXPECT(remainder[sfTakerPays] == mpt(kBigMpt));
7845 BEAST_EXPECT(remainder[sfTakerGets] == XRP(1));
7846 BEAST_EXPECT(
7847 amountFromQuality(getQuality(remainder[sfBookDirectory])) ==
7848 STAmount(noIssue(), Number{mpt(kBigMpt).value()} / Number{XRP(1).value()}));
7849 }
7850 BEAST_EXPECT((*env.le(alice))[sfOwnerCount] == 2); // MPToken and offer
7851 }
7852
7853 void
7855 {
7856 // TickSize plus a large MPT quality plus a counterparty on the book.
7857 // The rate used to exceed 2^64 in divide(); now it is representable,
7858 // so the tick-rounding path runs, its divide() takes the same large
7859 // quotient, and the offer still crosses in full.
7860 testcase("MPT Offer large rate - tick size with crossing");
7861
7862 using namespace jtx;
7863
7864 auto const kBigMpt = 5'000'000'000'000'000'000LL;
7865
7866 Env env{*this, features};
7867 auto const gw = Account{"gateway"};
7868 auto const alice = Account{"alice"};
7869 auto const bob = Account{"bob"};
7870 env.fund(XRP(10'000), gw, alice, bob);
7871 env.close();
7872
7873 auto const usd = gw["USD"];
7874 env(trust(alice, usd(1'000)));
7875 env(pay(gw, alice, usd(100)));
7876 env.close();
7877
7878 auto txn = noop(gw);
7879 txn[sfTickSize.fieldName] = 5;
7880 env(txn);
7881 env.close();
7882 BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5);
7883
7884 MPT const mpt = MPTTester(
7885 {.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = kMaxMpTokenAmount});
7886 env(pay(gw, bob, mpt(kBigMpt)));
7887 env.close();
7888
7889 // Bob rests the sell side; representable in that direction.
7890 BEAST_EXPECT(getRate(mpt(kBigMpt), usd(1)) != 0);
7891 auto const bobSeq = env.seq(bob);
7892 env(offer(bob, usd(1), mpt(kBigMpt)), Ter(tesSUCCESS));
7893 env.close();
7894 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr);
7895
7896 // Alice takes it from the other side, with the tick size in force on
7897 // her TakerGets.
7898 BEAST_EXPECT(getRate(usd(1), mpt(kBigMpt)) != 0);
7899 env(offer(alice, mpt(kBigMpt), usd(1)), Ter(tesSUCCESS));
7900 env.close();
7901
7902 BEAST_EXPECT(env.balance(alice, mpt) == mpt(kBigMpt));
7903 BEAST_EXPECT(env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) == nullptr);
7904 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7905 }
7906
7907 void
7909 {
7910 // tfImmediateOrCancel and tfFillOrKill with a large MPT quality whose
7911 // quotient is above 2^64 in divide(). Fill-or-kill disables partial
7912 // payment (OfferCreate.cpp: flowCross is passed !tfFillOrKill), so a
7913 // not-fully-fillable offer crosses nothing and is killed.
7914 testcase("MPT Offer large rate - IOC and FoK");
7915
7916 using namespace jtx;
7917
7918 auto const kBigMpt = 200'000'000'000'000'000LL;
7919
7920 auto const runScenario = [&](std::uint32_t flags, TER expected) {
7921 Env env{*this, features};
7922 auto const gw = Account{"gateway"};
7923 auto const alice = Account{"alice"};
7924 auto const bob = Account{"bob"};
7925 env.fund(XRP(10'000), gw, alice, bob);
7926 env.close();
7927
7928 MPT const mpt = MPTTester(
7929 {.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = kMaxMpTokenAmount});
7930 env(pay(gw, bob, mpt(kBigMpt)));
7931 env.close();
7932
7933 auto const bobSeq = env.seq(bob);
7934 env(offer(bob, XRP(1), mpt(kBigMpt)), Ter(tesSUCCESS));
7935 env.close();
7936
7937 // Asking for twice what bob has forces a partial cross, so the
7938 // flag handling -- not the fully-crossed early return -- decides.
7939 BEAST_EXPECT(getRate(XRP(2), mpt(2 * kBigMpt)) != 0);
7940 env(offer(alice, mpt(2 * kBigMpt), XRP(2), flags), Ter(expected));
7941 env.close();
7942
7943 auto const bobOfferLive =
7944 env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq))) != nullptr;
7945 if (isTesSuccess(expected))
7946 {
7947 // Immediate-or-cancel: the crossed part is kept, the rest is
7948 // cancelled.
7949 BEAST_EXPECT(env.balance(alice, mpt) == mpt(kBigMpt));
7950 BEAST_EXPECT(!bobOfferLive);
7951 }
7952 else
7953 {
7954 // Fill-or-kill: the offer is not fully fillable, so nothing
7955 // crosses at all and bob's offer survives untouched.
7956 BEAST_EXPECT(env.balance(alice, mpt) == mpt(0));
7957 BEAST_EXPECT(bobOfferLive);
7958 }
7959 BEAST_EXPECT(offersOnAccount(env, alice).empty());
7960 };
7961
7962 runScenario(tfImmediateOrCancel, tesSUCCESS);
7963 runScenario(tfFillOrKill, tecKILLED);
7964 }
7965
7966 void
7968 {
7969 testCanceledOffer(features);
7970 testRmFundedOffer(features);
7971 testTinyPayment(features);
7972 testXRPTinyPayment(features);
7973 testInsufficientReserve(features);
7974 testFillModes(features);
7975 testMalformed(features);
7976 testExpiration(features);
7977 testUnfundedCross(features);
7978 testSelfCross(false, features);
7979 testSelfCross(true, features);
7980 testNegativeBalance(features);
7981 testOfferCrossWithXRP(true, features);
7982 testOfferCrossWithXRP(false, features);
7984 testOfferAcceptThenCancel(features);
7988 testCrossCurrencyStartXRP(features);
7989 testCrossCurrencyEndXRP(features);
7990 testCrossCurrencyBridged(features);
7991 testBridgedSecondLegDry(features);
7992 testOfferFeesConsumeFunds(features);
7993 testOfferCreateThenCross(features);
7994 testSellFlagBasic(features);
7995 testSellFlagExceedLimit(features);
7996 testGatewayCrossCurrency(features);
7997 testPartialCross(features);
7998 testXRPDirectCross(features);
7999 testDirectCross(features);
8000 testBridgedCross(features);
8001 testSellOffer(features);
8002 testSellWithFillOrKill(features);
8003 testTransferRateOffer(features);
8005 testSelfCrossOffer(features);
8006 testSelfIssueOffer(features);
8007 testDirectToDirectPath(features);
8009 testOfferInScaling(features);
8011 testSelfPayXferFeeOffer(features);
8012 testSelfPayUnlimitedFunds(features);
8013 testRequireAuth(features);
8014 testMissingAuth(features);
8015 testSelfAuth(features);
8016 testDeletedOfferIssuer(features);
8017 testTicketOffer(features);
8018 testTicketCancelOffer(features);
8037 testFillOrKill(features);
8038 testTickSize(features);
8039 testMPTOfferZeroRate(features);
8046 testZeroRateXrpIouOffer(features);
8047 testBookOffersMPTFunding(features);
8048 testAutoCreateReserve(features);
8052 }
8053
8054 void
8055 run() override
8056 {
8057 using namespace jtx;
8058 static FeatureBitset const kAll{testableAmendments()};
8059 testAll(kAll);
8060 }
8061};
8062
8064
8065} // namespace xrpl::test
A testsuite class.
Definition suite.h:52
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Represents a JSON value.
Definition json_value.h:121
bool isArray() const
UInt size() const
Number of values in array or object.
bool isMember(char const *key) const
Return true if the object has a member named key.
virtual Config & config()=0
static BaseUInt fromVoid(void const *data)
Definition base_uint.h:340
constexpr bool parseHex(std::string_view sv)
Parse a hex string into a base_uint.
Definition base_uint.h:526
Specifies an order book.
Definition Book.h:28
A currency issued by an account.
Definition Issue.h:18
bool native() const
Definition Issue.cpp:54
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
std::string getText() const override
static constexpr int kMinOffset
Definition STAmount.h:61
static constexpr std::uint64_t kMinValue
Definition STAmount.h:65
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry const > const_pointer
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
constexpr value_type value() const
Returns the underlying value.
Definition XRPAmount.h:225
void testMPTOfferLargeRateCrossable(FeatureBitset features)
void testMPTOfferFeePartialInStillFills(FeatureBitset features)
void testCurrencyConversionInParts(FeatureBitset features)
void run() override
Runs the suite.
void testCurrencyConversionEntire(FeatureBitset features)
void testMPTOfferFeeZeroInRemoved(FeatureBitset features)
void testXRPDirectCross(FeatureBitset features)
void testSellFlagExceedLimit(FeatureBitset features)
void testSelfPayUnlimitedFunds(FeatureBitset features)
void testCanceledOffer(FeatureBitset features)
void testMalformed(FeatureBitset features)
static std::vector< SLE::const_pointer > offersOnAccount(jtx::Env &env, jtx::Account account)
void testOfferAcceptThenCancel(FeatureBitset features)
static std::uint32_t lastClose(jtx::Env &env)
void testMPTOfferFeeZeroOutUnblocksBook(FeatureBitset features)
void testOfferInScalingWithXferRate(FeatureBitset features)
void testRequireAuth(FeatureBitset features)
void testUnfundedCross(FeatureBitset features)
void testMPTOfferFundsLimitedDustUnblocksBook(FeatureBitset features)
void testGatewayCrossCurrency(FeatureBitset features)
void testOfferCreateThenCross(FeatureBitset features)
void testMPTOfferLargeRatePartialCross(FeatureBitset features)
void testBookBaseDomainMptDistinct(FeatureBitset)
void testMPTOfferFeeZeroInUnblocksBook(FeatureBitset features)
void testInsufficientReserve(FeatureBitset features)
void testOfferInScaling(FeatureBitset features)
void testRmSmallIncreasedQOffersXRP(FeatureBitset features)
void testSelfAuth(FeatureBitset features)
void testMPTIssuerOfferUsesRemainingCapacity(FeatureBitset features)
void testMPTOfferLargeRateFlags(FeatureBitset features)
void testTransferRateOffer(FeatureBitset features)
void testTransferRateOverflowOffer(FeatureBitset features)
void testCurrencyConversionIntoDebt(FeatureBitset features)
void testSelfCrossOffer2(FeatureBitset features)
void testBridgedSecondLegDry(FeatureBitset features)
void testPartiallyFundedLargeMPTAsk(FeatureBitset features)
void testMPTOfferLargeTakerPaysQuality(FeatureBitset features)
void testTicketOffer(FeatureBitset features)
void testDestroyedMPTIssuanceBookInput(FeatureBitset features)
static std::vector< SLE::const_pointer > sortedOffersOnAccount(jtx::Env &env, jtx::Account const &acct)
void testRmSmallIncreasedQOffersMPT(FeatureBitset features)
void testPartiallyFundedMPTInputOfferZeroInput(FeatureBitset features)
void testTinyPayment(FeatureBitset features)
void testSelfCross(bool usePartner, FeatureBitset features)
void testCrossCurrencyBridged(FeatureBitset features)
void testNegativeBalance(FeatureBitset features)
void testSelfCrossOffer1(FeatureBitset features)
void testIOUOfferFeeZeroOutSlice(FeatureBitset features)
void testSellFlagBasic(FeatureBitset features)
void testMPTOfferFundsLimitedOwnerPays(FeatureBitset features)
void testBookBaseMixedAssetCollision(FeatureBitset)
void testSelfCrossOffer(FeatureBitset features)
void testDirectCross(FeatureBitset features)
void testSelfCrossLowQualityOffer(FeatureBitset features)
void testRmFundedOffer(FeatureBitset features)
void testMissingAuth(FeatureBitset features)
void testPartialCross(FeatureBitset features)
void testDeletedOfferIssuer(FeatureBitset features)
void testOfferCrossWithXRP(bool reverseOrder, FeatureBitset features)
void testSellWithFillOrKill(FeatureBitset features)
void testMPTOfferLargeRateTickSizeCross(FeatureBitset features)
void testSellOffer(FeatureBitset features)
void testMPTIssuerOfferZeroSelfDebit(FeatureBitset features)
void testMPTHolderOfferFeeZeroOutUnblocksBook(FeatureBitset features)
void testMPTAMMLimitQualityRounding(FeatureBitset features)
void testTicketCancelOffer(FeatureBitset features)
void testBookOffersMPTFunding(FeatureBitset features)
void testDirectToDirectPath(FeatureBitset features)
void testMPTOfferLargeRemainderCross(FeatureBitset features)
void testFillOrKill(FeatureBitset features)
void testCrossCurrencyStartXRP(FeatureBitset features)
void testZeroRateXrpIouOffer(FeatureBitset features)
void testMPTOfferZeroRate(FeatureBitset features)
void testExpiration(FeatureBitset features)
void testFillModes(FeatureBitset features)
void testCrossCurrencyEndXRP(FeatureBitset features)
void testOfferCrossWithLimitOverride(FeatureBitset features)
void testXRPOfferFeeZeroInSlice(FeatureBitset features)
void testXRPTinyPayment(FeatureBitset features)
void testTickSize(FeatureBitset features)
void testAutoCreateReserve(FeatureBitset features)
void testOfferFeesConsumeFunds(FeatureBitset features)
void testAll(FeatureBitset features)
void testMPTOfferFeeZeroOutRemoved(FeatureBitset features)
void testBridgedCross(FeatureBitset features)
static XRPAmount reserve(jtx::Env &env, std::uint32_t count)
void testSelfIssueOffer(FeatureBitset features)
void testBookBaseMptMptDistinct(FeatureBitset)
void testSelfPayXferFeeOffer(FeatureBitset features)
json::Value json() const
Definition PathSet.h:187
Convenience class to test AMM functionality.
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
std::string const & human() const
Returns the human readable public key.
AccountID id() const
Returns the Account ID.
A balance matches.
Definition balance.h:24
A transaction testing environment.
Definition Env.h:161
Application & app()
Definition Env.h:300
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
std::uint32_t ownerCount(Account const &account) const
Return the number of objects owned by an account.
Definition Env.cpp:266
std::shared_ptr< ReadView const > closed()
Returns the last closed ledger.
Definition Env.cpp:127
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
PrettyAmount limit(Account const &account, Issue const &issue) const
Returns the IOU limit on an account.
Definition Env.cpp:254
std::uint32_t seq(Account const &account) const
Returns the next sequence number on account.
Definition Env.cpp:302
Account const & master
Definition Env.h:165
PrettyAmount balance(Account const &account) const
Returns the XRP balance on an account.
Definition Env.cpp:201
void trust(STAmount const &amount, Account const &account)
Establish trust lines.
Definition Env.cpp:354
void require(Args const &... args)
Check a set of requirements.
Definition Env.h:766
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
Set the fee on a JTx.
Definition fee.h:20
Inject raw JSON.
Definition jtx_json.h:16
Test helper for creating, mutating, and asserting MPT and confidential MPT ledger state.
Definition mpt.h:512
std::int64_t getBalance(Account const &account) const
Definition mpt.cpp:956
void pay(Account const &src, Account const &dest, std::int64_t amount, std::optional< TER > err=std::nullopt, std::optional< std::vector< std::string > > credentials=std::nullopt, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:861
void set(MPTSet const &set={}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:581
void authorize(MPTAuthorize const &arg=MPTAuthorize{}, std::source_location const &loc=std::source_location::current())
Definition mpt.cpp:459
Converts to MPT Issue or STAmount.
Match the number of items in the account's owner directory.
Definition owners.h:55
Add a path.
Definition paths.h:47
Check a set of conditions.
Definition require.h:49
Sets the SendMax on a JTx.
Definition sendmax.h:16
Set the expected result code for a JTx The test will fail if the code doesn't match.
Definition ter.h:18
Set the flags on a JTx.
Definition txflags.h:14
Set a ticket sequence on a JTx.
Definition ticket.h:36
T distance(T... args)
T is_same_v
T make_unique(T... args)
@ Array
array value (ordered list)
Definition json_value.h:32
Keylet offer(AccountID const &id, SeqProxy const &seq) noexcept
An offer from an account.
Definition Indexes.cpp:310
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
json::Value create(Account const &account, std::uint32_t count)
Create one of more tickets.
Definition ticket.cpp:16
static NoneT const kNone
Definition tags.h:9
auto const kMptDexFlags
Definition mpt.h:47
json::Value ledgerEntryMPT(jtx::Env &env, jtx::Account const &acct, MPTID const &mptID)
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
static EpsilonT const kEpsilon
json::Value offerCancel(Account const &account, std::uint32_t offerSeq)
Cancel an offer.
Definition offer.cpp:31
void testHelper2TokensMix(TTester &&tester)
XrpT const XRP
Converts to XRP Issue or STAmount.
Definition amount.cpp:92
bool hasEnvelope2(json::Value const &reply)
Reports whether reply carries the version 2 envelope: jsonrpc equal to rpc::kJsonRpcVersion and rippl...
json::Value noop(Account const &account)
The null transaction.
Definition noop.h:14
json::Value getBookOffers(jtx::Env &env, Asset const &takerPays, Asset const &takerGets)
bool expectOffers(Env const &env, AccountID const &account, std::uint16_t size, std::vector< Amounts > const &toMatch)
XRPAmount txFee(Env const &env, std::uint16_t n)
FeatureBitset testableAmendments()
Definition Env.h:92
void testHelper3TokensMix(TTester &&tester)
OwnerCount< ltOFFER > Offers
Match the number of offers in the account's owner directory.
Definition owners.h:137
json::Value acctdelete(Account const &account, Account const &dest)
Delete account.
std::array< Account, 1+sizeof...(Args)> noripple(Account const &account, Args const &... args)
Designate accounts as no-ripple in Env::fund.
Definition Env.h:86
json::Value offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
Definition offer.cpp:14
json::Value ledgerEntryRoot(Env &env, Account const &acct)
std::unique_ptr< Config > envconfig()
creates and initializes a default configuration for jtx::Env
Definition envconfig.h:38
json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:18
OwnerCount< ltMPTOKEN > MPTokens
Match the number of MPToken in the account's owner directory.
Definition owners.h:142
PrettyAmount drops(Integer i)
Returns an XRP PrettyAmount, which is trivially convertible to STAmount.
json::Value rate(Account const &account, double multiplier)
Set a transfer rate.
Definition rate.cpp:15
OwnerCount< ltTICKET > Tickets
Match the number of tickets on the account.
Definition ticket.h:54
json::Value ledgerEntryOffer(jtx::Env &env, jtx::Account const &acct, std::uint32_t offerSeq)
bool isOffer(jtx::Env const &env, jtx::Account const &account, STAmount const &takerPays, STAmount const &takerGets)
An offer exists.
Definition PathSet.h:60
constexpr XRPAmount
Convert XRP to drops (integral types).
Definition TxTest.h:53
static XRPAmount reserve(jtx::Env const &env, std::uint32_t count)
BEAST_DEFINE_TESTSUITE_PRIO(AccountDelete, app, xrpl, 2)
std::unique_ptr< WSClient > makeWSClient(Config const &cfg, bool v2, unsigned rpcVersion, std::unordered_map< std::string, std::string > const &headers)
Returns a client operating through WebSockets/S.
Definition WSClient.cpp:373
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
void forEachItem(ReadView const &view, Keylet const &root, std::function< void(SLE::ConstRef)> const &f)
Iterate all items in the given directory.
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
@ RpcEntryNotFound
Definition ErrorCodes.h:144
UInt256 getBookBase(Book const &book)
Definition Indexes.cpp:136
std::uint64_t getQuality(UInt256 const &uBase)
Definition Indexes.cpp:207
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
@ tefEXCEPTION
Definition TER.h:166
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
BaseUInt< 160, detail::CurrencyTag > Currency
Currency is a hash representing a specific currency.
Definition UintTypes.h:42
Seed generateSeed(std::string const &passPhrase)
Generate a seed deterministically.
Definition Seed.cpp:58
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
@ Actor
Another account signed and submitted transactions on behalf of this account (this account is the owne...
BaseUInt< 256 > UInt256
Definition base_uint.h:581
STAmount amountFromQuality(std::uint64_t rate)
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
json::Value getJson(LedgerFill const &fill)
Return a new json::Value representing the ledger with given options.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
constexpr std::uint16_t kMaxTransferFee
The maximum token transfer fee allowed.
Definition Protocol.h:97
@ temBAD_CURRENCY
Definition TER.h:78
@ temBAD_AMOUNT
Definition TER.h:77
@ temREDUNDANT
Definition TER.h:100
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TERSubset< CanCvtToTER > TER
Definition TER.h:657
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:118
MPTID badMPT()
Definition MPTIssue.h:121
@ tecINSUF_RESERVE_OFFER
Definition TER.h:300
@ tecPATH_PARTIAL
Definition TER.h:293
@ tecPATH_DRY
Definition TER.h:305
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecNO_AUTH
Definition TER.h:311
@ tecUNFUNDED_OFFER
Definition TER.h:295
@ tecEXPIRED
Definition TER.h:325
@ tecKILLED
Definition TER.h:327
@ tecNO_ISSUER
Definition TER.h:310
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
@ tesSUCCESS
Definition TER.h:253
T remove_if(T... args)
T sort(T... args)
Represents an XRP, IOU, or MPT quantity This customizes the string conversion and supports XRP conver...
STAmount const & value() const
T to_string(T... args)