xrpld
Loading...
Searching...
No Matches
FlowMPT_test.cpp
1#include <test/jtx/Account.h>
2#include <test/jtx/Env.h>
3#include <test/jtx/PathSet.h>
4#include <test/jtx/TestHelpers.h>
5#include <test/jtx/amount.h>
6#include <test/jtx/balance.h>
7#include <test/jtx/mpt.h>
8#include <test/jtx/offer.h>
9#include <test/jtx/owners.h>
10#include <test/jtx/paths.h>
11#include <test/jtx/pay.h>
12#include <test/jtx/sendmax.h>
13#include <test/jtx/ter.h>
14#include <test/jtx/trust.h>
15#include <test/jtx/txflags.h>
16
17#include <xrpl/basics/base_uint.h>
18#include <xrpl/beast/unit_test/suite.h>
19#include <xrpl/core/ServiceRegistry.h>
20#include <xrpl/ledger/ApplyView.h>
21#include <xrpl/ledger/OpenView.h>
22#include <xrpl/ledger/PaymentSandbox.h>
23#include <xrpl/ledger/Sandbox.h>
24#include <xrpl/ledger/helpers/DirectoryHelpers.h>
25#include <xrpl/ledger/helpers/OfferHelpers.h>
26#include <xrpl/protocol/AccountID.h>
27#include <xrpl/protocol/Asset.h>
28#include <xrpl/protocol/Feature.h>
29#include <xrpl/protocol/Indexes.h>
30#include <xrpl/protocol/Keylet.h>
31#include <xrpl/protocol/LedgerFormats.h>
32#include <xrpl/protocol/Protocol.h>
33#include <xrpl/protocol/SField.h>
34#include <xrpl/protocol/STAmount.h>
35#include <xrpl/protocol/STPathSet.h>
36#include <xrpl/protocol/SeqProxy.h>
37#include <xrpl/protocol/TER.h>
38#include <xrpl/protocol/TxFlags.h>
39#include <xrpl/protocol/XRPAmount.h>
40#include <xrpl/tx/paths/Flow.h>
41#include <xrpl/tx/paths/detail/Steps.h>
42
43#include <cstdint>
44#include <initializer_list>
45#include <optional>
46#include <string>
47#include <type_traits>
48#include <utility>
49#include <vector>
50
51namespace xrpl::test {
52
54{
56
57 void
59 {
60 testcase("Direct Step");
61
62 using namespace jtx;
63 auto const alice = Account("alice");
64 auto const bob = Account("bob");
65 auto const carol = Account("carol");
66 auto const gw = Account("gw");
67 {
68 // Pay USD, trivial path
69 Env env(*this, features);
70
71 env.fund(XRP(10000), alice, bob, gw);
72 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
73 env(pay(gw, alice, usd(100)));
74 env(pay(alice, bob, usd(10)), Paths(usd));
75 env.require(Balance(bob, usd(10)));
76 }
77 {
78 // Partial payments
79 Env env(*this, features);
80
81 env.fund(XRP(10000), alice, bob, gw);
82 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
83 env(pay(gw, alice, usd(100)));
84 env(pay(alice, bob, usd(110)), Paths(usd), Ter(tecPATH_PARTIAL));
85 env.require(Balance(bob, usd(0)));
86 env(pay(alice, bob, usd(110)), Paths(usd), Txflags(tfPartialPayment));
87 env.require(Balance(bob, usd(100)));
88 }
89
90 {
91 // Limit quality
92 auto const test = [&](auto&& issue1, auto&& issue2) {
93 Env env(*this, features);
94
95 env.fund(XRP(10'000), gw, alice, bob, carol);
96 env.close();
97
98 auto const usd =
99 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol}});
100 auto const eur =
101 issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}});
102
103 env(pay(gw, alice, usd(100)));
104 env(pay(gw, bob, eur(100)));
105
106 env(offer(alice, eur(4), usd(4)));
107 env.close();
108
109 env(pay(bob, carol, usd(5)),
110 Sendmax(eur(4)),
111 Txflags(tfLimitQuality | tfPartialPayment),
113 env.require(Balance(carol, usd(0)));
114
115 env(pay(bob, carol, usd(5)), Sendmax(eur(4)), Txflags(tfPartialPayment));
116 env.require(Balance(carol, usd(4)));
117 };
119 }
120 }
121
122 void
124 {
125 testcase("Book Step");
126
127 using namespace jtx;
128
129 auto const gw = Account("gateway");
130 Account const alice("alice");
131 Account const bob("bob");
132 Account const carol("carol");
133
134 {
135 // simple [MPT|IOU]/[IOU|MPT] offer
136 auto const test = [&](auto&& issue1, auto&& issue2) {
137 Env env(*this, features);
138
139 env.fund(XRP(10'000), alice, bob, carol, gw);
140 env.close();
141
142 auto const usd = issue1(
143 {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}});
144 auto const btc = issue2(
145 {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}});
146
147 env(pay(gw, alice, btc(50)));
148 env(pay(gw, bob, usd(50)));
149
150 env(offer(bob, btc(50), usd(50)));
151
152 env(pay(alice, carol, usd(50)), Path(~usd), Sendmax(btc(50)));
153
154 env.require(Balance(alice, btc(0)));
155 env.require(Balance(bob, btc(50)));
156 env.require(Balance(bob, usd(0)));
157 env.require(Balance(carol, usd(50)));
158 BEAST_EXPECT(!isOffer(env, bob, btc(50), usd(50)));
159 };
161 }
162 {
163 // simple [MPT|IOU]/XRP XRP/[IOU|MPT] offer
164 auto const test = [&](auto&& issue1, auto&& issue2) {
165 Env env(*this, features);
166
167 env.fund(XRP(10'000), alice, bob, carol, gw);
168 env.close();
169
170 auto const usd = issue1(
171 {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}});
172 auto const btc = issue2(
173 {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}});
174
175 env(pay(gw, alice, btc(50)));
176 env(pay(gw, bob, usd(50)));
177
178 env(offer(bob, btc(50), XRP(50)));
179 env(offer(bob, XRP(50), usd(50)));
180
181 env(pay(alice, carol, usd(50)), Path(~XRP, ~usd), Sendmax(btc(50)));
182
183 env.require(Balance(alice, btc(0)));
184 env.require(Balance(bob, btc(50)));
185 env.require(Balance(bob, usd(0)));
186 env.require(Balance(carol, usd(50)));
187 BEAST_EXPECT(!isOffer(env, bob, XRP(50), usd(50)));
188 BEAST_EXPECT(!isOffer(env, bob, btc(50), XRP(50)));
189 };
191 }
192 {
193 // simple XRP -> USD through offer and sendmax
194 Env env(*this, features);
195
196 env.fund(XRP(10'000), alice, bob, carol, gw);
197 env.close();
198
199 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
200 MPT const btc = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
201
202 env(pay(gw, bob, usd(50)));
203
204 env(offer(bob, XRP(50), usd(50)));
205
206 env(pay(alice, carol, usd(50)), Path(~usd), Sendmax(XRP(50)));
207
208 // fee: MPTokenAuthorize * 2(EUR, USD) + pay
209 env.require(Balance(alice, XRP(10'000 - 50) - txFee(env, 3)));
210 // fee: MPTokenAuthorize * 2(EUR, USD) + offer
211 env.require(Balance(bob, XRP(10'000 + 50) - txFee(env, 3)));
212 env.require(Balance(bob, usd(0)));
213 env.require(Balance(carol, usd(50)));
214 BEAST_EXPECT(!isOffer(env, bob, XRP(50), usd(50)));
215 }
216 {
217 // simple USD -> XRP through offer and sendmax
218 Env env(*this, features);
219
220 env.fund(XRP(10'000), alice, bob, carol, gw);
221 env.close();
222
223 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
224 MPT const btc = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
225
226 env(pay(gw, alice, usd(50)));
227
228 env(offer(bob, usd(50), XRP(50)));
229
230 env(pay(alice, carol, XRP(50)), Path(~XRP), Sendmax(usd(50)));
231
232 env.require(Balance(alice, usd(0)));
233 env.require(Balance(bob, XRP(10'000 - 50) - txFee(env, 3)));
234 env.require(Balance(bob, usd(50)));
235 env.require(Balance(carol, XRP(10'000 + 50) - txFee(env, 2)));
236 BEAST_EXPECT(!isOffer(env, bob, usd(50), XRP(50)));
237 }
238 {
239 // test unfunded offers are removed when payment succeeds
240 auto const test = [&](auto&& issue1, auto&& issue2, auto&& issue3) {
241 Env env(*this, features);
242
243 env.fund(XRP(10'000), alice, bob, carol, gw);
244 env.close();
245
246 auto const usd = issue1(
247 {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}});
248 auto const btc = issue2(
249 {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}});
250 auto const eur = issue3(
251 {.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob, carol}});
252
253 env(pay(gw, alice, btc(60)));
254 env(pay(gw, bob, usd(50)));
255 env(pay(gw, bob, eur(50)));
256
257 env(offer(bob, btc(50), usd(50)));
258 env(offer(bob, btc(40), eur(50)));
259 env(offer(bob, eur(50), usd(50)));
260
261 // unfund offer
262 env(pay(bob, gw, eur(50)));
263 env.require(Balance(bob, eur(0)));
264 BEAST_EXPECT(isOffer(env, bob, btc(50), usd(50)));
265 BEAST_EXPECT(isOffer(env, bob, btc(40), eur(50)));
266 BEAST_EXPECT(isOffer(env, bob, eur(50), usd(50)));
267
268 env(pay(alice, carol, usd(50)), Path(~usd), Path(~eur, ~usd), Sendmax(btc(60)));
269
270 env.require(Balance(alice, btc(10)));
271 env.require(Balance(bob, btc(50)));
272 env.require(Balance(bob, usd(0)));
273 env.require(Balance(bob, eur(0)));
274 env.require(Balance(carol, usd(50)));
275 // used in the payment
276 BEAST_EXPECT(!isOffer(env, bob, btc(50), usd(50)));
277 // found unfunded
278 BEAST_EXPECT(!isOffer(env, bob, btc(40), eur(50)));
279 // unfunded, but should not yet be found unfunded
280 BEAST_EXPECT(isOffer(env, bob, eur(50), usd(50)));
281 };
283 }
284 {
285 // test unfunded offers are returned when the payment fails.
286 // bob makes two offers: a funded 5000 USD for 50 BTC and an
287 // unfunded 5000 EUR for 60 BTC. alice pays carol 6100 USD with 61
288 // BTC. alice only has 60 BTC, so the payment will fail. The payment
289 // uses two paths: one through bob's funded offer and one through
290 // his unfunded offer. When the payment fails `flow` should return
291 // the unfunded offer. This test is intentionally similar to the one
292 // that removes unfunded offers when the payment succeeds.
293 auto const test = [&](auto&& issue1, auto&& issue2, auto&& issue3) {
294 Env env(*this, features);
295
296 env.fund(XRP(10'000), alice, bob, carol, gw);
297 env.close();
298
299 auto const usd = issue1({
300 .env = env,
301 .token = "USD",
302 .issuer = gw,
303 .holders = {alice, bob, carol},
304 .limit = 100'000,
305 });
306 auto const btc = issue2({
307 .env = env,
308 .token = "BTC",
309 .issuer = gw,
310 .holders = {alice, bob, carol},
311 .limit = 100'000,
312 });
313 auto const eur = issue3({
314 .env = env,
315 .token = "EUR",
316 .issuer = gw,
317 .holders = {alice, bob, carol},
318 .limit = 100'000,
319 });
320
321 env(pay(gw, alice, btc(60)));
322 env(pay(gw, bob, usd(6'000)));
323 env(pay(gw, bob, eur(5'000)));
324 env(pay(gw, carol, eur(100)));
325
326 env(offer(bob, btc(50), usd(5'000)));
327 env(offer(bob, btc(60), eur(5'000)));
328 env(offer(carol, btc(1'000), eur(100)));
329 env(offer(bob, eur(5'000), usd(5'000)));
330
331 // unfund offer
332 env(pay(bob, gw, eur(5'000)));
333 BEAST_EXPECT(isOffer(env, bob, btc(50), usd(5'000)));
334 BEAST_EXPECT(isOffer(env, bob, btc(60), eur(5'000)));
335 BEAST_EXPECT(isOffer(env, carol, btc(1'000), eur(100)));
336
337 auto flowJournal = env.app().getLogs().journal("Flow");
338 auto const flowResult = [&] {
339 STAmount const deliver(usd(5'100));
340 STAmount smax(btc(61));
341 PaymentSandbox sb(env.current().get(), TapNone);
342 STPathSet paths;
343 auto const ipe = [](Asset const& asset) {
344 return STPathElement(
346 xrpAccount(),
347 asset,
348 asset.getIssuer());
349 };
350 {
351 // BTC -> USD
352 STPath const p1({ipe(usd)});
353 paths.pushBack(p1);
354 // BTC -> EUR -> USD
355 STPath const p2({ipe(eur), ipe(usd)});
356 paths.pushBack(p2);
357 }
358
359 return flow(
360 sb,
361 deliver,
362 alice,
363 carol,
364 paths,
365 false,
366 false,
367 true,
369 std::nullopt,
370 smax,
371 std::nullopt,
372 flowJournal);
373 }();
374
375 BEAST_EXPECT(flowResult.removableOffers.size() == 1);
376 env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) {
377 if (flowResult.removableOffers.empty())
378 return false;
379 Sandbox sb(&view, TapNone);
380 for (auto const& o : flowResult.removableOffers)
381 {
382 if (auto const ok = sb.peek(keylet::offer(o)))
383 offerDelete(sb, ok, flowJournal);
384 }
385 sb.apply(view);
386 return true;
387 });
388
389 // used in payment, but since payment failed should
390 // be untouched
391 BEAST_EXPECT(isOffer(env, bob, btc(50), usd(5'000)));
392 BEAST_EXPECT(isOffer(env, carol, btc(1'000), eur(100)));
393 // found unfunded
394 BEAST_EXPECT(!isOffer(env, bob, btc(60), eur(5'000)));
395 };
397 }
398 {
399 // Do not produce more in the forward pass than the
400 // reverse pass. This test uses a path whose reverse
401 // pass will compute a 0.5 USD input required for a 1
402 // EUR output. It sets a sendmax of 0.4 USD, so the
403 // payment engine will need to do a forward pass.
404 // Without limits, the 0.4 USD would produce 1000 EUR in
405 // the forward pass. This test checks that the payment
406 // produces 1 EUR, as expected.
407 auto const test = [&](auto&& issue1, auto&& issue2) {
408 Env env(*this, features);
409 env.fund(XRP(10'000), alice, bob, carol, gw);
410
411 auto const usd = issue1(
412 {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}});
413 auto const eur = issue1(
414 {.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob, carol}});
415
416 env(pay(gw, alice, usd(1'000)));
417 env(pay(gw, bob, eur(1'000)));
418
419 Keylet const bobUsdOffer = keylet::offer(bob, SeqProxy::rawSequence(env.seq(bob)));
420 env(offer(bob, usd(10), drops(2)), Txflags(tfPassive));
421 env(offer(bob, drops(1), eur(1'000)), Txflags(tfPassive));
422
423 bool const reducedOffersV2 = features[fixReducedOffersV2];
424
425 // With reducedOffersV2, it is not allowed to accept
426 // less than USD(0.5) of bob's USD offer. If we
427 // provide 1 drop for less than USD(0.5), then the
428 // remaining fractional offer would block the order
429 // book.
430 TER const expectedTER = reducedOffersV2 ? TER(tecPATH_DRY) : TER(tesSUCCESS);
431 env(pay(alice, carol, eur(1)),
432 Path(~XRP, ~eur),
433 Sendmax(usd(4)),
434 Txflags(tfNoRippleDirect | tfPartialPayment),
435 Ter(expectedTER));
436
437 if (!reducedOffersV2)
438 {
439 env.require(Balance(carol, eur(1)));
440 env.require(Balance(bob, usd(4)));
441 env.require(Balance(bob, eur(999)));
442
443 // Show that bob's USD offer is now a blocker.
444 SLE::const_pointer const usdOffer = env.le(bobUsdOffer);
445 if (BEAST_EXPECT(usdOffer))
446 {
447 std::uint64_t const bookRate = [&usdOffer] {
448 // Extract the least significant 64
449 // bits from the book page. That's
450 // where the quality is stored.
451 std::string bookDirStr = to_string(usdOffer->at(sfBookDirectory));
452 bookDirStr.erase(0, 48);
453 return std::stoull(bookDirStr, nullptr, 16);
454 }();
455 std::uint64_t const actualRate =
456 getRate(usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays));
457
458 // We expect the actual rate of the offer to
459 // be worse (larger) than the rate of the
460 // book page holding the offer. This is a
461 // defect which is corrected by
462 // fixReducedOffersV2.
463 BEAST_EXPECT(actualRate > bookRate);
464 }
465 }
466 };
468 }
469 }
470
471 void
473 {
474 testcase("Transfer Rate");
475
476 using namespace jtx;
477
478 auto const gw = Account("gateway");
479 Account const alice("alice");
480 Account const bob("bob");
481 Account const carol("carol");
482
483 {
484 // Simple payment through a gateway with a
485 // transfer rate
486 Env env(*this, features);
487
488 env.fund(XRP(10000), alice, bob, carol, gw);
489
490 MPT const usd = MPTTester({
491 .env = env,
492 .issuer = gw,
493 .holders = {alice, bob, carol},
494 .transferFee = 25'000,
495 .maxAmt = 1'000,
496 });
497
498 env(pay(gw, alice, usd(50)));
499 env.require(Balance(alice, usd(50)));
500 env(pay(alice, bob, usd(40)), Sendmax(usd(50)));
501 env.require(Balance(bob, usd(40)), Balance(alice, usd(0)));
502 }
503 {
504 // transfer rate is not charged when issuer is src or
505 // dst
506 Env env(*this, features);
507
508 env.fund(XRP(10'000), alice, bob, carol, gw);
509
510 MPT const usd = MPTTester({
511 .env = env,
512 .issuer = gw,
513 .holders = {alice, bob, carol},
514 .transferFee = 25'000,
515 .maxAmt = 1'000,
516 });
517
518 env(pay(gw, alice, usd(50)));
519 env.require(Balance(alice, usd(50)));
520 env(pay(alice, gw, usd(40)), Sendmax(usd(40)));
521 env.require(Balance(alice, usd(10)));
522 }
523 {
524 // transfer fee on an offer
525 Env env(*this, features);
526
527 env.fund(XRP(10'000), alice, bob, carol, gw);
528
529 MPT const usd = MPTTester({
530 .env = env,
531 .issuer = gw,
532 .holders = {alice, bob, carol},
533 .transferFee = 25'000,
534 .maxAmt = 10'000,
535 });
536
537 // scale by 1
538 env(pay(gw, bob, usd(650)));
539
540 env(offer(bob, XRP(50), usd(500)));
541
542 env(pay(alice, carol, usd(500)),
543 Path(~usd),
544 Sendmax(XRP(50)),
545 Txflags(tfPartialPayment));
546
547 // bob pays 25% on 500USD -> 100USD; 400USD goes to carol
548 env.require(
549 Balance(alice, XRP(10'000 - 50) - txFee(env, 2)),
550 Balance(bob, usd(150)),
551 Balance(carol, usd(400)));
552 }
553 {
554 // Transfer fee two consecutive offers
555 auto const test = [&](auto&& issue1, auto&& issue2) {
556 Env env(*this, features);
557
558 env.fund(XRP(10'000), alice, bob, carol, gw);
559 env.close();
560
561 auto const usd = issue1({
562 .env = env,
563 .token = "USD",
564 .issuer = gw,
565 .holders = {alice, bob, carol},
566 .limit = 1'000,
567 .transferFee = 25'000,
568 });
569 auto const eur = issue2({
570 .env = env,
571 .token = "EUR",
572 .issuer = gw,
573 .holders = {alice, bob, carol},
574 .limit = 1'000,
575 .transferFee = 25'000,
576 });
577
578 env(pay(gw, bob, usd(50)));
579 env(pay(gw, bob, eur(50)));
580
581 env(offer(bob, XRP(50), usd(50)));
582 env(offer(bob, usd(50), eur(50)));
583
584 env(pay(alice, carol, eur(40)),
585 Path(~usd, ~eur),
586 Sendmax(XRP(40)),
587 Txflags(tfPartialPayment));
588 // +1 for fset in helperIssueIOU
589 using TEur = std::decay_t<decltype(eur)>;
590 auto const fee = txFee(env, 3);
591 // bob pays 25% on 40USD (40 since sendmax is 40XRP)
592 // 8USD goes to gw and 32USD goes back to bob ->
593 // bob's USD balance is 42USD. USD/EUR offer is 32USD/32EUR.
594 // bob pays 25% on 32EUR -> 7EUR if MPT, 6.4EUR if IOU,
595 // therefore carl gets 25EUR if MPT, 25.6EUR if IOU.
596 auto const carolEUR = [&] {
597 if constexpr (std::is_same_v<TEur, IOU>)
598 {
599 return eur(25.6);
600 }
601 else
602 {
603 return eur(25);
604 }
605 }();
606 env.require(
607 Balance(alice, XRP(10'000 - 40) - fee),
608 Balance(bob, usd(42)),
609 Balance(bob, eur(18)),
610 Balance(carol, carolEUR));
611 };
613 }
614 {
615 // Offer where the owner is also the issuer, sender pays
616 // fee
617 Env env(*this, features);
618
619 env.fund(XRP(10'000), alice, bob, gw);
620
621 MPT const usd = MPTTester({
622 .env = env,
623 .issuer = gw,
624 .holders = {alice, bob},
625 .transferFee = 25'000,
626 .maxAmt = 1'000,
627 });
628
629 env(offer(gw, XRP(100), usd(100)));
630 env(pay(alice, bob, usd(100)), Sendmax(XRP(100)), Txflags(tfPartialPayment));
631 env.require(Balance(alice, XRP(10'000 - 100) - txFee(env, 2)), Balance(bob, usd(80)));
632 }
633 {
634 // Offer where the owner is also the issuer, sender pays
635 // fee
636 Env env(*this, features);
637
638 env.fund(XRP(10'000), alice, bob, gw);
639
640 MPT const usd = MPTTester({
641 .env = env,
642 .issuer = gw,
643 .holders = {alice, bob},
644 .transferFee = 25'000,
645 .maxAmt = 1'000,
646 });
647
648 env(offer(gw, XRP(125), usd(125)));
649 env(pay(alice, bob, usd(100)), Sendmax(XRP(200)));
650 env.require(Balance(alice, XRP(10'000 - 125) - txFee(env, 2)), Balance(bob, usd(100)));
651 }
652 }
653
654 void
656 {
657 testcase("MPT Endpoint transfer rate overflow");
658
659 using namespace jtx;
660
661 Account const iouGW("iou_gateway");
662 Account const mptGW("mpt_gateway");
663 Account const alice("alice");
664 Account const bob("bob");
665
666 {
667 // Control: the same issuer-owned offer path works when the
668 // transfer-fee-adjusted input amount remains representable.
669 Env env(*this, features);
670
671 std::int64_t constexpr deliverAmount = 1'000'000'000'000'000'000LL;
672 std::int64_t constexpr offerAmount = deliverAmount + (deliverAmount / 2);
673
674 env.fund(XRP(10'000), iouGW, mptGW, alice, bob);
675 env.close();
676
677 auto const usd = iouGW["USD"];
678 env.trust(usd(offerAmount), alice);
679 env.trust(usd(offerAmount), mptGW);
680 env(pay(iouGW, alice, usd(offerAmount)));
681
682 MPTTester const mpt(
683 {.env = env, .issuer = mptGW, .holders = {bob}, .transferFee = kMaxTransferFee});
684
685 env(offer(mptGW, usd(offerAmount), mpt(offerAmount)));
686
687 env(pay(alice, bob, mpt(deliverAmount)),
688 Path(~mpt),
689 Sendmax(usd(offerAmount)),
690 Txflags(tfNoRippleDirect | tfPartialPayment));
691
692 env.require(Balance(alice, usd(0)), Balance(bob, mpt(deliverAmount)));
693 BEAST_EXPECT(!isOffer(env, mptGW, usd(offerAmount), mpt(offerAmount)));
694 }
695 {
696 // Regression: an extreme transfer-fee-adjusted MPT amount used to
697 // throw from MPTAmount::mulRatio during the endpoint reverse pass.
698 // The reverse pass now caps srcToDst at the largest amount whose
699 // transfer-fee-adjusted input is representable, so the offer limits
700 // the strand and a partial payment goes through.
701 Env env(*this, features);
702
703 std::int64_t constexpr overflowAmount = 7'000'000'000'000'000'000LL;
704 // The offer caps the input at overflowAmount, which the maximum
705 // transfer rate of 1.5 scales down to 7e18 * 2 / 3, rounded down
706 std::int64_t constexpr deliveredAmount = 4'666'666'666'666'666'666LL;
707
708 env.fund(XRP(10'000), iouGW, mptGW, alice, bob);
709 env.close();
710
711 auto const usd = iouGW["USD"];
712 env.trust(usd(overflowAmount), alice);
713 env.trust(usd(overflowAmount), mptGW);
714 env(pay(iouGW, alice, usd(overflowAmount)));
715
716 MPTTester const mpt(
717 {.env = env, .issuer = mptGW, .holders = {bob}, .transferFee = kMaxTransferFee});
718
719 env(offer(mptGW, usd(overflowAmount), mpt(overflowAmount)));
720
721 env(pay(alice, bob, mpt(overflowAmount)),
722 Path(~mpt),
723 Sendmax(usd(overflowAmount)),
724 Txflags(tfNoRippleDirect | tfPartialPayment));
725
726 env.require(Balance(alice, usd(0)), Balance(bob, mpt(deliveredAmount)));
727 BEAST_EXPECT(!isOffer(env, mptGW, usd(overflowAmount), mpt(overflowAmount)));
728 }
729 }
730
731 void
733 {
734 // A payment between the holders of an MPT with a transfer fee ripples
735 // through the issuer, and the issuing step has to charge the transfer
736 // rate on the amount it receives. maxPaymentFlow() returns the issuance
737 // maximum for that step, so srcToDst * transferRate is not necessarily
738 // representable as an MPT amount. The reverse pass must cap the flow at
739 // the largest representable input instead of declaring the strand dry,
740 // otherwise a deliverable partial payment fails with tecPATH_DRY.
741 //
742 // Same defect as the case above, reached without an offer: holder ->
743 // issuer -> holder, one case per branch of the pre-fix revImp.
744 testcase("MPT Endpoint rippling input overflow");
745
746 using namespace jtx;
747
748 Account const gw("gateway");
749 Account const alice("alice");
750 Account const bob("bob");
751
752 // The maximum transfer fee gives a transfer rate of 1.5, so an input of
753 // kMaxMpTokenAmount covers at most kMaxMpTokenAmount * 2 / 3 of output.
754 std::int64_t constexpr maxRepresentable = 6'148'914'691'236'517'204LL;
755 std::int64_t constexpr aliceBalance = 1'000;
756 // The forward pass rounds the delivered amount down: 1000 / 1.5
757 std::int64_t constexpr bobBalance = 666;
758
759 auto const test =
760 [&](std::uint64_t maxAmt, std::int64_t deliver, std::string const& label) {
761 Env env(*this, features);
762 env.fund(XRP(10'000), gw, alice, bob);
763 env.close();
764
765 auto const mpt = MPTTester({
766 .env = env,
767 .issuer = gw,
768 .holders = {alice, bob},
769 .transferFee = kMaxTransferFee,
770 .maxAmt = maxAmt,
771 });
772
773 env(pay(gw, alice, mpt(aliceBalance)));
774 env.close();
775
776 // alice asks to deliver more than the transfer rate can scale,
777 // so the issuing step caps the flow and her balance limits it
778 // further
779 env(pay(alice, bob, mpt(deliver)),
781 Txflags(tfPartialPayment));
782 BEAST_EXPECTS(env.ter() == tesSUCCESS, label);
783 BEAST_EXPECTS(env.balance(alice, mpt) == mpt(0), label);
784 BEAST_EXPECTS(env.balance(bob, mpt) == mpt(bobBalance), label);
785 BEAST_EXPECTS(mpt.checkMPTokenOutstandingAmount(bobBalance), label);
786 };
787
788 // The requested amount is below MaximumAmount, so the reverse pass
789 // takes the non-limiting branch and overflows on the requested amount
790 test(kMaxMpTokenAmount, maxRepresentable + 1, "non-limiting");
791
792 // MaximumAmount is below the requested amount but still large enough
793 // that scaling it by the transfer rate is not representable, so the
794 // reverse pass takes the limiting branch and overflows on the maximum
795 test(maxRepresentable + 1, kMaxMpTokenAmount, "limiting");
796 }
797
798 void
800 {
801 // OfferCreate doesn't compare TakerPays with the MPT's MaximumAmount,
802 // so a bid for more than the cap rests. Taking it has the issuer send
803 // TakerPays to the owner, and isMPTOverflow() rejects a single send
804 // above the cap. BookStep now limits the offer's input to the cap so
805 // the bid fills partially, like an underfunded offer, instead of
806 // throwing out of consumeOffer() and drying the strand (which left the
807 // bid on the book to dead-end every payment that crossed it).
808 //
809 // XRP -> x -> y. carol asks the whole 1,000 x supply for XRP(1,000);
810 // mallory bids x for 2,000 y; alice pays dave y.
811 testcase("BookStep input above MaximumAmount");
812
813 using namespace jtx;
814
815 Account const gwX("gwX");
816 Account const gwY("gwY");
817 Account const alice("alice");
818 Account const carol("carol");
819 Account const mallory("mallory");
820 Account const dave("dave");
821
822 std::int64_t constexpr cap = 1'000;
823 std::int64_t constexpr bidGets = 2'000;
824 // A bid above the cap at a non-unit price.
825 std::int64_t constexpr unevenBidPays = (3 * cap) + 100;
826
827 auto const test = [&](Account const& bidder,
828 std::int64_t bidPays,
829 std::int64_t deliver,
830 bool partial,
831 std::int64_t delivered,
832 std::optional<TER> const& ter = std::nullopt) {
833 Env env(*this, features);
834 env.fund(XRP(100'000), gwX, gwY, alice, carol, mallory, dave);
835 env.close();
836
837 MPT const x = MPTTester(
838 {.env = env, .issuer = gwX, .holders = {carol, mallory, dave}, .maxAmt = cap});
839 MPT const y = MPTTester({.env = env, .issuer = gwY, .holders = {mallory, dave, gwX}});
840 env(pay(gwX, carol, x(cap)));
841 env(pay(gwY, bidder, y(bidGets)));
842 env.close();
843
844 env(offer(carol, XRP(cap), x(cap)));
845 auto const bidSeq = env.seq(bidder);
846 env(offer(bidder, x(bidPays), y(bidGets)));
847 env.close();
848 auto const bidKeylet = keylet::offer(bidder.id(), SeqProxy::rawSequence(bidSeq));
849 BEAST_EXPECT(env.le(bidKeylet) != nullptr);
850
851 auto const flags = partial ? tfNoRippleDirect | tfPartialPayment : tfNoRippleDirect;
852 env(pay(alice, dave, y(deliver)),
853 Path(~x, ~y),
854 Sendmax(XRP(5'000)),
855 Txflags(flags),
856 ter ? Ter(*ter) : Ter(tesSUCCESS));
857 env.close();
858
859 BEAST_EXPECT(env.balance(dave, y) == y(delivered));
860 // Each x delivered through the bid costs bidGets/bidPays y.
861 std::int64_t const xTaken = delivered * bidPays / bidGets;
862 if (bidder != gwX)
863 BEAST_EXPECT(env.balance(bidder, x) == x(xTaken));
864 BEAST_EXPECT(env.balance(carol, x) == x(cap - xTaken));
865
866 auto const sle = env.le(bidKeylet);
867 if (xTaken == bidPays)
868 {
869 BEAST_EXPECT(!sle);
870 }
871 else if (BEAST_EXPECT(sle))
872 {
873 BEAST_EXPECT((*sle)[sfTakerPays] == x(bidPays - xTaken));
874 BEAST_EXPECT((*sle)[sfTakerGets] == y(bidGets - delivered));
875 }
876
877 auto const issuance = env.le(keylet::mptokenIssuance(x.mpt()));
878 if (BEAST_EXPECT(issuance))
879 {
880 // x taken by the issuer's own bid is redeemed.
881 std::int64_t const outstanding = bidder == gwX ? cap - xTaken : cap;
882 BEAST_EXPECT(
883 (*issuance)[sfOutstandingAmount] == static_cast<std::uint64_t>(outstanding));
884 }
885 };
886
887 // Bid above the cap: the input is limited to the cap, so at most
888 // 1,000 x (= 1,000 y at this bid's price) can flow through it.
889 test(mallory, 2 * cap, 1'001, true, cap);
890 test(mallory, 2 * cap, bidGets, true, cap);
891 // Not partial: the strand no longer throws, but 1,001 y can't be
892 // delivered.
893 test(mallory, 2 * cap, 1'001, false, 0, tecPATH_PARTIAL);
894 // Controls: a request within the cap, and a bid at the cap.
895 test(mallory, 2 * cap, 500, true, 500);
896 test(mallory, cap, bidGets, true, bidGets);
897 // The issuer's own bid above the cap isn't limited: the issuer's send
898 // to itself is a no-op, so upstream supply bounds the fill as usual.
899 test(gwX, 2 * cap, 1'001, true, cap);
900
901 // A bid above the cap at a non-unit price, crossed repeatedly. Each
902 // crossing is limited to the cap and the output is rounded down, so
903 // the remainder's quality is no worse than the original's. The
904 // remainder stays on the book and is eventually consumed.
905 {
906 Env env(*this, features);
907 env.fund(XRP(100'000), gwX, gwY, alice, carol, mallory, dave);
908 env.close();
909
910 MPT const x = MPTTester(
911 {.env = env, .issuer = gwX, .holders = {carol, mallory, dave}, .maxAmt = cap});
912 MPT const y = MPTTester({.env = env, .issuer = gwY, .holders = {mallory, dave}});
913 env(pay(gwX, carol, x(cap)));
914 env(pay(gwY, mallory, y(bidGets)));
915 env.close();
916
917 auto const bidSeq = env.seq(mallory);
918 env(offer(mallory, x(unevenBidPays), y(bidGets)));
919 env.close();
920 auto const bidKeylet = keylet::offer(mallory.id(), SeqProxy::rawSequence(bidSeq));
921
922 // {x taken, y delivered} per round; the first three are capped.
923 // 1,000 x buys floor(1,000 * gets / pays) y at the remainder's
924 // price: 2,000/3,100, 1,355/2,100, 710/1,100. The last 100 x buy
925 // the remaining 65 y and consume the bid.
926 std::int64_t totalY = 0;
927 std::int64_t bidPays = unevenBidPays;
928 std::int64_t bidGetsLeft = bidGets;
929 for (auto const& [xTaken, yDelivered] :
931 {cap, 645},
932 {cap, 645},
933 {cap, 645},
934 {100, 65},
935 })
936 {
937 auto const askSeq = env.seq(carol);
938 env(offer(carol, XRP(cap), x(cap)));
939 env.close();
940 env(pay(alice, dave, y(1'001)),
941 Path(~x, ~y),
942 Sendmax(XRP(5'000)),
943 Txflags(tfNoRippleDirect | tfPartialPayment));
944 env.close();
945
946 totalY += yDelivered;
947 bidPays -= xTaken;
948 bidGetsLeft -= yDelivered;
949 BEAST_EXPECT(env.balance(dave, y) == y(totalY));
950 BEAST_EXPECT(env.balance(mallory, x) == x(xTaken));
951 BEAST_EXPECT(env.balance(carol, x) == x(cap - xTaken));
952 auto const sle = env.le(bidKeylet);
953 if (bidPays == 0)
954 {
955 BEAST_EXPECT(!sle);
956 }
957 else if (BEAST_EXPECT(sle))
958 {
959 BEAST_EXPECT((*sle)[sfTakerPays] == x(bidPays));
960 BEAST_EXPECT((*sle)[sfTakerGets] == y(bidGetsLeft));
961 // The remainder's quality is no worse than the original's.
962 BEAST_EXPECT(bidGetsLeft * unevenBidPays >= bidGets * bidPays);
963 }
964
965 // Return x to carol for the next round, and cancel her unfilled
966 // ask remainder.
967 env(pay(mallory, carol, x(xTaken)));
968 env(offerCancel(carol, askSeq));
969 env.close();
970 }
971 BEAST_EXPECT(totalY == bidGets);
972 }
973
974 // A transfer fee on x: the cap is grossed up by the rate when limiting
975 // the taker's input, and the owner receives exactly the cap. The
976 // previous step must redeem for the fee to apply, so alice pays with
977 // x directly (MPTEndpoint alice -> gwX, then the x/y book). alice can
978 // hold at most the cap, so upstream still bounds the fill: she pays
979 // 1,000 gross, mallory receives floor(1,000 / 1.1) = 909 x, dave gets
980 // floor(909 * 2,000 / 3,100) = 586 y.
981 {
982 Env env(*this, features);
983 env.fund(XRP(100'000), gwX, gwY, alice, mallory, dave);
984 env.close();
985
986 MPT const x = MPTTester({
987 .env = env,
988 .issuer = gwX,
989 .holders = {alice, mallory, dave},
990 .transferFee = 10'000,
991 .maxAmt = cap,
992 });
993 MPT const y = MPTTester({.env = env, .issuer = gwY, .holders = {mallory, dave}});
994 env(pay(gwX, alice, x(cap)));
995 env(pay(gwY, mallory, y(bidGets)));
996 env.close();
997
998 auto const bidSeq = env.seq(mallory);
999 env(offer(mallory, x(unevenBidPays), y(bidGets)));
1000 env.close();
1001 auto const bidKeylet = keylet::offer(mallory.id(), SeqProxy::rawSequence(bidSeq));
1002
1003 env(pay(alice, dave, y(1'001)),
1004 Path(~y),
1005 Sendmax(x(cap)),
1006 Txflags(tfNoRippleDirect | tfPartialPayment));
1007 env.close();
1008
1009 BEAST_EXPECT(env.balance(dave, y) == y(586));
1010 BEAST_EXPECT(env.balance(mallory, x) == x(909));
1011 BEAST_EXPECT(env.balance(alice, x) == x(0));
1012 auto const sle = env.le(bidKeylet);
1013 if (BEAST_EXPECT(sle))
1014 {
1015 BEAST_EXPECT((*sle)[sfTakerPays] == x(unevenBidPays - 909));
1016 BEAST_EXPECT((*sle)[sfTakerGets] == y(bidGets - 586));
1017 }
1018 auto const issuance = env.le(keylet::mptokenIssuance(x.mpt()));
1019 if (BEAST_EXPECT(issuance))
1020 BEAST_EXPECT((*issuance)[sfOutstandingAmount] == 909);
1021 }
1022
1023 // Two bids above the cap at the same quality, mallory's ahead of
1024 // bob's. Stopping after a cap-limited bid doesn't strand bob's: the
1025 // step's input is already at the cap, which is all carol can supply,
1026 // so delivery equals the single-bid case. If mallory's bid is
1027 // underfunded below the cap instead, it isn't cap-limited: it is
1028 // consumed, removed, and bob's bid is crossed in the same pass.
1029 auto const twoBids = [&](std::int64_t malloryY,
1030 std::int64_t delivered,
1031 std::int64_t malloryX,
1032 std::int64_t malloryYSold,
1033 std::int64_t bobX,
1034 std::int64_t bobYSold,
1036 Env env(*this, features);
1037 Account const bob("bob");
1038 env.fund(XRP(100'000), gwX, gwY, alice, bob, carol, mallory, dave);
1039 env.close();
1040
1041 MPT const x = MPTTester(
1042 {.env = env, .issuer = gwX, .holders = {bob, carol, mallory, dave}, .maxAmt = cap});
1043 MPT const y = MPTTester({.env = env, .issuer = gwY, .holders = {bob, mallory, dave}});
1044 env(pay(gwX, carol, x(cap)));
1045 env(pay(gwY, mallory, y(malloryY)));
1046 env(pay(gwY, bob, y(bidGets)));
1047 env.close();
1048
1049 env(offer(carol, XRP(cap), x(cap)));
1050 // Close between the bids: within one ledger, transactions apply in
1051 // canonical order, and mallory's bid must be ahead of bob's.
1052 auto const mallorySeq = env.seq(mallory);
1053 env(offer(mallory, x(unevenBidPays), y(bidGets)));
1054 env.close();
1055 auto const bobSeq = env.seq(bob);
1056 env(offer(bob, x(unevenBidPays), y(bidGets)));
1057 env.close();
1058
1059 env(pay(alice, dave, y(bidGets)),
1060 Path(~x, ~y),
1061 Sendmax(XRP(5'000)),
1062 Txflags(tfNoRippleDirect | tfPartialPayment));
1063 env.close();
1064
1065 BEAST_EXPECT(env.balance(dave, y) == y(delivered));
1066 BEAST_EXPECT(env.balance(mallory, x) == x(malloryX));
1067 BEAST_EXPECT(env.balance(mallory, y) == y(malloryY - malloryYSold));
1068 BEAST_EXPECT(env.balance(bob, x) == x(bobX));
1069 BEAST_EXPECT(env.balance(bob, y) == y(bidGets - bobYSold));
1070 BEAST_EXPECT(env.balance(carol, x) == x(cap - malloryX - bobX));
1071
1072 auto const mallorySle =
1073 env.le(keylet::offer(mallory.id(), SeqProxy::rawSequence(mallorySeq)));
1074 if (!malloryBid)
1075 {
1076 BEAST_EXPECT(!mallorySle);
1077 }
1078 else if (BEAST_EXPECT(mallorySle))
1079 {
1080 BEAST_EXPECT((*mallorySle)[sfTakerPays] == x(malloryBid->first));
1081 BEAST_EXPECT((*mallorySle)[sfTakerGets] == y(malloryBid->second));
1082 }
1083 auto const bobSle = env.le(keylet::offer(bob.id(), SeqProxy::rawSequence(bobSeq)));
1084 if (BEAST_EXPECT(bobSle))
1085 {
1086 BEAST_EXPECT((*bobSle)[sfTakerPays] == x(unevenBidPays - bobX));
1087 BEAST_EXPECT((*bobSle)[sfTakerGets] == y(bidGets - bobYSold));
1088 }
1089 auto const issuance = env.le(keylet::mptokenIssuance(x.mpt()));
1090 if (BEAST_EXPECT(issuance))
1091 BEAST_EXPECT((*issuance)[sfOutstandingAmount] == static_cast<std::uint64_t>(cap));
1092 };
1093 // Both funded: mallory's bid takes the cap for 645 y and rests at
1094 // 2,100/1,355; bob's is untouched.
1095 twoBids(bidGets, 645, cap, 645, 0, 0, std::pair{unevenBidPays - cap, bidGets - 645});
1096 // mallory holds 500 y: funds limit her bid to 775 x, under the cap, so
1097 // it is consumed and removed; bob's bid takes the remaining 225 x for
1098 // 145 y in the same pass. Same 645 y total.
1099 twoBids(500, 645, 775, 500, 225, 145, std::nullopt);
1100 }
1101
1102 void
1104 {
1105 // BookStep limits an MPT input to MaximumAmount (see maxIn_) and
1106 // grosses up the transfer fee on no more than the cap. Grossing up
1107 // the bid's whole TakerPays can overflow even though a fill at the
1108 // cap fits, and the overflow used to remove the bid. OfferCreate
1109 // doesn't place a bid whose grossed-up TakerPays overflows, but one
1110 // can rest at a lower fee before the issuer raises it.
1111 //
1112 // mallory bids for 9e18 x, above x's 8e18 cap, while x has no fee.
1113 // gwX then raises the fee. alice pays x directly, so the step redeems
1114 // and the fee applies.
1115 testcase("BookStep input above MaximumAmount with transfer fee");
1116
1117 using namespace jtx;
1118
1119 Account const gwX("gwX");
1120 Account const gwY("gwY");
1121 Account const alice("alice");
1122 Account const mallory("mallory");
1123 Account const dave("dave");
1124
1125 std::int64_t constexpr cap = 8'000'000'000'000'000'000LL;
1126 std::int64_t constexpr bid = 9'000'000'000'000'000'000LL;
1127 std::int64_t constexpr deliver = 1'000;
1128
1129 auto const test = [&](std::uint16_t fee, bool fills) {
1130 Env env(*this, features);
1131 env.fund(XRP(100'000), gwX, gwY, alice, mallory, dave);
1132 env.close();
1133
1134 MPTTester x(
1135 {.env = env, .issuer = gwX, .holders = {alice, mallory, dave}, .maxAmt = cap});
1136 MPT const y = MPTTester({.env = env, .issuer = gwY, .holders = {mallory, dave}});
1137 std::int64_t const gross = deliver + ((deliver * fee) / 100'000);
1138 env(pay(gwX, alice, x(gross)));
1139 env(pay(gwY, mallory, y(bid)));
1140 env.close();
1141
1142 auto const bidSeq = env.seq(mallory);
1143 env(offer(mallory, x(bid), y(bid)));
1144 env.close();
1145 auto const bidKeylet = keylet::offer(mallory.id(), SeqProxy::rawSequence(bidSeq));
1146 BEAST_EXPECT(env.le(bidKeylet) != nullptr);
1147
1148 x.set({.account = gwX, .transferFee = fee});
1149 env.close();
1150
1151 env(pay(alice, dave, y(deliver)),
1152 Path(~y),
1153 Sendmax(x(gross)),
1154 Txflags(tfNoRippleDirect),
1155 Ter(fills ? TER(tesSUCCESS) : TER(tecPATH_PARTIAL)));
1156 env.close();
1157
1158 auto const sle = env.le(bidKeylet);
1159 if (fills)
1160 {
1161 BEAST_EXPECT(env.balance(dave, y) == y(deliver));
1162 BEAST_EXPECT(env.balance(mallory, x) == x(deliver));
1163 BEAST_EXPECT(env.balance(alice, x) == x(0));
1164 // The remainder is still funded and stays on the book.
1165 if (BEAST_EXPECT(sle))
1166 {
1167 BEAST_EXPECT((*sle)[sfTakerPays] == x(bid - deliver));
1168 BEAST_EXPECT((*sle)[sfTakerGets] == y(bid - deliver));
1169 }
1170 }
1171 else
1172 {
1173 // Even the cap overflows once grossed up, so BookStep removes
1174 // the bid and nothing is delivered. The failed payment
1175 // discards its changes, so the bid is still on the ledger.
1176 BEAST_EXPECT(env.balance(dave, y) == y(0));
1177 BEAST_EXPECT(env.balance(alice, x) == x(gross));
1178 BEAST_EXPECT(sle);
1179 }
1180 };
1181
1182 // 9e18 * 1.1 overflows but 8e18 * 1.1 fits: the bid fills partially.
1183 test(10'000, true);
1184 // 8e18 * 1.5 overflows too, so the bid is removed as before.
1185 test(kMaxTransferFee, false);
1186 }
1187
1188 void
1190 {
1191 // A path through a book whose MPT issuance doesn't exist. BookStep's
1192 // constructor looks the issuance up for MaximumAmount before check()
1193 // rejects the step, so the lookup must tolerate a missing entry.
1194 testcase("BookStep on a missing MPT issuance");
1195
1196 using namespace jtx;
1197
1198 Env env(*this, features);
1199 Account const gw("gw");
1200 Account const alice("alice");
1201 Account const bob("bob");
1202 env.fund(XRP(10'000), gw, alice, bob);
1203 env.close();
1204
1205 MPT const y = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}});
1206 MPT const missing{"missing", makeMptID(99, gw)};
1207 BEAST_EXPECT(!env.le(keylet::mptokenIssuance(missing.mpt())));
1208
1209 env(pay(alice, bob, y(10)),
1210 Path(~missing, ~y),
1211 Sendmax(XRP(100)),
1212 Txflags(tfNoRippleDirect),
1214 env.close();
1215 BEAST_EXPECT(env.balance(bob, y) == y(0));
1216 }
1217
1218 void
1220 {
1221 // An overflow while consuming an offer fails the strand under
1222 // MPTokensV2, and the transaction with tecINTERNAL otherwise. Either
1223 // way no balances change and the offer stays on the book.
1224 testcase("BookStep consumeOffer overflow");
1225
1226 using namespace jtx;
1227
1228 Account const gw("gateway");
1229 Account const eurGW("eur_gateway");
1230 Account const maker("maker");
1231 Account const alice("alice");
1232 Account const bob("bob");
1233
1234 for (auto const& testFeatures : {features, features - featureMPTokensV2})
1235 {
1236 Env env(*this, testFeatures);
1237
1238 auto const withV2 = testFeatures[featureMPTokensV2];
1239
1240 env.fund(XRP(10'000), gw, eurGW, maker, alice, bob);
1241 env.close();
1242
1243 auto const usd = gw["USD"];
1244 auto const eur = eurGW["EUR"];
1245 STAmount const usdMax{usd.issue(), STAmount::kMaxValue, STAmount::kMaxOffset};
1246 STAmount const usdIn{usd.issue(), 1, 90};
1247
1248 env.trust(usdMax, maker, alice);
1249 env.trust(eur(1'000), maker, bob);
1250 env.close();
1251
1252 env(pay(gw, maker, usdMax));
1253 env(pay(gw, alice, usdIn));
1254 env(pay(eurGW, maker, eur(100)));
1255 env(offer(maker, usdIn, eur(100)));
1256 env.close();
1257
1258 env(pay(alice, bob, eur(100)),
1259 Path(~eur),
1260 Sendmax(usdIn),
1261 Ter(withV2 ? TER{tecPATH_PARTIAL} : TER{tecINTERNAL}));
1262 env.close();
1263
1264 env.require(
1265 Balance(bob, eur(0)),
1266 Balance(maker, eur(100)),
1267 Balance(maker, usdMax),
1268 Balance(alice, usdIn));
1269 BEAST_EXPECT(isOffer(env, maker, usdIn, eur(100)));
1270 }
1271 }
1272
1273 void
1275 {
1276 testcase("falseDryChanges");
1277
1278 using namespace jtx;
1279
1280 auto const gw = Account("gateway");
1281 Account const alice("alice");
1282 Account const bob("bob");
1283 Account const carol("carol");
1284
1285 auto const test = [&](auto&& issue1, auto&& issue2) {
1286 Env env(*this, features);
1287
1288 env.fund(XRP(10'000), alice, carol, gw);
1289 env.fund(reserve(env, 5), bob);
1290 env.close();
1291
1292 auto const usd =
1293 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol, bob}});
1294 auto const eur =
1295 issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, carol, bob}});
1296
1297 env(pay(gw, alice, eur(50)));
1298 env(pay(gw, bob, usd(50)));
1299
1300 // Bob has _just_ slightly less than 50 xrp available
1301 // If his owner count changes, he will have more liquidity.
1302 // This is one error case to test (when Flow is used).
1303 // Computing the incoming xrp to the XRP/USD offer will
1304 // require two recursive calls to the EUR/XRP offer. The
1305 // second call will return tecPATH_DRY, but the entire path
1306 // should not be marked as dry. This is the second error
1307 // case to test (when flowV1 is used).
1308 env(offer(bob, eur(50), XRP(50)));
1309 env(offer(bob, XRP(50), usd(50)));
1310
1311 env(pay(alice, carol, usd(1'000'000)),
1312 Path(~XRP, ~usd),
1313 Sendmax(eur(500)),
1314 Txflags(tfNoRippleDirect | tfPartialPayment));
1315
1316 auto const carolUSD = env.balance(carol, usd).value();
1317 BEAST_EXPECT(carolUSD > usd(0) && carolUSD < usd(50));
1318 };
1320 }
1321
1322 void
1324 {
1325 // Single path with two offers and limit quality. The
1326 // quality limit is such that the first offer should be
1327 // taken but the second should not. The total amount
1328 // delivered should be the sum of the two offers and sendMax
1329 // should be more than the first offer.
1330 testcase("limitQuality");
1331 using namespace jtx;
1332
1333 auto const gw = Account("gateway");
1334 Account const alice("alice");
1335 Account const bob("bob");
1336 Account const carol("carol");
1337
1338 {
1339 Env env(*this);
1340
1341 env.fund(XRP(10'000), alice, bob, carol, gw);
1342
1343 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}});
1344
1345 env(pay(gw, bob, usd(100)));
1346 env(offer(bob, XRP(50), usd(50)));
1347 env(offer(bob, XRP(100), usd(50)));
1348
1349 env(pay(alice, carol, usd(100)),
1350 Path(~usd),
1351 Sendmax(XRP(100)),
1352 Txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality));
1353
1354 env.require(Balance(carol, usd(50)));
1355 }
1356 }
1357
1358 // Helper function that returns the reserve on an account based on
1359 // the passed in number of owners.
1360 static XRPAmount
1362 {
1363 return env.current()->fees().accountReserve(count, 1);
1364 }
1365
1366 // Helper function that returns the Offers on an account.
1369 {
1371 forEachItem(*env.current(), account, [&result](SLE::ConstRef sle) {
1372 if (sle->getType() == ltOFFER)
1373 result.push_back(sle);
1374 });
1375 return result;
1376 }
1377
1378 void
1380 {
1381 using namespace jtx;
1382 Account const alice("alice");
1383 Account const bob("bob");
1384 Account const carol("carol");
1385 Account const gw("gw");
1386
1387 {
1388 testcase("Reserve-edge offer owner cannot create another object");
1389
1390 Env env(*this, features);
1391
1392 auto const baseFee = env.current()->fees().base;
1393 auto const ownerIncrement = reserve(env, 1) - reserve(env, 0);
1394 auto const xrpOffer = ownerIncrement - drops(1);
1395 auto const bobStart = reserve(env, 2) - drops(1) + baseFee;
1396
1397 env.fund(XRP(10'000), alice, gw);
1398 env.fund(bobStart, bob);
1399 env.close();
1400
1401 MPTTester const usd({.env = env, .issuer = gw, .maxAmt = 10});
1402
1403 env(offer(bob, usd(1), xrpOffer));
1404 env.close();
1405
1406 env.require(Balance(bob, reserve(env, 2) - drops(1)), Owners(bob, 1));
1407
1408 // This mirrors the full-crossing setup below. Bob has enough XRP
1409 // for the resting offer, but not enough to pay a fee and add
1410 // another owner-count object while the offer remains on ledger.
1411 env(check::create(bob, alice, drops(1)), Ter(tecINSUFFICIENT_RESERVE));
1412 env.close();
1413
1414 env.require(Owners(bob, 1));
1415 BEAST_EXPECT(offersOnAccount(env, bob).size() == 1);
1416 }
1417
1418 {
1419 testcase("Reserve-edge offer owner creates MPToken during consume");
1420
1421 Env env(*this, features);
1422
1423 auto const baseFee = env.current()->fees().base;
1424 auto const ownerIncrement = reserve(env, 1) - reserve(env, 0);
1425 auto const xrpOffer = ownerIncrement - drops(1);
1426 auto const bobStart = reserve(env, 2) - drops(1) + baseFee;
1427
1428 env.fund(XRP(10'000), alice, carol, gw);
1429 env.fund(bobStart, bob);
1430 env.close();
1431
1432 MPTTester const usd({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 10});
1433
1434 env(pay(gw, alice, usd(1)));
1435 env(offer(bob, usd(1), xrpOffer));
1436 env.close();
1437
1438 env.require(Balance(bob, reserve(env, 2) - drops(1)), Owners(bob, 1));
1439 BEAST_EXPECT(!env.le(keylet::mptoken(usd.issuanceID(), bob.id())));
1440 auto const carolXRP = env.balance(carol);
1441
1442 // Bob has enough XRP for the resting offer but is close to
1443 // reserve. The payment should not create Bob's USD MPToken until
1444 // the offer is actually consumed, otherwise the temporary owner
1445 // count increase can make the offer look underfunded during path
1446 // execution.
1447 env(pay(alice, carol, xrpOffer),
1448 Path(~XRP),
1449 Sendmax(usd(1)),
1450 Txflags(tfNoRippleDirect));
1451 env.close();
1452
1453 env.require(Balance(carol, carolXRP + xrpOffer));
1454 env.require(Balance(bob, usd(1)));
1455 env.require(Balance(bob, reserve(env, 1)), Owners(bob, 1));
1456 BEAST_EXPECT(env.le(keylet::mptoken(usd.issuanceID(), bob.id())));
1457 BEAST_EXPECT(offersOnAccount(env, bob).empty());
1458 }
1459
1460 {
1461 testcase("Partial offer owner creates MPToken during consume");
1462
1463 Env env(*this, features);
1464
1465 auto const baseFee = env.current()->fees().base;
1466 auto const ownerIncrement = reserve(env, 1) - reserve(env, 0);
1467 auto const bobStart = reserve(env, 3) + baseFee;
1468
1469 env.fund(XRP(10'000), alice, carol, gw);
1470 env.fund(bobStart, bob);
1471 env.close();
1472
1473 MPTTester const usd({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 10});
1474
1475 env(pay(gw, alice, usd(1)));
1476 env(offer(bob, usd(2), drops(2 * ownerIncrement)));
1477 env.close();
1478
1479 env.require(Balance(bob, reserve(env, 3)), Owners(bob, 1));
1480 BEAST_EXPECT(!env.le(keylet::mptoken(usd.issuanceID(), bob.id())));
1481 auto const carolXRP = env.balance(carol);
1482
1483 // Partial consumption leaves Bob's offer on the ledger, so he ends
1484 // up owning both the remaining offer and a newly created MPToken.
1485 // The MPToken is created regardless of reserve; this setup simply
1486 // funds Bob enough that he still meets reserve(2) afterward (the
1487 // under-reserved case is covered in OfferMPT_test's no-reserve-check
1488 // testcase).
1489 env(pay(alice, carol, drops(ownerIncrement)),
1490 Path(~XRP),
1491 Sendmax(usd(1)),
1492 Txflags(tfNoRippleDirect));
1493 env.close();
1494
1495 env.require(Balance(carol, carolXRP + drops(ownerIncrement)));
1496 env.require(Balance(bob, usd(1)));
1497 env.require(Balance(bob, reserve(env, 2)), Owners(bob, 2));
1498 BEAST_EXPECT(env.le(keylet::mptoken(usd.issuanceID(), bob.id())));
1499 BEAST_EXPECT(offersOnAccount(env, bob).size() == 1);
1500 BEAST_EXPECT(isOffer(env, bob, usd(1), drops(ownerIncrement)));
1501 }
1502
1503 {
1504 testcase("Issuer-owned offer does not create issuer MPToken");
1505
1506 Env env(*this, features);
1507
1508 env.fund(XRP(10'000), alice, carol, gw);
1509 env.close();
1510
1511 MPTTester const usd({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 10});
1512
1513 env(pay(gw, alice, usd(1)));
1514 env(offer(gw, usd(1), drops(1'000)));
1515 env.close();
1516
1517 BEAST_EXPECT(!env.le(keylet::mptoken(usd.issuanceID(), gw.id())));
1518 auto const carolXRP = env.balance(carol);
1519
1520 // The issuer can own an offer that receives its own MPT without an
1521 // MPToken. Consuming that offer should keep the issuer side
1522 // tokenless.
1523 env(pay(alice, carol, drops(1'000)),
1524 Path(~XRP),
1525 Sendmax(usd(1)),
1526 Txflags(tfNoRippleDirect));
1527 env.close();
1528
1529 env.require(Balance(alice, usd(0)));
1530 env.require(Balance(carol, carolXRP + drops(1'000)));
1531 BEAST_EXPECT(!env.le(keylet::mptoken(usd.issuanceID(), gw.id())));
1532 BEAST_EXPECT(offersOnAccount(env, gw).empty());
1533 }
1534 }
1535
1536 void
1538 {
1539 testcase("Self-payment 1");
1540
1541 // In this test case the new flow code mis-computes the
1542 // amount of money to move. Fortunately the new code's
1543 // re-execute check catches the problem and throws out the
1544 // transaction.
1545 //
1546 // The old payment code handles the payment correctly.
1547 using namespace jtx;
1548
1549 auto const test = [&](auto&& issue1, auto&& issue2) {
1550 auto const gw1 = Account("gw1");
1551 auto const gw2 = Account("gw2");
1552 auto const alice = Account("alice");
1553
1554 Env env(*this, features);
1555
1556 env.fund(XRP(1'000'000), gw1, gw2);
1557 env.close();
1558
1559 // The fee that's charged for transactions.
1560 auto const f = env.current()->fees().base;
1561
1562 env.fund(reserve(env, 3) + f * 4, alice);
1563 env.close();
1564
1565 auto const usd = issue1(
1566 {.env = env, .token = "USD", .issuer = gw1, .holders = {alice}, .limit = 20'000});
1567 auto const eur = issue2(
1568 {.env = env, .token = "EUR", .issuer = gw2, .holders = {alice}, .limit = 20'000});
1569
1570 env(pay(gw1, alice, usd(10)));
1571 env(pay(gw2, alice, eur(10'000)));
1572 env.close();
1573
1574 env(offer(alice, usd(5'000), eur(6'000)));
1575 env.close();
1576
1577 env.require(Owners(alice, 3));
1578 env.require(Balance(alice, usd(10)));
1579 env.require(Balance(alice, eur(10'000)));
1580
1581 auto aliceOffers = offersOnAccount(env, alice);
1582 BEAST_EXPECT(aliceOffers.size() == 1);
1583 for (auto const& offerPtr : aliceOffers)
1584 {
1585 auto const offer = *offerPtr;
1586 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
1587 BEAST_EXPECT(offer[sfTakerGets] == eur(6'000));
1588 BEAST_EXPECT(offer[sfTakerPays] == usd(5'000));
1589 }
1590
1591 env(pay(alice, alice, eur(6'000)), Sendmax(usd(5'000)), Txflags(tfPartialPayment));
1592 env.close();
1593
1594 env.require(Owners(alice, 3));
1595 env.require(Balance(alice, usd(10)));
1596 env.require(Balance(alice, eur(10'000)));
1597 aliceOffers = offersOnAccount(env, alice);
1598 BEAST_EXPECT(aliceOffers.size() == 1);
1599 for (auto const& offerPtr : aliceOffers)
1600 {
1601 auto const offer = *offerPtr;
1602 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
1603 BEAST_EXPECT(offer[sfTakerGets] == eur(5'988));
1604 BEAST_EXPECT(offer[sfTakerPays] == usd(4'990));
1605 }
1606 };
1608 }
1609
1610 template <typename TGets, typename TPays>
1618
1619 void
1621 {
1622 testcase("Self-payment 2");
1623
1624 using namespace jtx;
1625
1626 // This test shows a difference between IOU and MPT
1627 // self-payment result depending on IOU trustline limit.
1628
1629 auto const gw1 = Account("gw1");
1630 auto const gw2 = Account("gw2");
1631 auto const alice = Account("alice");
1632
1633 auto const initMPT = [&](Env& env) {
1634 MPT const usd =
1635 MPTTester({.env = env, .issuer = gw1, .holders = {alice}, .maxAmt = 506});
1636 MPT const eur =
1637 MPTTester({.env = env, .issuer = gw2, .holders = {alice}, .maxAmt = 606});
1638 // Payment's engine last step overflows
1639 // OutstandingAmount since it doesn't know if the
1640 // BookStep redeems or not. The BookStep then has 600EUR
1641 // available. Consequently, the entire offer is crossed.
1642 return TokenData<MPT, MPT>{
1643 .gets = eur,
1644 .pays = usd,
1645 .remTakerGets = eur(540),
1646 .remTakerPays = usd(450),
1647 };
1648 };
1649
1650 auto const initXRP = [&](Env& env) {
1651 MPT const usd =
1652 MPTTester({.env = env, .issuer = gw1, .holders = {alice}, .maxAmt = 1'000});
1653 // Payment's engine last step overflows
1654 // OutstandingAmount since it doesn't know if the
1655 // BookStep redeems or not. The BookStep then has 600EUR
1656 // available. Consequently, the entire offer is crossed.
1657 return TokenData<XrpT, MPT>{
1658 .gets = XRP,
1659 .pays = usd,
1660 .remTakerGets = XRP(540),
1661 .remTakerPays = usd(450),
1662 };
1663 };
1664
1665 auto const initIOU = [&](Env& env) {
1666 auto const usd = gw1["USD"];
1667 auto const eur = gw2["EUR"];
1668 env(trust(alice, usd(506)));
1669 env(trust(alice, eur(606)));
1670 env.close();
1671 // Payment's engine last step is limited by alice's
1672 // trustline - 606. Therefore, only 6EUR is delivered
1673 // and the offer is partially crossed.
1674 return TokenData<IOU, IOU>{
1675 .gets = eur,
1676 .pays = usd,
1677 .remTakerGets = eur(594),
1678 .remTakerPays = usd(495),
1679 };
1680 };
1681
1682 auto const initIOU1 = [&](Env& env) {
1683 auto const usd = gw1["USD"];
1684 auto const eur = gw2["EUR"];
1685 env(trust(alice, usd(1'000)));
1686 env(trust(alice, eur(1'000)));
1687 env.close();
1688 // Payment's engine last step is not limited by alice's
1689 // trustline. Therefore, the entire offer is crossed.
1690 // This the same result as with MPT.
1691 return TokenData<IOU, IOU>{
1692 .gets = eur,
1693 .pays = usd,
1694 .remTakerGets = eur(540),
1695 .remTakerPays = usd(450),
1696 };
1697 };
1698
1699 auto const test = [&](auto&& initToken) {
1700 Env env(*this, features);
1701
1702 env.fund(XRP(2'000), gw1, gw2, alice);
1703 env.close();
1704
1705 auto const f = env.current()->fees().base;
1706
1707 auto const tok = initToken(env);
1708
1709 auto const& toK1 = tok.pays;
1710 auto const& toK2 = tok.gets;
1711 bool const isTakerGetsXRP = isXRP(Asset{toK2});
1712 std::uint32_t const ownerCnt = isTakerGetsXRP ? 2 : 3;
1713
1714 env(pay(gw1, alice, toK1(500)));
1715 if (!isTakerGetsXRP)
1716 env(pay(gw2, alice, toK2(600)));
1717 env.close();
1718
1719 env(offer(alice, toK1(500), toK2(600)));
1720 env.close();
1721
1722 env.require(Owners(alice, ownerCnt));
1723 env.require(Balance(alice, toK1(500)));
1724 if (isTakerGetsXRP)
1725 {
1726 env.require(Balance(alice, toK2(2'000) - 2 * f));
1727 }
1728 else
1729 {
1730 env.require(Balance(alice, toK2(600)));
1731 }
1732
1733 auto aliceOffers = offersOnAccount(env, alice);
1734 BEAST_EXPECT(aliceOffers.size() == 1);
1735 for (auto const& offerPtr : aliceOffers)
1736 {
1737 auto const offer = *offerPtr;
1738 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
1739 BEAST_EXPECT(offer[sfTakerGets] == toK2(600));
1740 BEAST_EXPECT(offer[sfTakerPays] == toK1(500));
1741 }
1742
1743 env(pay(alice, alice, toK2(60)), Sendmax(toK1(50)), Txflags(tfPartialPayment));
1744 env.close();
1745
1746 env.require(Owners(alice, ownerCnt));
1747 env.require(Balance(alice, toK1(500)));
1748 if (isTakerGetsXRP)
1749 {
1750 env.require(Balance(alice, toK2(2'000) - 3 * f));
1751 }
1752 else
1753 {
1754 env.require(Balance(alice, toK2(600)));
1755 }
1756 aliceOffers = offersOnAccount(env, alice);
1757 BEAST_EXPECT(aliceOffers.size() == 1);
1758 for (auto const& offerPtr : aliceOffers)
1759 {
1760 auto const offer = *offerPtr;
1761 BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER);
1762 BEAST_EXPECT(offer[sfTakerGets] == tok.remTakerGets);
1763 BEAST_EXPECT(offer[sfTakerPays] == tok.remTakerPays);
1764 }
1765 };
1766
1767 test(initXRP);
1768 test(initMPT);
1769 test(initIOU);
1770 test(initIOU1);
1771 }
1772
1773 void
1774 testSelfFundedXRPEndpoint(bool consumeOffer, FeatureBitset features)
1775 {
1776 // Test that the deferred credit table is not bypassed for
1777 // XRPEndpointSteps. If the account in the first step is
1778 // sending XRP and that account also owns an offer that
1779 // receives XRP, it should not be possible for that step to
1780 // use the XRP received in the offer as part of the payment.
1781 testcase("Self funded XRPEndpoint");
1782
1783 using namespace jtx;
1784
1785 Env env(*this, features);
1786
1787 auto const alice = Account("alice");
1788 auto const gw = Account("gw");
1789
1790 env.fund(XRP(10'000), alice, gw);
1791
1792 MPT const usd = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 20});
1793
1794 env(pay(gw, alice, usd(10)));
1795 env(offer(alice, XRP(50'000), usd(10)));
1796
1797 // Consuming the offer changes the owner count, which could
1798 // also cause liquidity to decrease in the forward pass
1799 auto const toSend = consumeOffer ? usd(10) : usd(9);
1800 env(pay(alice, alice, toSend),
1801 Path(~usd),
1802 Sendmax(XRP(20'000)),
1803 Txflags(tfPartialPayment | tfNoRippleDirect));
1804 }
1805
1806 void
1808 {
1809 testcase("Unfunded Offer");
1810
1811 using namespace jtx;
1812 {
1813 // Test reverse
1814 Env env(*this, features);
1815
1816 auto const alice = Account("alice");
1817 auto const bob = Account("bob");
1818 auto const gw = Account("gw");
1819
1820 env.fund(XRP(100'000), alice, bob, gw);
1821
1822 MPT const usd =
1823 MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20E+17});
1824
1825 // scale by 17
1826 STAmount const tinyAmt1{usd, 9'000'000'000'000'000ll, 0, false, STAmount::Unchecked{}};
1827 STAmount const tinyAmt3{usd, 9'000'000'000'000'003ll, 0, false, STAmount::Unchecked{}};
1828
1829 env(offer(gw, drops(9'000'000'000), tinyAmt3));
1830
1831 env(pay(alice, bob, tinyAmt1),
1832 Path(~usd),
1833 Sendmax(drops(9'000'000'000)),
1834 Txflags(tfNoRippleDirect));
1835
1836 BEAST_EXPECT(!isOffer(env, gw, XRP(0), usd(0)));
1837 }
1838 {
1839 // Test forward
1840 Env env(*this, features);
1841
1842 auto const alice = Account("alice");
1843 auto const bob = Account("bob");
1844 auto const gw = Account("gw");
1845
1846 env.fund(XRP(100'000), alice, bob, gw);
1847
1848 MPT const usd =
1849 MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20E+17});
1850
1851 // scale by 17
1852 STAmount const tinyAmt1{usd, 9'000'000'000'000'000ll, 0, false, STAmount::Unchecked{}};
1853 STAmount const tinyAmt3{usd, 9'000'000'000'000'003ll, 0, false, STAmount::Unchecked{}};
1854
1855 env(pay(gw, alice, tinyAmt1));
1856
1857 env(offer(gw, tinyAmt3, drops(9'000'000'000)));
1858 env(pay(alice, bob, drops(9'000'000'000)),
1859 Path(~XRP),
1860 Sendmax(usd(static_cast<std::uint64_t>(1E+17))),
1861 Txflags(tfNoRippleDirect));
1862
1863 BEAST_EXPECT(!isOffer(env, gw, usd(0), XRP(0)));
1864 }
1865 }
1866
1867 void
1869 {
1870 testcase("ReexecuteDirectStep");
1871
1872 using namespace jtx;
1873 Env env(*this, features);
1874
1875 auto const alice = Account("alice");
1876 auto const bob = Account("bob");
1877 auto const gw = Account("gw");
1878
1879 env.fund(XRP(10'000), alice, bob, gw);
1880
1881 // scale by 16
1882 MPT const usd =
1883 MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 100E+16});
1884
1885 env(
1886 pay(gw,
1887 alice,
1888 // 12.55....
1889 STAmount{usd, std::uint64_t(1255555555555555ull), 2, false}));
1890
1891 env(offer(
1892 gw,
1893 // 5.0...
1894 STAmount{usd, std::uint64_t(5000000000000000ull), 1, false},
1895 XRP(1000)));
1896
1897 env(offer(
1898 gw,
1899 // .555...
1900 STAmount{usd, std::uint64_t(5555555555555555ull), 0, false},
1901 XRP(10)));
1902
1903 env(offer(
1904 gw,
1905 // 4.44....
1906 STAmount{usd, std::uint64_t(4444444444444444ull), 1, false},
1907 XRP(.1)));
1908
1909 env(offer(
1910 alice,
1911 // 17
1912 STAmount{usd, std::uint64_t(1700000000000000ull), 0, false},
1913 XRP(.001)));
1914
1915 env(pay(alice, bob, XRP(10'000)),
1916 Path(~XRP),
1917 Sendmax(usd(static_cast<std::uint64_t>(100E+16))),
1918 Txflags(tfPartialPayment | tfNoRippleDirect));
1919 }
1920
1921 void
1923 {
1924 // The new payment code used to assert if an offer was made
1925 // for more XRP than the offering account held. This unit
1926 // test reproduces that failing case.
1927 testcase("Self crossing low quality offer");
1928
1929 using namespace jtx;
1930
1931 Env env(*this, features);
1932
1933 auto const ann = Account("ann");
1934 auto const gw = Account("gateway");
1935
1936 auto const fee = env.current()->fees().base;
1937 env.fund(reserve(env, 2) + drops(9999640) + fee, ann);
1938 env.fund(reserve(env, 2) + fee * 4, gw);
1939
1940 // scale by 5
1941 MPT const ctb = MPTTester({
1942 .env = env,
1943 .issuer = gw,
1944 .holders = {ann},
1945 .transferFee = 2'000, // 2%
1946 .maxAmt = 1'000'000,
1947 });
1948
1949 env(pay(gw, ann, ctb(285'600)));
1950 env.close();
1951
1952 env(offer(ann, drops(365'611'702'030), ctb(571'300)));
1953 env.close();
1954
1955 // This payment caused assert.
1956 env(pay(ann, ann, ctb(68'700)), Sendmax(drops(20'000'000'000)), Txflags(tfPartialPayment));
1957 }
1958
1959 void
1961 {
1962 testcase("Empty Strand");
1963 using namespace jtx;
1964
1965 auto const alice = Account("alice");
1966
1967 Env env(*this, features);
1968
1969 env.fund(XRP(10000), alice);
1970
1971 MPT const usd;
1972
1973 env(pay(alice, alice, usd(100)), Path(~usd), Ter(temBAD_PATH));
1974 }
1975
1976 void
1978 {
1979 testcase("Circular XRP");
1980
1981 using namespace jtx;
1982 auto const alice = Account("alice");
1983 auto const bob = Account("bob");
1984 auto const gw = Account("gw");
1985
1986 {
1987 // Payment path starting with XRP
1988 auto const test = [&](auto&& issue1, auto&& issue2) {
1989 Env env(*this);
1990 env.fund(XRP(10'000), alice, bob, gw);
1991
1992 auto const usd =
1993 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}});
1994 auto const eur =
1995 issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}});
1996 env(pay(gw, alice, usd(100)));
1997 env(pay(gw, alice, eur(100)));
1998 env.close();
1999
2000 env(offer(alice, XRP(100), usd(100)), Txflags(tfPassive));
2001 env(offer(alice, usd(100), XRP(100)), Txflags(tfPassive));
2002 env(offer(alice, XRP(100), eur(100)), Txflags(tfPassive));
2003 env.close();
2004
2005 TER const expectedTer = TER{temBAD_PATH_LOOP};
2006 env(pay(alice, bob, eur(1)),
2007 Path(~usd, ~XRP, ~eur),
2008 Sendmax(XRP(1)),
2009 Txflags(tfNoRippleDirect),
2010 Ter(expectedTer));
2011 };
2013 }
2014 {
2015 // Payment path ending with XRP
2016 auto const test = [&](auto&& issue1, auto&& issue2) {
2017 Env env(*this);
2018 env.fund(XRP(10'000), alice, bob, gw);
2019 auto const usd =
2020 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}});
2021 auto const eur =
2022 issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}});
2023 env(pay(gw, alice, usd(100)));
2024 env(pay(gw, alice, eur(100)));
2025 env.close();
2026
2027 env(offer(alice, XRP(100), usd(100)), Txflags(tfPassive));
2028 env(offer(alice, eur(100), XRP(100)), Txflags(tfPassive));
2029 env.close();
2030 // EUR -> //XRP -> //USD ->XRP
2031 env(pay(alice, bob, XRP(1)),
2032 Path(~XRP, ~usd, ~XRP),
2033 Sendmax(eur(1)),
2034 Txflags(tfNoRippleDirect),
2036 };
2038 }
2039 {
2040 // Payment where loop is formed in the middle of the
2041 // path, not on an endpoint
2042 auto const test = [&](auto&& issue1, auto&& issue2, auto&& issue3) {
2043 Env env(*this);
2044 env.fund(XRP(10'000), alice, bob, gw);
2045 env.close();
2046 auto const usd =
2047 issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}});
2048 auto const eur =
2049 issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}});
2050 auto const jpy =
2051 issue3({.env = env, .token = "JPY", .issuer = gw, .holders = {alice, bob}});
2052 env(pay(gw, alice, usd(100)));
2053 env(pay(gw, alice, eur(100)));
2054 env(pay(gw, alice, jpy(100)));
2055 env.close();
2056
2057 env(offer(alice, usd(100), XRP(100)), Txflags(tfPassive));
2058 env(offer(alice, XRP(100), eur(100)), Txflags(tfPassive));
2059 env(offer(alice, eur(100), XRP(100)), Txflags(tfPassive));
2060 env(offer(alice, XRP(100), jpy(100)), Txflags(tfPassive));
2061 env.close();
2062
2063 env(pay(alice, bob, jpy(1)),
2064 Path(~XRP, ~eur, ~XRP, ~jpy),
2065 Sendmax(usd(1)),
2066 Txflags(tfNoRippleDirect),
2068 };
2070 }
2071 }
2072
2073 void
2075 {
2076 testcase("Max Flow/Self Payment Edge Cases");
2077 using namespace jtx;
2078 Account const gw("gw");
2079 Account const alice("alice");
2080 Account const carol("carol");
2081 Account const bob("bob");
2082
2083 // Direct payment between holders.
2084 {
2085 Env env(*this);
2086
2087 env.fund(XRP(1'000), gw, alice, carol);
2088
2089 MPT const usd =
2090 MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100});
2091
2092 env(pay(gw, alice, usd(100)));
2093
2094 env(pay(alice, carol, usd(100)));
2095
2096 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2097 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2098 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2099 }
2100
2101 // Direct payment between holders. Partial payment limited
2102 // by holder funds.
2103 {
2104 Env env(*this);
2105
2106 env.fund(XRP(1'000), gw, alice, carol);
2107
2108 MPT const usd =
2109 MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100});
2110
2111 env(pay(gw, alice, usd(80)));
2112
2113 env(pay(alice, carol, usd(100)), Txflags(tfPartialPayment));
2114
2115 BEAST_EXPECT(env.balance(gw, usd) == usd(-80));
2116 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2117 BEAST_EXPECT(env.balance(carol, usd) == usd(80));
2118 }
2119
2120 // Direct payment between holders. Partial payment limited
2121 // by holder funds. OutstandingAmount is already at max
2122 // before the payment.
2123 {
2124 Env env(*this);
2125
2126 env.fund(XRP(1'000), gw, alice, carol, bob);
2127
2128 MPT const usd = MPTTester(
2129 {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 100});
2130
2131 env(pay(gw, bob, usd(20)));
2132 env(pay(gw, alice, usd(80)));
2133
2134 env(pay(alice, carol, usd(100)), Txflags(tfPartialPayment));
2135
2136 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2137 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2138 BEAST_EXPECT(env.balance(carol, usd) == usd(80));
2139 }
2140
2141 // Cross-currency payment holder to holder. Holder owns an
2142 // offer. OutstandingAmount is already at max before the
2143 // payment.
2144 {
2145 Env env(*this);
2146
2147 env.fund(XRP(1'000), gw, alice, carol, bob);
2148
2149 MPT const usd =
2150 MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100});
2151
2152 env(pay(gw, alice, usd(100)));
2153
2154 env(offer(alice, XRP(100), usd(100)));
2155
2156 env(pay(bob, carol, usd(100)), Sendmax(XRP(100)), Path(~usd));
2157
2158 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2159 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2160 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2161 }
2162
2163 // Cross-currency payment holder to holder. Issuer owns an
2164 // offer. OutstandingAmount is already at max before the
2165 // payment. Since an issuer owns the offer, it issues more
2166 // tokens to another holder, and the payment fails.
2167 {
2168 Env env(*this);
2169
2170 env.fund(XRP(1'000), gw, alice, carol);
2171
2172 MPT const usd =
2173 MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100});
2174
2175 env(pay(gw, carol, usd(100)));
2176
2177 env(offer(gw, XRP(100), usd(100)));
2178
2179 env(pay(alice, carol, usd(100)),
2180 Sendmax(XRP(100)),
2181 Path(~usd),
2182 Txflags(tfPartialPayment),
2183 Ter(tecPATH_DRY));
2184
2185 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2186 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2187 }
2188
2189 // Cross-currency payment holder to holder. Issuer owns an
2190 // offer. OutstandingAmount is at 80USD before the payment.
2191 // Consequently, the issuer can issue 20USD more.
2192 {
2193 Env env(*this);
2194
2195 env.fund(XRP(1'000), gw, alice, carol);
2196
2197 MPT const usd =
2198 MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100});
2199
2200 env(pay(gw, carol, usd(80)));
2201
2202 env(offer(gw, XRP(100), usd(100)));
2203
2204 env(pay(alice, carol, usd(100)),
2205 Sendmax(XRP(100)),
2206 Path(~usd),
2207 Txflags(tfPartialPayment));
2208
2209 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2210 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2211 }
2212
2213 // Cross-currency payment holder to holder. Holder owns an
2214 // offer. The offer buys more MPT's. The payment fails since
2215 // OutstandingAmount is already at max.
2216 {
2217 Env env(*this);
2218
2219 env.fund(XRP(1'000), gw, alice);
2220
2221 MPT const usd =
2222 MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 100});
2223
2224 env(pay(gw, alice, usd(100)));
2225
2226 env(offer(alice, usd(100), XRP(100)));
2227
2228 env(pay(gw, alice, XRP(100)), Sendmax(usd(100)), Path(~XRP), Ter(tecPATH_PARTIAL));
2229
2230 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2231 BEAST_EXPECT(env.balance(alice, usd) == usd(100));
2232 }
2233
2234 // Cross-currency payment issuer to holder. Holder owns an
2235 // offer. The offer buys EUR, OutstandingAmount goes to max,
2236 // no overflow. The offer redeems USD to the issuer. While
2237 // OutstandingAmount is already at max, the payment succeeds
2238 // since USD is redeemed.
2239 {
2240 auto const test = [&](auto&& issue1, auto&& issue2) {
2241 Env env(*this);
2242
2243 env.fund(XRP(1'000), gw, alice, carol);
2244 env.close();
2245
2246 auto const usd = issue1({
2247 .env = env,
2248 .token = "USD",
2249 .issuer = gw,
2250 .holders = {alice, carol},
2251 .limit = 100,
2252 });
2253 using TUsd = std::decay_t<decltype(usd)>;
2254 auto const eur = issue2({
2255 .env = env,
2256 .token = "EUR",
2257 .issuer = gw,
2258 .holders = {alice, carol},
2259 .limit = 100,
2260 });
2261
2262 env(pay(gw, alice, usd(100)));
2263
2264 env(offer(alice, eur(100), usd(100)));
2265
2266 env(pay(gw, carol, usd(100)), Sendmax(eur(100)), Path(~usd));
2267
2268 if constexpr (std::is_same_v<TUsd, MPT>)
2269 BEAST_EXPECT(env.balance(gw, usd) == usd(-100));
2270 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2271 BEAST_EXPECT(env.balance(alice, eur) == eur(100));
2272 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2273 };
2275 }
2276
2277 // Cross-currency payment holder to holder. Offer is owned
2278 // by destination account. OutstandingAmount is not at max.
2279 {
2280 Env env(*this);
2281
2282 env.fund(XRP(1'000), gw, alice, carol);
2283
2284 MPT const usd =
2285 MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 120});
2286
2287 env(pay(gw, carol, usd(100)));
2288
2289 env(offer(carol, XRP(100), usd(100)));
2290
2291 env(pay(alice, carol, usd(100)),
2292 Path(~usd),
2293 Sendmax(XRP(100)),
2294 Txflags(tfPartialPayment));
2295
2296 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2297 }
2298
2299 // Cross-currency payment holder to holder. Offer is owned
2300 // by destination account. OutstandingAmount is already at
2301 // max.
2302 {
2303 Env env(*this);
2304
2305 env.fund(XRP(1'000), gw, alice, carol);
2306
2307 MPT const usd =
2308 MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100});
2309
2310 env(pay(gw, carol, usd(100)));
2311
2312 env(offer(carol, XRP(100), usd(100)));
2313
2314 env(pay(alice, carol, usd(100)),
2315 Path(~usd),
2316 Sendmax(XRP(100)),
2317 Txflags(tfPartialPayment));
2318
2319 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2320 }
2321
2322 // Cross-currency payment holder to holder. Multiple offers
2323 // with different owners - some holders, some issuer.
2324 {
2325 auto const test = [&](auto&& issue1, auto&& issue2) {
2326 Env env(*this);
2327
2328 env.fund(XRP(1'000), gw, alice, carol, bob);
2329 env.close();
2330
2331 auto const usd = issue1({
2332 .env = env,
2333 .token = "USD",
2334 .issuer = gw,
2335 .holders = {alice, carol, bob},
2336 .limit = 1'000,
2337 });
2338 using TUsd = std::decay_t<decltype(usd)>;
2339 auto const eur = issue2({
2340 .env = env,
2341 .token = "EUR",
2342 .issuer = gw,
2343 .holders = {alice, carol, bob},
2344 .limit = 1'000,
2345 });
2346 using TEur = std::decay_t<decltype(eur)>;
2347
2348 env(pay(gw, alice, usd(600)));
2349 env(pay(gw, carol, eur(700)));
2350
2351 env(offer(alice, eur(100), usd(105)));
2352 env(offer(gw, eur(100), usd(104)));
2353 env(offer(gw, eur(100), usd(103)));
2354 env(offer(gw, eur(100), usd(102)));
2355 env(offer(gw, eur(100), usd(101)));
2356 env(offer(gw, eur(100), usd(100)));
2357
2358 env(pay(carol, bob, usd(2'000)),
2359 Sendmax(eur(2'000)),
2360 Path(~usd),
2361 Txflags(tfPartialPayment));
2362
2363 if constexpr (std::is_same_v<TUsd, MPT>)
2364 {
2365 BEAST_EXPECT(env.balance(gw, usd) == usd(-1'000));
2366 BEAST_EXPECT(env.balance(alice, usd) == usd(495));
2367 BEAST_EXPECT(env.balance(bob, usd) == usd(505));
2368 }
2369 else
2370 {
2371 BEAST_EXPECT(env.balance(gw, usd) == usd(0));
2372 BEAST_EXPECT(env.balance(alice, usd) == usd(495));
2373 // all offers are consumed since the limit is different
2374 // for the holders
2375 BEAST_EXPECT(env.balance(bob, usd) == usd(615));
2376 }
2377 if constexpr (std::is_same_v<TEur, MPT>)
2378 {
2379 if constexpr (std::is_same_v<TUsd, MPT>)
2380 {
2381 BEAST_EXPECT(env.balance(carol, eur) == eur(210));
2382 }
2383 else
2384 {
2385 // carol sells 600USD since all offers are consumed
2386 BEAST_EXPECT(env.balance(carol, eur) == eur(100));
2387 }
2388 }
2389 else
2390 {
2391 BEAST_EXPECT(
2392 env.balance(carol, eur) == STAmount(eur, UINT64_C(209'9009900990099), -13));
2393 }
2394 // 100/101 is partially crossed (90/91) and 100/100 is
2395 // unfunded when MPT. All offers are consumed if IOU.
2396 env.require(Offers(gw, 0));
2397 // alice's offer is consumed.
2398 env.require(Offers(alice, 0));
2399 };
2401 }
2402
2403 // Cross-currency payment holder to holder. Multiple offers
2404 // with different owners - some holders, some issuer. Source
2405 // and destination account is the same.
2406 {
2407 Env env(*this);
2408
2409 env.fund(XRP(1'000), gw, alice, carol);
2410
2411 MPT const usd =
2412 MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 2'000});
2413
2414 env(pay(gw, carol, usd(1'000)));
2415 env(pay(gw, alice, usd(600)));
2416
2417 env(offer(gw, XRP(5), usd(11)));
2418 env(offer(gw, XRP(6), usd(13)));
2419 env(offer(carol, XRP(7), usd(15)));
2420 env(offer(carol, XRP(17), usd(35)));
2421 env(offer(carol, XRP(23), usd(47)));
2422 env(offer(alice, XRP(10), usd(19)));
2423 env(offer(alice, XRP(15), usd(28)));
2424 env(offer(alice, XRP(25), usd(46)));
2425
2426 env(pay(carol, carol, usd(200)), Sendmax(XRP(100)), Txflags(tfPartialPayment));
2427
2428 BEAST_EXPECT(env.balance(gw, usd) == usd(-1'624));
2429 BEAST_EXPECT(env.balance(carol, usd) == usd(1'102));
2430 env.require(Offers(carol, 0));
2431 env.require(Offers(gw, 0));
2432 // 100 XRP's = 5+6+7+17+23+10+15+17(25-8)
2433 BEAST_EXPECT(isOffer(env, alice, XRP(8), usd(15)));
2434 }
2435
2436 // Cross-currency payment holder to holder. Multiple offers
2437 // with different owners - some holders, some issuer.
2438 {
2439 Env env(*this);
2440 env.fund(XRP(1'000), gw, alice, carol, bob);
2441
2442 MPT const usd =
2443 MPTTester({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 30});
2444
2445 env(pay(gw, alice, usd(12))); // 12, 15, 20
2446 env(pay(gw, bob, usd(5))); // 5, 5, 10
2447
2448 env(offer(alice, XRP(10), usd(12)));
2449 env(offer(gw, XRP(10), usd(11)));
2450 env(offer(bob, XRP(10), usd(10)));
2451
2452 env(pay(carol, bob, usd(30)), Sendmax(XRP(30)), Txflags(tfPartialPayment), Path(~usd));
2453 BEAST_EXPECT(env.balance(gw, usd) == usd(-28));
2454 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2455 // 12+11+5
2456 BEAST_EXPECT(env.balance(bob, usd) == usd(28));
2457 }
2458
2459 // Cross-currency payment two steps. Second book step
2460 // issues, first book step redeems.
2461 {
2462 Account const dan{"dan"};
2463 Account const john{"john"};
2464 Account const ed{"ed"};
2465 Account const sam{"sam"};
2466 Account const bill{"bill"};
2467
2468 struct TestData
2469 {
2470 int maxAmt;
2471 int sendMax;
2472 int dstTrustLimit;
2473 int dstExpectEUR;
2474 int outstandingUSD;
2475 int expEdBuyUSD;
2476 int expDanBuyUSD;
2477 int expBobSellUSD;
2478 int expGwXRP; // whole XRP excluding the fees
2479 std::uint8_t expOffersGw;
2480 bool lastGwBuyUSD;
2481 [[nodiscard]] std::uint8_t
2482 expOffersBob() const
2483 {
2484 return expBobSellUSD == 0 ? 1 : 0;
2485 }
2486 [[nodiscard]] std::uint8_t
2487 expOffersEd() const
2488 {
2489 // partially crossed if < 100
2490 return expEdBuyUSD < 100 ? 1 : 0;
2491 }
2492 [[nodiscard]] std::uint8_t
2493 expOffersDan() const
2494 {
2495 return expDanBuyUSD == 0 ? 1 : 0;
2496 }
2497 };
2498
2499 auto const test = [&](TestData const& d) {
2500 Env env(*this);
2501 env.fund(XRP(1'000), gw, alice, carol, bob, dan, john, ed, sam, bill);
2502 env.close();
2503
2504 MPT const usd = MPTTester(
2505 {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = d.maxAmt});
2506 auto const eur = gw["EUR"];
2507
2508 env(pay(gw, alice, usd(100)));
2509 env(pay(gw, carol, usd(100)));
2510 env(pay(gw, bob, usd(100)));
2511
2512 BEAST_EXPECT(env.balance(gw, usd) == usd(-300));
2513
2514 env(trust(john, eur(100)));
2515 env(trust(dan, eur(100)));
2516 env(trust(ed, eur(100)));
2517 env(trust(bill, eur(d.dstTrustLimit)));
2518
2519 env(pay(gw, john, eur(100)));
2520 env(pay(gw, dan, eur(100)));
2521 env(pay(gw, ed, eur(100)));
2522 env.close();
2523
2524 // Sell USD
2525 env(offer(alice, XRP(100), usd(100)));
2526 env.close(); // close after each create to ensure
2527 // the order
2528 env(offer(carol, XRP(100), usd(100)));
2529 env.close();
2530 if (!d.lastGwBuyUSD)
2531 {
2532 env(offer(gw, XRP(100), usd(100)));
2533 env.close();
2534 }
2535 env(offer(bob, XRP(100), usd(100)));
2536 env.close();
2537 if (d.lastGwBuyUSD)
2538 {
2539 env(offer(gw, XRP(100), usd(100)));
2540 env.close();
2541 }
2542 BEAST_EXPECT(expectOffers(env, alice, 1));
2543 BEAST_EXPECT(expectOffers(env, carol, 1));
2544 BEAST_EXPECT(expectOffers(env, gw, 1));
2545 BEAST_EXPECT(expectOffers(env, bob, 1));
2546
2547 // Buy USD
2548 env(offer(john, usd(100), eur(100)));
2549 env.close();
2550 env(offer(gw, usd(100), eur(100)));
2551 env.close();
2552 env(offer(dan, usd(100), eur(100)));
2553 env.close();
2554 env(offer(ed, usd(100), eur(100)));
2555 env.close();
2556 BEAST_EXPECT(expectOffers(env, john, 1));
2557 BEAST_EXPECT(expectOffers(env, gw, 2));
2558 BEAST_EXPECT(expectOffers(env, dan, 1));
2559 BEAST_EXPECT(expectOffers(env, ed, 1));
2560
2561 env(pay(sam, bill, eur(400)),
2562 Sendmax(XRP(d.sendMax)),
2563 Path(~usd, ~eur),
2564 Txflags(tfPartialPayment | tfNoRippleDirect));
2565 env.close();
2566
2567 auto const baseFee = env.current()->fees().base.drops();
2568 BEAST_EXPECT(env.balance(bill, eur) == eur(d.dstExpectEUR));
2569 BEAST_EXPECT(env.balance(john, usd) == usd(100));
2570 BEAST_EXPECT(env.balance(dan, usd) == usd(d.expDanBuyUSD));
2571 BEAST_EXPECT(env.balance(ed, usd) == usd(d.expEdBuyUSD));
2572 BEAST_EXPECT(env.balance(gw, usd) == usd(-d.outstandingUSD));
2573 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
2574 BEAST_EXPECT(env.balance(carol, usd) == usd(0));
2575 BEAST_EXPECT(env.balance(bob, usd) == usd(100 - d.expBobSellUSD));
2576 BEAST_EXPECT(env.balance(gw) == XRPAmount{d.expGwXRP * kDropsPerXrp - baseFee * 9});
2577 BEAST_EXPECT(expectOffers(env, john, 0));
2578 BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw));
2579 BEAST_EXPECT(expectOffers(env, dan, d.expOffersDan()));
2580 BEAST_EXPECT(expectOffers(env, ed, d.expOffersEd()));
2581 BEAST_EXPECT(expectOffers(env, alice, 0));
2582 BEAST_EXPECT(expectOffers(env, carol, 0));
2583 BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob()));
2584 };
2585
2586 // clang-format off
2588 // Sell USD: alice, carol, bob, gw are consumed.
2589 // Buy USD: john, gw, dan, ed are consumed.
2590 // gw's sell USD is consumed because there is sufficient available balance (100USD).
2591 // but OutstandingAmount is 300USD because gw's sell offer is balanced out by
2592 // gw's buy offer.
2593 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2594 { .maxAmt=400, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=400, .outstandingUSD=300, .expEdBuyUSD=100, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false},
2595 // Sell USD: alice, carol, bob, gw are consumed.
2596 // Buy USD: john, gw, dan, ed (partially) are consumed.
2597 // gw's sell USD is partially consumed because there is available balance (50USD).
2598 // OutstandingAmount is 250USD because gw's sell offer is partially balanced by
2599 // gw's buy offer. ed's offer is on the books because it's partially crossed.
2600 // gw's offer is removed from the order book because it's partially consumed and
2601 // the remaining offer is unfunded.
2602 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2603 { .maxAmt=350, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=350, .outstandingUSD=250, .expEdBuyUSD=50, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=false},
2604 // Sell USD: alice, carol, bob are consumed; gw's is unfunded
2605 // since OutstandingAmount is initially at MaximumAmount.
2606 // Buy USD: john, gw, dan are consumed; ed's remains on the order
2607 // book since 300USD is the sell limit.
2608 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2609 { .maxAmt=300, .sendMax=400, .dstTrustLimit=400, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false},
2610 // Same as above. bill's trustline limit sets the output to 300USD.
2611 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2612 { .maxAmt=300, .sendMax=400, .dstTrustLimit=300, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false},
2613 // Sell USD: alice, carol, bob are consumed; gw's removed from
2614 // the order book since it's unfunded.
2615 // Buy USD: john, gw, dan are consumed; ed's remains on the order
2616 // book since 300USD is the limit.
2617 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2618 { .maxAmt=300, .sendMax=400, .dstTrustLimit=300, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=true},
2619 // Sell USD: alice, carol are consumed; gw's removed from
2620 // the order book in rev pass since it's unfunded; bob's
2621 // remains on the order book.
2622 // Buy USD: john, gw; ed's, dan's remains on the order
2623 // book since 300USD is the limit.
2624 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2625 { .maxAmt=300, .sendMax=200, .dstTrustLimit=300, .dstExpectEUR=200, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=0, .expBobSellUSD=0, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false},
2626 // Same as three tests above since limited by buy 300USD (gw offer is unfunded)
2627 //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw
2628 { .maxAmt=300, .sendMax=380, .dstTrustLimit=400, .dstExpectEUR=300, .outstandingUSD=200, .expEdBuyUSD=0, .expDanBuyUSD=100, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=false},
2629 };
2630 // clang-format on
2631 for (auto const& t : tests)
2632 test(t);
2633 }
2634
2635 // Cross-currency payment. BookStep issues, the first step
2636 // redeems.
2637 {
2638 Account const ed{"ed"};
2639
2640 struct TestData
2641 {
2642 int maxAmt;
2643 int sendMax;
2644 int gwOffer; // quality == 1
2645 int dstExpectXRP;
2646 int outstandingUSD;
2647 int expBobBuyUSD;
2648 int expGwXRP; // whole XRP excluding the fees
2649 std::uint8_t expOffersGw;
2650 bool lastGwBuyUSD;
2651 [[nodiscard]] std::uint8_t
2652 expOffersBob() const
2653 {
2654 // partially crossed if < 100
2655 return expBobBuyUSD < 100 ? 1 : 0;
2656 }
2657 };
2658
2659 auto const test = [&](TestData const& d) {
2660 Env env(*this);
2661 env.fund(XRP(1'000), gw, alice, carol, bob, ed);
2662 env.close();
2663
2664 MPT const usd =
2665 MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = d.maxAmt});
2666
2667 env(pay(gw, alice, usd(300)));
2668 env.close();
2669
2670 env(offer(carol, usd(100), XRP(100)));
2671 env.close();
2672 if (!d.lastGwBuyUSD)
2673 {
2674 env(offer(gw, usd(d.gwOffer), XRP(d.gwOffer)));
2675 env.close();
2676 }
2677 env(offer(bob, usd(100), XRP(100)));
2678 env.close();
2679 if (d.lastGwBuyUSD)
2680 {
2681 env(offer(gw, usd(d.gwOffer), XRP(d.gwOffer)));
2682 env.close();
2683 }
2684
2685 BEAST_EXPECT(expectOffers(env, carol, 1));
2686 BEAST_EXPECT(expectOffers(env, bob, 1));
2687 BEAST_EXPECT(expectOffers(env, gw, 1));
2688 BEAST_EXPECT(env.balance(gw, usd) == usd(-300));
2689
2690 env(pay(alice, ed, XRP(300)),
2691 Sendmax(usd(d.sendMax)),
2692 Path(~XRP),
2693 Txflags(tfPartialPayment | tfNoRippleDirect));
2694 env.close();
2695
2696 auto const baseFee = env.current()->fees().base.drops();
2697 BEAST_EXPECT(env.balance(alice, usd) == usd(300 - d.sendMax));
2698 BEAST_EXPECT(env.balance(carol, usd) == usd(100));
2699 BEAST_EXPECT(env.balance(bob, usd) == usd(d.expBobBuyUSD));
2700 BEAST_EXPECT(env.balance(ed) == XRP(d.dstExpectXRP));
2701 BEAST_EXPECT(env.balance(gw, usd) == usd(-d.outstandingUSD));
2702 BEAST_EXPECT(env.balance(gw) == XRPAmount{d.expGwXRP * kDropsPerXrp - baseFee * 3});
2703 BEAST_EXPECT(expectOffers(env, carol, 0));
2704 BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob()));
2705 BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw));
2706 };
2707
2708 // clang-format off
2710 // Buy USD: carol, gw, bob are consumed.
2711 // Gw gets 300USD from alice; carol and bob buy 200USD,
2712 // therefore OutstandingAmount is 200.
2713 //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw
2714 { .maxAmt=300, .sendMax=300, .gwOffer=100, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=0, .lastGwBuyUSD=false},
2715 // Same as above. Gw offer location in the order book doesn't matter
2716 //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw
2717 { .maxAmt=300, .sendMax=300, .gwOffer=100, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=0, .lastGwBuyUSD=true},
2718 // Buy USD: carol, gw are consumed. bob's offer remains on the order book.
2719 // Gw gets 300USD from alice; carol buys 100USD,
2720 // therefore OutstandingAmount is 100.
2721 //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw
2722 { .maxAmt=300, .sendMax=300, .gwOffer=200, .dstExpectXRP=1300, .outstandingUSD=100, .expBobBuyUSD=0, .expGwXRP=800, .expOffersGw=0, .lastGwBuyUSD=false},
2723 // Buy USD: carol, bob are consumed; gw's is partially consumed (100/100) since it's last.
2724 // Gw gets 300USD from alice; carol and bob buy 200USD,
2725 // therefore OutstandingAmount is 200.
2726 //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw
2727 { .maxAmt=300, .sendMax=300, .gwOffer=200, .dstExpectXRP=1300, .outstandingUSD=200, .expBobBuyUSD=100, .expGwXRP=900, .expOffersGw=1, .lastGwBuyUSD=true},
2728 // Buy USD: carol, bob are consumed; gw's is partially consumed (50/50) since it's last
2729 // and sendMax limits the output.
2730 // Gw gets 250USD from alice; carol and bob buy 200USD, alice has 50USD left,
2731 // therefore OutstandingAmount is 200.
2732 //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw
2733 { .maxAmt=300, .sendMax=250, .gwOffer=200, .dstExpectXRP=1250, .outstandingUSD=250, .expBobBuyUSD=100, .expGwXRP=950, .expOffersGw=1, .lastGwBuyUSD=true},
2734 };
2735 // clang-format on
2736 for (auto const& t : tests)
2737 test(t);
2738 }
2739
2740 // Cross-currency payment. BookStep redeems, the last step
2741 // issues.
2742 {
2743 Account const ed{"ed"};
2744
2745 struct TestData
2746 {
2747 int maxAmt;
2748 int sendMax;
2749 int initDst;
2750 int gwOffer; // quality == 1
2751 int dstExpectUSD;
2752 int outstandingUSD;
2753 int expAliceXRP; // whole XRP excluding the fees
2754 int expBobSellUSD;
2755 int expGwXRP;
2756 std::uint8_t expOffersGw;
2757 bool lastGwBuyUSD;
2758 [[nodiscard]] std::uint8_t
2759 expOffersBob() const
2760 {
2761 return expBobSellUSD > 0 && expBobSellUSD < 100 ? 1 : 0;
2762 }
2763 };
2764
2765 auto const test = [&](TestData const& d) {
2766 Env env(*this);
2767 env.fund(XRP(1'000), gw, alice, carol, bob, ed);
2768 env.close();
2769
2770 MPT const usd = MPTTester(
2771 {.env = env, .issuer = gw, .holders = {carol, bob, ed}, .maxAmt = d.maxAmt});
2772
2773 if (d.initDst != 0)
2774 env(pay(gw, ed, usd(d.initDst)));
2775 env(pay(gw, carol, usd(100)));
2776 env(pay(gw, bob, usd(100)));
2777 env.close();
2778
2779 env(offer(carol, XRP(100), usd(100)));
2780 env.close();
2781 if (!d.lastGwBuyUSD)
2782 {
2783 env(offer(gw, XRP(d.gwOffer), usd(d.gwOffer)));
2784 env.close();
2785 }
2786 env(offer(bob, XRP(100), usd(100)));
2787 env.close();
2788 if (d.lastGwBuyUSD)
2789 {
2790 env(offer(gw, XRP(d.gwOffer), usd(d.gwOffer)));
2791 env.close();
2792 }
2793
2794 BEAST_EXPECT(expectOffers(env, carol, 1));
2795 BEAST_EXPECT(expectOffers(env, bob, 1));
2796 BEAST_EXPECT(expectOffers(env, gw, 1));
2797 BEAST_EXPECT(env.balance(gw, usd) == usd(-200 - d.initDst));
2798
2799 env(pay(alice, ed, usd(300)),
2800 Sendmax(XRP(d.sendMax)),
2801 Path(~usd),
2802 Txflags(tfPartialPayment | tfNoRippleDirect));
2803 env.close();
2804
2805 auto const baseFee = env.current()->fees().base.drops();
2806 BEAST_EXPECT(
2807 env.balance(alice) == XRPAmount{d.expAliceXRP * kDropsPerXrp - baseFee});
2808 BEAST_EXPECT(env.balance(carol, usd) == usd(0));
2809 BEAST_EXPECT(env.balance(bob, usd) == usd(100 - d.expBobSellUSD));
2810 BEAST_EXPECT(env.balance(ed, usd) == usd(d.dstExpectUSD));
2811 BEAST_EXPECT(env.balance(gw, usd) == usd(-d.outstandingUSD));
2812 BEAST_EXPECT(
2813 env.balance(gw) ==
2814 XRPAmount{
2815 d.expGwXRP * kDropsPerXrp - baseFee * (4 + (d.initDst != 0 ? 1 : 0))});
2816 BEAST_EXPECT(expectOffers(env, carol, 0));
2817 BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob()));
2818 BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw));
2819 };
2820
2821 // clang-format off
2823 // Sell USD: carol, gw, bob are consumed.
2824 // ed buys 300USD from carol, gw, bob therefore OutstandingAmount is 300.
2825 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2826 { .maxAmt=300, .sendMax=300, .initDst=0, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=700, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false},
2827 // Same as above. Gw offer location in the order book doesn't matter
2828 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2829 { .maxAmt=300, .sendMax=300, .initDst=0, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=700, .expBobSellUSD=100, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=true},
2830 // Sell USD: carol, bob are consumed, gw is partially consumed.
2831 // ed buys 200 from carol and bob and 50 from gw because gw can only issue 50
2832 // (300(max) - 200(carol+bob) - 50(ed)). ed buys 250 from carol, gw, bob and has 50 initially,
2833 // therefore OutstandingAmount is 300.
2834 // gw's offer is removed from the order book because it's partially consumed and the remaining
2835 // offer is unfunded.
2836 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2837 { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=false},
2838 // Same as above. Gw offer location in the order book doesn't matter.
2839 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2840 { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true},
2841 // Same as above. Gw offer size doesn't matter.
2842 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2843 { .maxAmt=300, .sendMax=300, .initDst=50, .gwOffer=200, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true},
2844 // Sell USD: carol, gw are consumed, bob is partially consumed.
2845 // ed buys 200 from carol and gw and 50 form bob because of sendMax limit. bob keeps 50,
2846 // therefore OutstandingAmount is 300.
2847 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2848 { .maxAmt=300, .sendMax=250, .initDst=0, .gwOffer=100, .dstExpectUSD=250, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=50, .expGwXRP=1100, .expOffersGw=0, .lastGwBuyUSD=false},
2849 // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit.
2850 // ed buys 200 from carol and bob and 50 from gw. Therefore, OutstandingAmount is 250.
2851 // gw's offer remains on the order book because it's partially consumed and has more funds.
2852 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2853 { .maxAmt=300, .sendMax=250, .initDst=0, .gwOffer=100, .dstExpectUSD=250, .outstandingUSD=250, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=1, .lastGwBuyUSD=true},
2854 // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit, also
2855 // there is only 50 available to issue. ed buys 200 from carol and bob and 50 from gw, plus
2856 // he has initially 50, therefore OutstandingAmount is 300.
2857 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2858 { .maxAmt=300, .sendMax=250, .initDst=50, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=750, .expBobSellUSD=100, .expGwXRP=1050, .expOffersGw=0, .lastGwBuyUSD=true},
2859 // Sell USD: carol, bob are consumed, gw is not consumed because there is not available funds
2860 // to issue. ed buys 200 from carol and bob and, plus he has initially 100,
2861 // therefore OutstandingAmount is 300. gw offer is removed because it's unfunded.
2862 //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw
2863 { .maxAmt=300, .sendMax=250, .initDst=100, .gwOffer=100, .dstExpectUSD=300, .outstandingUSD=300, .expAliceXRP=800, .expBobSellUSD=100, .expGwXRP=1000, .expOffersGw=0, .lastGwBuyUSD=true},
2864 };
2865 // clang-format on
2866 for (auto const& t : tests)
2867 test(t);
2868 }
2869
2870 // Cross-currency payment with BookStep as the first step. BookStep
2871 // limits the buy amount to what the issuer can still issue. That
2872 // limits the issuer, not carol's offer: it keeps its funded
2873 // remainder, and since the step stops there the issuer's own offer
2874 // behind it at the same quality is not reached either.
2875 {
2876 auto const test = [&](int sendMax) {
2877 Env env(*this);
2878 env.fund(XRP(1'000), gw, alice, carol);
2879
2880 MPT const usd = MPTTester({.env = env, .issuer = gw, .maxAmt = 300});
2881
2882 env(offer(carol, usd(400), XRP(400)));
2883 env(offer(gw, usd(100), XRP(100)));
2884 BEAST_EXPECT(expectOffers(env, carol, 1));
2885 BEAST_EXPECT(expectOffers(env, gw, 1));
2886
2887 env(pay(gw, alice, XRP(500)),
2888 Sendmax(usd(sendMax)),
2889 Path(~XRP),
2890 Txflags(tfPartialPayment | tfNoRippleDirect));
2891
2892 BEAST_EXPECT(env.balance(alice) == XRP(1'300));
2893 BEAST_EXPECT(env.balance(gw, usd) == usd(-300));
2894 BEAST_EXPECT(env.balance(carol, usd) == usd(300));
2895 BEAST_EXPECT(expectOffers(env, carol, 1, {{usd(100), XRP(100)}}));
2896 BEAST_EXPECT(expectOffers(env, gw, 1));
2897 };
2898 test(500);
2899 test(350);
2900 }
2901
2902 // Same-quality offers behind the clipped one, with the issuer's own
2903 // offer at the back. Once the issuer has nothing left to issue the
2904 // step stops: no offer is consumed for zero, deleted, or given an
2905 // MPToken.
2906 {
2907 Account const dan{"dan"};
2908 Account const erin{"erin"};
2909 auto const test = [&](int outstanding) {
2910 Env env(*this);
2911 env.fund(XRP(1'000), gw, alice, carol, dan, erin);
2912 env.close();
2913
2914 MPT const usd =
2915 MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 300});
2916 if (outstanding)
2917 env(pay(gw, carol, usd(outstanding)));
2918 env(offer(carol, usd(400), XRP(400)));
2919 env.close();
2920 env(offer(dan, usd(100), XRP(100)));
2921 env.close();
2922 env(offer(erin, usd(400), XRP(400)));
2923 env.close();
2924 env(offer(gw, usd(100), XRP(100)));
2925 env.close();
2926
2927 int const issued = 300 - outstanding;
2928 env(pay(gw, alice, XRP(500)),
2929 Sendmax(usd(500)),
2930 Path(~XRP),
2931 Txflags(tfPartialPayment | tfNoRippleDirect),
2932 Ter(issued ? TER{tesSUCCESS} : TER{tecPATH_DRY}));
2933 env.close();
2934
2935 BEAST_EXPECT(env.balance(alice) == XRP(1'000 + issued));
2936 BEAST_EXPECT(env.balance(gw, usd) == usd(-300));
2937 BEAST_EXPECT(env.balance(carol, usd) == usd(300));
2938 BEAST_EXPECT(expectOffers(env, carol, 1, {{usd(400 - issued), XRP(400 - issued)}}));
2939 BEAST_EXPECT(expectOffers(env, dan, 1));
2940 BEAST_EXPECT(expectOffers(env, erin, 1));
2941 BEAST_EXPECT(expectOffers(env, gw, 1));
2942 BEAST_EXPECT(!env.le(keylet::mptoken(usd.mpt(), dan)));
2943 BEAST_EXPECT(!env.le(keylet::mptoken(usd.mpt(), erin)));
2944 };
2945 // carol is clipped to 300 and keeps 100/100
2946 test(0);
2947 // nothing left to issue, the step is dry
2948 test(300);
2949 }
2950 }
2951
2952 void
2954 {
2955 // Regression: a cross-currency strand whose second book step
2956 // consumes the offer of a holder that is locked on the step's
2957 // in-asset (an MPT). The strand is XRP -> [book1: XRP/USD] ->
2958 // USD -> [book2: USD/EUR] -> EUR, so book2 has book_.in == USD
2959 // (an MPT) and its previous step is another BookStep. That is
2960 // exactly the checkMPTDEX() branch that trusts the preceding
2961 // BookStep and no longer re-checks isFrozen(owner, book_.in).
2962 //
2963 // The bypass the branch might appear to open does not exist:
2964 // for MPT, isDeepFrozen() == isFrozen() (frozen MPTs can neither
2965 // send nor receive), and OfferStream gates every offer through
2966 // isDeepFrozen(owner, assetIn) before it can reach checkMPTDEX().
2967 // So a locked mid-path holder's offer is removed by the liquidity
2968 // source and the strand simply finds no liquidity at book2.
2969 testcase("Locked mid-path holder behind a BookStep");
2970
2971 using namespace jtx;
2972
2973 Account const gw("gw");
2974 Account const alice("alice"); // book1 (XRP/USD) offer owner
2975 Account const mid("mid"); // book2 (USD/EUR) offer owner
2976 Account const sam("sam"); // source
2977 Account const bill("bill"); // destination
2978
2979 auto const test = [&](bool lock) {
2980 Env env(*this, features);
2981 env.fund(XRP(1'000), gw, alice, mid, sam, bill);
2982 env.close();
2983
2984 auto usd = MPTTester({
2985 .env = env,
2986 .issuer = gw,
2987 .holders = {alice, mid},
2988 .flags = kMptDexFlags | tfMPTCanLock,
2989 .maxAmt = 1'000,
2990 });
2991 auto const eur = gw["EUR"];
2992
2993 // alice funds book1 (sells USD for XRP); mid funds book2
2994 // (sells EUR for USD, i.e. receives the mid-path USD).
2995 env(pay(gw, alice, usd(100)));
2996 env(trust(mid, eur(100)));
2997 env(pay(gw, mid, eur(100)));
2998 env(trust(bill, eur(100)));
2999 env.close();
3000
3001 env(offer(alice, XRP(100), usd(100))); // XRP/USD, sells USD
3002 env.close();
3003 env(offer(mid, usd(100), eur(100))); // USD/EUR, sells EUR
3004 env.close();
3005 BEAST_EXPECT(expectOffers(env, alice, 1));
3006 BEAST_EXPECT(expectOffers(env, mid, 1));
3007
3008 // Lock mid on USD *after* its offer is already on the book:
3009 // the reviewer's "frozen holder's offer sits behind a
3010 // BookStep" scenario.
3011 if (lock)
3012 {
3013 usd.set({.holder = mid, .flags = tfMPTLock});
3014 env.close();
3015 }
3016
3017 env(pay(sam, bill, eur(100)),
3018 Sendmax(XRP(100)),
3019 Path(~usd, ~eur),
3020 Txflags(tfNoRippleDirect),
3021 // book1 (XRP/USD) still has liquidity, so the strand is
3022 // not fully dry; it just cannot cross book2 once mid's
3023 // offer is removed, hence PARTIAL rather than DRY.
3024 Ter(lock ? TER(tecPATH_PARTIAL) : TER(tesSUCCESS)));
3025 env.close();
3026
3027 if (lock)
3028 {
3029 // No liquidity reached book2: mid neither received USD
3030 // nor delivered EUR, so bill received nothing.
3031 BEAST_EXPECT(env.balance(bill, eur) == eur(0));
3032 BEAST_EXPECT(env.balance(mid, usd) == usd(0));
3033 }
3034 else
3035 {
3036 // The strand crosses both books: mid receives the
3037 // mid-path USD and bill receives EUR.
3038 BEAST_EXPECT(env.balance(bill, eur) == eur(100));
3039 BEAST_EXPECT(env.balance(mid, usd) == usd(100));
3040 BEAST_EXPECT(env.balance(alice, usd) == usd(0));
3041 BEAST_EXPECT(expectOffers(env, alice, 0));
3042 BEAST_EXPECT(expectOffers(env, mid, 0));
3043 }
3044 };
3045
3046 test(false); // baseline: unlocked strand succeeds
3047 test(true); // locked mid-path holder: strand finds no liquidity
3048 }
3049
3050 void
3052 {
3053 using namespace jtx;
3054
3056 testFalseDry(features);
3057 testDirectStep(features);
3058 testBookStep(features);
3059 testOfferOwnerMPTCreation(features);
3060 testTransferRate(features);
3066 testConsumeOfferOverflow(features);
3067 testSelfPayment1(features);
3068 testSelfPayment2(features);
3069 testSelfFundedXRPEndpoint(false, features);
3070 testSelfFundedXRPEndpoint(true, features);
3071 testUnfundedOffer(features);
3072 testReExecuteDirectStep(features);
3074 testLockedMidPathHolder(features);
3075 testIssuerSourceMPTLoop(features);
3076 }
3077
3078 void
3080 {
3081 // An issuer paying with its own MPT may not route it back through a
3082 // book that outputs the same MPT. It would issue at the first book
3083 // and again after the second, and with the issuer's own offer in
3084 // the second book the engine could not keep the sum within
3085 // MaximumAmount. Holders already get temBAD_PATH_LOOP for this.
3086 testcase("Issuer-sourced payment looping through its own MPT");
3087
3088 using namespace jtx;
3089
3090 Account const gw{"gw"};
3091 Account const alice{"alice"};
3092 Account const c1{"c1"};
3093 Account const e1{"e1"};
3094 Account const dan{"dan"};
3095
3096 Env env(*this, features);
3097 env.fund(XRP(1'000), gw, alice, c1, e1, dan);
3098 env.close();
3099
3100 MPT const x =
3101 MPTTester({.env = env, .issuer = gw, .holders = {alice, c1, e1, dan}, .maxAmt = 100});
3102 auto const eur = gw["EUR"];
3103 auto const usd = gw["USD"];
3104 env(trust(e1, eur(1'000)));
3105 env(trust(e1, usd(1'000)));
3106 env(trust(dan, eur(1'000)));
3107 env(pay(gw, e1, eur(1'000)));
3108 env(pay(gw, e1, usd(1'000)));
3109 env(pay(gw, alice, x(10)));
3110 env.close();
3111
3112 // Liquidity for every path below, arranged so nothing crosses at
3113 // creation.
3114 env(offer(gw, XRP(60), x(30))); // issuer sells x for XRP
3115 env(offer(gw, usd(100), x(100))); // issuer sells x for usd
3116 env.close();
3117 env(offer(c1, x(100), XRP(100))); // buys x for XRP
3118 env(offer(e1, XRP(70), usd(70))); // sells usd for XRP
3119 env(offer(e1, x(100), eur(100))); // sells eur for x
3120 env.close();
3121 BEAST_EXPECT(expectOffers(env, gw, 2));
3122 BEAST_EXPECT(expectOffers(env, c1, 1));
3123 BEAST_EXPECT(expectOffers(env, e1, 2));
3124
3125 auto const flags = Txflags(tfNoRippleDirect | tfPartialPayment);
3126
3127 // x -> XRP -> x, the issuer's own offer feeds the endpoint
3128 env(pay(gw, dan, x(100)), Sendmax(x(100)), Path(~XRP, ~x), flags, Ter(temBAD_PATH_LOOP));
3129 // x -> XRP -> x -> eur, the issuer's own offer feeds a third book
3130 env(pay(gw, dan, eur(100)),
3131 Sendmax(x(100)),
3132 Path(~XRP, ~x, ~eur),
3133 flags,
3135 // x -> XRP -> usd -> x, a limiting book before the issuer's own offer
3136 env(pay(gw, dan, x(100)),
3137 Sendmax(x(100)),
3138 Path(~XRP, ~usd, ~x),
3139 flags,
3141 // Same loop from a holder is already rejected
3142 env(pay(alice, dan, x(10)), Sendmax(x(10)), Path(~XRP, ~x), flags, Ter(temBAD_PATH_LOOP));
3143 env.close();
3144
3145 BEAST_EXPECT(env.balance(gw, x) == x(-10));
3146 BEAST_EXPECT(env.balance(c1, x) == x(0));
3147 BEAST_EXPECT(env.balance(dan, x) == x(0));
3148
3149 // The issuer paying with another asset may still take its own offer
3150 env(pay(gw, dan, x(50)), Sendmax(usd(50)), Path(~x), flags);
3151 env.close();
3152 BEAST_EXPECT(env.balance(dan, x) == x(50));
3153 BEAST_EXPECT(env.balance(gw, x) == x(-60));
3154 }
3155
3156 void
3157 run() override
3158 {
3159 using namespace jtx;
3160 auto const sa = testableAmendments();
3163 testWithFeats(sa);
3164 testEmptyStrand(sa);
3165 }
3166};
3167
3169
3170} // namespace xrpl::test
A generic endpoint for log messages.
Definition Journal.h:44
A testsuite class.
Definition suite.h:52
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
beast::Journal journal(std::string const &name)
Definition Log.cpp:137
bool modify(ModifyType const &f)
Modify the open ledger.
Writable ledger view that accumulates state and tx changes.
Definition OpenView.h:59
A wrapper which makes credits unavailable to balances.
static constexpr std::uint64_t kMaxValue
Definition STAmount.h:67
static constexpr int kMaxOffset
Definition STAmount.h:62
std::shared_ptr< STLedgerEntry const > const & ConstRef
std::shared_ptr< STLedgerEntry const > const_pointer
bool pushBack(STPath const &e)
pushBack adds a path to the set.
Definition STPathSet.h:669
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
virtual OpenLedger & getOpenLedger()=0
virtual Logs & getLogs()=0
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
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
TER ter() const
Return the TER for the last JTx.
Definition Env.h:844
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
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
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
Test helper for creating, mutating, and asserting MPT and confidential MPT ledger state.
Definition mpt.h:512
Converts to MPT Issue or STAmount.
xrpl::MPTID const & mpt() const
Match the number of items in the account's owner directory.
Definition owners.h:55
Add a path.
Definition paths.h:47
Set Paths, SendMax on a JTx.
Definition paths.h:23
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
T erase(T... args)
T is_same_v
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 mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
json::Value create(A const &account, A const &dest, STAmount const &sendMax)
Create a check.
auto const kMptDexFlags
Definition mpt.h:47
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
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 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
STPathElement ipe(Asset const &asset)
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 trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:18
PrettyAmount drops(Integer i)
Returns an XRP PrettyAmount, which is trivially convertible to STAmount.
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
BEAST_DEFINE_TESTSUITE_PRIO(AccountDelete, app, xrpl, 2)
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.
TER offerDelete(ApplyView &view, SLE::Ref sle, beast::Journal j)
Delete an offer.
bool isXRP(AccountID const &c)
Definition AccountID.h:84
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
StrandResult< TInAmt, TOutAmt > flow(PaymentSandbox const &baseView, Strand const &strand, std::optional< TInAmt > const &maxIn, TOutAmt const &out, beast::Journal j)
Request out amount from a strand.
Definition StrandFlow.h:101
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
MPTID makeMptID(std::uint32_t const sequence, AccountID const &account)
Definition Indexes.cpp:219
@ TapNone
Definition ApplyView.h:28
constexpr std::uint16_t kMaxTransferFee
The maximum token transfer fee allowed.
Definition Protocol.h:97
@ temBAD_PATH
Definition TER.h:84
@ temBAD_PATH_LOOP
Definition TER.h:85
TERSubset< CanCvtToTER > TER
Definition TER.h:657
AccountID const & xrpAccount()
Compute AccountID from public key.
@ tecPATH_PARTIAL
Definition TER.h:293
@ tecPATH_DRY
Definition TER.h:305
@ tecOBJECT_NOT_FOUND
Definition TER.h:337
@ tecINTERNAL
Definition TER.h:321
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
constexpr std::uint64_t kMaxMpTokenAmount
The maximum amount of MPTokenIssuance.
Definition Protocol.h:297
@ tesSUCCESS
Definition TER.h:253
T stoull(T... args)
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20
void run() override
Runs the suite.
void testLockedMidPathHolder(FeatureBitset features)
void testConsumeOfferOverflow(FeatureBitset features)
void testSelfFundedXRPEndpoint(bool consumeOffer, FeatureBitset features)
void testMPTEndpointRipplingInputOverflow(FeatureBitset features)
void testBookStepInputAboveMaximumAmount(FeatureBitset features)
void testBookStepInputAboveMaximumAmountWithFee(FeatureBitset features)
void testFalseDry(FeatureBitset features)
void testIssuerSourceMPTLoop(FeatureBitset features)
void testSelfPayment1(FeatureBitset features)
void testWithFeats(FeatureBitset features)
void testTransferRate(FeatureBitset features)
void testBookStep(FeatureBitset features)
void testMPTEndpointTransferRateOverflow(FeatureBitset features)
std::vector< jtx::Account > Accounts
static std::vector< SLE::const_pointer > offersOnAccount(jtx::Env &env, jtx::Account account)
void testOfferOwnerMPTCreation(FeatureBitset features)
void testSelfPayment2(FeatureBitset features)
void testEmptyStrand(FeatureBitset features)
void testDirectStep(FeatureBitset features)
void testBookStepMissingIssuance(FeatureBitset features)
void testMaxAndSelfPaymentEdgeCases(FeatureBitset features)
void testSelfPayLowQualityOffer(FeatureBitset features)
static XRPAmount reserve(jtx::Env &env, std::uint32_t count)
void testReExecuteDirectStep(FeatureBitset features)
void testUnfundedOffer(FeatureBitset features)
Represents an XRP, IOU, or MPT quantity This customizes the string conversion and supports XRP conver...
STAmount const & value() const