xrpld
Loading...
Searching...
No Matches
AMM_test.cpp
1#include <test/jtx/AMM.h>
2#include <test/jtx/AMMTest.h>
3#include <test/jtx/CaptureLogs.h>
4#include <test/jtx/Env.h>
5#include <test/jtx/TestHelpers.h>
6#include <test/jtx/amount.h>
7#include <test/jtx/envconfig.h>
8#include <test/jtx/escrow.h>
9#include <test/jtx/fee.h>
10#include <test/jtx/flags.h>
11#include <test/jtx/offer.h>
12#include <test/jtx/paths.h>
13#include <test/jtx/pay.h>
14#include <test/jtx/paychan.h>
15#include <test/jtx/rate.h>
16#include <test/jtx/sendmax.h>
17#include <test/jtx/seq.h>
18#include <test/jtx/sig.h>
19#include <test/jtx/tags.h>
20#include <test/jtx/ter.h>
21#include <test/jtx/trust.h>
22#include <test/jtx/txflags.h>
23
24#include <xrpld/core/Config.h>
25
26#include <xrpl/basics/Number.h>
27#include <xrpl/basics/base_uint.h>
28#include <xrpl/basics/chrono.h>
29#include <xrpl/basics/safe_cast.h>
30#include <xrpl/beast/unit_test/suite.h>
31#include <xrpl/beast/utility/Journal.h>
32#include <xrpl/json/json_value.h>
33#include <xrpl/ledger/ApplyView.h>
34#include <xrpl/ledger/helpers/AMMHelpers.h>
35#include <xrpl/ledger/helpers/AccountRootHelpers.h>
36#include <xrpl/protocol/AMMCore.h>
37#include <xrpl/protocol/AccountID.h>
38#include <xrpl/protocol/AmountConversions.h>
39#include <xrpl/protocol/Feature.h>
40#include <xrpl/protocol/Indexes.h>
41#include <xrpl/protocol/Issue.h>
42#include <xrpl/protocol/LedgerFormats.h>
43#include <xrpl/protocol/Protocol.h>
44#include <xrpl/protocol/Quality.h>
45#include <xrpl/protocol/Rules.h>
46#include <xrpl/protocol/SField.h>
47#include <xrpl/protocol/STAmount.h>
48#include <xrpl/protocol/TER.h>
49#include <xrpl/protocol/TxFlags.h>
50#include <xrpl/protocol/UintTypes.h>
51#include <xrpl/protocol/jss.h>
52#include <xrpl/tx/Transactor.h>
53#include <xrpl/tx/transactors/dex/AMMBid.h>
54
55#include <boost/regex/v5/regex.hpp>
56#include <boost/regex/v5/regex_search.hpp>
57
58#include <array>
59#include <cassert>
60#include <chrono>
61#include <cstdint>
62#include <functional>
63#include <initializer_list>
64#include <memory>
65#include <optional>
66#include <string>
67#include <tuple>
68#include <utility>
69#include <vector>
70
71namespace xrpl::test {
72
77struct AMM_test : public jtx::AMMTest
78{
79 // Use small Number mantissas for the life of this test.
81
82private:
83 static FeatureBitset
85 {
86 // For now, just disable SAV entirely, which locks in the small Number
87 // mantissas
88 return jtx::testableAmendments() - featureSingleAssetVault - featureLendingProtocol -
89 featureMPTokensV2;
90 }
91
92 // Seed from the local testableAmendments() which strips SAV and Lending.
98
99 void
101 {
102 testcase("Instance Create");
103
104 using namespace jtx;
105
106#if NUMBERTODO
107 // XRP to IOU, with featureSingleAssetVault
108 testAMM(
109 [&](AMM& ammAlice, Env&) {
110 BEAST_EXPECT(
111 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0}));
112 },
113 {},
114 0,
115 {},
117#endif
118
119 // XRP to IOU, without featureSingleAssetVault
120 testAMM(
121 [&](AMM& ammAlice, Env&) {
122 BEAST_EXPECT(
123 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0}));
124 },
125 {},
126 0,
127 {},
128 {testableAmendments() - featureSingleAssetVault});
129
130 // IOU to IOU
131 testAMM(
132 [&](AMM& ammAlice, Env&) {
133 BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0}));
134 },
135 {{USD(20'000), BTC(0.5)}});
136
137 // IOU to IOU + transfer fee
138 {
139 Env env{*this};
140 fund(env, gw_, {alice_}, {USD(20'000), BTC(0.5)}, Fund::All);
141 env(rate(gw_, 1.25));
142 env.close();
143 // no transfer fee on create
144 AMM const ammAlice(env, alice_, USD(20'000), BTC(0.5));
145 BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0}));
146 BEAST_EXPECT(expectHolding(env, alice_, USD(0)));
147 BEAST_EXPECT(expectHolding(env, alice_, BTC(0)));
148 }
149
150 // Require authorization is set, account is authorized
151 {
152 Env env{*this};
153 env.fund(XRP(30'000), gw_, alice_);
154 env.close();
155 env(fset(gw_, asfRequireAuth));
156 env(trust(alice_, gw_["USD"](30'000), 0));
157 env(trust(gw_, alice_["USD"](0), tfSetfAuth));
158 env.close();
159 env(pay(gw_, alice_, USD(10'000)));
160 env.close();
161 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'000));
162 }
163
164 // Cleared global freeze
165 {
166 Env env{*this};
167 env.fund(XRP(30'000), gw_, alice_);
168 env.close();
169 env.trust(USD(30'000), alice_);
170 env.close();
171 env(pay(gw_, alice_, USD(10'000)));
172 env.close();
173 env(fset(gw_, asfGlobalFreeze));
174 env.close();
175 AMM const ammAliceFail(env, alice_, XRP(10'000), USD(10'000), Ter(tecFROZEN));
176 env(fclear(gw_, asfGlobalFreeze));
177 env.close();
178 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'000));
179 }
180
181 // Trading fee
182 testAMM(
183 [&](AMM& amm, Env&) {
184 BEAST_EXPECT(amm.expectTradingFee(1'000));
185 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0}));
186 },
187 std::nullopt,
188 1'000);
189
190 // Make sure asset comparison works.
191 BEAST_EXPECT(
192 STIssue(sfAsset, STAmount(XRP(2'000)).asset()) ==
193 STIssue(sfAsset, STAmount(XRP(2'000)).asset()));
194 BEAST_EXPECT(
195 STIssue(sfAsset, STAmount(XRP(2'000)).asset()) !=
196 STIssue(sfAsset, STAmount(USD(2'000)).asset()));
197 }
198
199 void
201 {
202 testcase("Invalid Instance");
203
204 using namespace jtx;
205
206 // Can't have both XRP tokens
207 {
208 Env env{*this};
209 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
210 AMM const ammAlice(env, alice_, XRP(10'000), XRP(10'000), Ter(temBAD_AMM_TOKENS));
211 BEAST_EXPECT(!ammAlice.ammExists());
212 }
213
214 // Can't have both tokens the same IOU
215 {
216 Env env{*this};
217 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
218 AMM const ammAlice(env, alice_, USD(10'000), USD(10'000), Ter(temBAD_AMM_TOKENS));
219 BEAST_EXPECT(!ammAlice.ammExists());
220 }
221
222 // Can't have zero or negative amounts
223 {
224 Env env{*this};
225 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
226 AMM const ammAlice(env, alice_, XRP(0), USD(10'000), Ter(temBAD_AMOUNT));
227 BEAST_EXPECT(!ammAlice.ammExists());
228 AMM const ammAlice1(env, alice_, XRP(10'000), USD(0), Ter(temBAD_AMOUNT));
229 BEAST_EXPECT(!ammAlice1.ammExists());
230 AMM const ammAlice2(env, alice_, XRP(10'000), USD(-10'000), Ter(temBAD_AMOUNT));
231 BEAST_EXPECT(!ammAlice2.ammExists());
232 AMM const ammAlice3(env, alice_, XRP(-10'000), USD(10'000), Ter(temBAD_AMOUNT));
233 BEAST_EXPECT(!ammAlice3.ammExists());
234 }
235
236 // Bad currency
237 {
238 Env env{*this};
239 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
240 AMM const ammAlice(env, alice_, XRP(10'000), BAD(10'000), Ter(temBAD_CURRENCY));
241 BEAST_EXPECT(!ammAlice.ammExists());
242 }
243
244 // Insufficient IOU balance
245 {
246 Env env{*this};
247 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
248 AMM const ammAlice(env, alice_, XRP(10'000), USD(40'000), Ter(tecUNFUNDED_AMM));
249 BEAST_EXPECT(!ammAlice.ammExists());
250 }
251
252 // Insufficient XRP balance
253 {
254 Env env{*this};
255 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
256 AMM const ammAlice(env, alice_, XRP(40'000), USD(10'000), Ter(tecUNFUNDED_AMM));
257 BEAST_EXPECT(!ammAlice.ammExists());
258 }
259
260 // Invalid trading fee
261 {
262 Env env{*this};
263 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
264 AMM const ammAlice(
265 env,
266 alice_,
267 XRP(10'000),
268 USD(10'000),
269 false,
270 65'001,
271 10,
272 std::nullopt,
273 std::nullopt,
274 std::nullopt,
275 Ter(temBAD_FEE));
276 BEAST_EXPECT(!ammAlice.ammExists());
277 }
278
279 // AMM already exists
280 testAMM([&](AMM& ammAlice, Env& env) {
281 AMM const ammCarol(env, carol_, XRP(10'000), USD(10'000), Ter(tecDUPLICATE));
282 });
283
284 // Invalid flags
285 {
286 Env env{*this};
287 fund(env, gw_, {alice_}, {USD(30'000)}, Fund::All);
288 AMM const ammAlice(
289 env,
290 alice_,
291 XRP(10'000),
292 USD(10'000),
293 false,
294 0,
295 10,
296 tfWithdrawAll,
297 std::nullopt,
298 std::nullopt,
300 BEAST_EXPECT(!ammAlice.ammExists());
301 }
302
303 // Invalid Account
304 {
305 Env env{*this};
306 Account const bad("bad");
307 env.memoize(bad);
308 AMM const ammAlice(
309 env,
310 bad,
311 XRP(10'000),
312 USD(10'000),
313 false,
314 0,
315 10,
316 std::nullopt,
317 Seq(1),
318 std::nullopt,
320 BEAST_EXPECT(!ammAlice.ammExists());
321 }
322
323 // Require authorization is set
324 {
325 Env env{*this};
326 env.fund(XRP(30'000), gw_, alice_);
327 env.close();
328 env(fset(gw_, asfRequireAuth));
329 env.close();
330 env(trust(gw_, alice_["USD"](30'000)));
331 env.close();
332 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'000), Ter(tecNO_AUTH));
333 BEAST_EXPECT(!ammAlice.ammExists());
334 }
335
336 // Globally frozen
337 {
338 Env env{*this};
339 env.fund(XRP(30'000), gw_, alice_);
340 env.close();
341 env(fset(gw_, asfGlobalFreeze));
342 env.close();
343 env(trust(gw_, alice_["USD"](30'000)));
344 env.close();
345 for (auto const& account : {alice_, gw_})
346 {
347 AMM const amm(env, account, XRP(10'000), USD(10'000), Ter(tecFROZEN));
348 BEAST_EXPECT(!amm.ammExists());
349 }
350 }
351
352 // Individually frozen
353 {
354 Env env{*this};
355 env.fund(XRP(30'000), gw_, alice_);
356 env.close();
357 env(trust(gw_, alice_["USD"](30'000)));
358 env.close();
359 env(trust(gw_, alice_["USD"](0), tfSetFreeze));
360 env.close();
361 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'000), Ter(tecFROZEN));
362 BEAST_EXPECT(!ammAlice.ammExists());
363 // issuer can create
364 AMM const amm(env, gw_, XRP(10'000), USD(10'000));
365 }
366
367 // Insufficient reserve, XRP/IOU
368 {
369 Env env(*this);
370 auto const startingXrp = XRP(1'000) + reserve(env, 3) + env.current()->fees().base * 4;
371 env.fund(startingXrp, gw_);
372 env.fund(startingXrp, alice_);
373 env.trust(USD(2'000), alice_);
374 env.close();
375 env(pay(gw_, alice_, USD(2'000)));
376 env.close();
377 env(offer(alice_, XRP(101), USD(100)));
378 env(offer(alice_, XRP(102), USD(100)));
379 AMM const ammAlice(env, alice_, XRP(1'000), USD(1'000), Ter(tecUNFUNDED_AMM));
380 }
381
382 // Insufficient reserve, IOU/IOU
383 {
384 Env env(*this);
385 auto const startingXrp = reserve(env, 4) + env.current()->fees().base * 5;
386 env.fund(startingXrp, gw_);
387 env.fund(startingXrp, alice_);
388 env.trust(USD(2'000), alice_);
389 env.trust(EUR(2'000), alice_);
390 env.close();
391 env(pay(gw_, alice_, USD(2'000)));
392 env(pay(gw_, alice_, EUR(2'000)));
393 env.close();
394 env(offer(alice_, EUR(101), USD(100)));
395 env(offer(alice_, EUR(102), USD(100)));
396 AMM const ammAlice(env, alice_, EUR(1'000), USD(1'000), Ter(tecINSUF_RESERVE_LINE));
397 }
398
399 // Insufficient fee
400 {
401 Env env(*this);
402 fund(env, gw_, {alice_}, XRP(2'000), {USD(2'000), EUR(2'000)});
403 AMM const ammAlice(
404 env,
405 alice_,
406 EUR(1'000),
407 USD(1'000),
408 false,
409 0,
410 ammCrtFee(env).drops() - 1,
411 std::nullopt,
412 std::nullopt,
413 std::nullopt,
415 }
416
417 // AMM with LPTokens
418
419 // AMM with one LPToken from another AMM.
420 testAMM([&](AMM& ammAlice, Env& env) {
421 fund(env, gw_, {alice_}, {EUR(10'000)}, Fund::TokenOnly);
422 AMM const ammAMMToken(
423 env,
424 alice_,
425 EUR(10'000),
426 STAmount{ammAlice.lptIssue(), 1'000'000},
428 AMM const ammAMMToken1(
429 env,
430 alice_,
431 STAmount{ammAlice.lptIssue(), 1'000'000},
432 EUR(10'000),
434 });
435
436 // AMM with two LPTokens from other AMMs.
437 testAMM([&](AMM& ammAlice, Env& env) {
438 fund(env, gw_, {alice_}, {EUR(10'000)}, Fund::TokenOnly);
439 AMM const ammAlice1(env, alice_, XRP(10'000), EUR(10'000));
440 auto const token1 = ammAlice.lptIssue();
441 auto const token2 = ammAlice1.lptIssue();
442 AMM const ammAMMTokens(
443 env,
444 alice_,
445 STAmount{token1, 1'000'000},
446 STAmount{token2, 1'000'000},
448 });
449
450 // Issuer has DefaultRipple disabled
451 {
452 Env env(*this);
453 env.fund(XRP(30'000), gw_);
454 env(fclear(gw_, asfDefaultRipple));
455 AMM const ammGw(env, gw_, XRP(10'000), USD(10'000), Ter(terNO_RIPPLE));
456 env.fund(XRP(30'000), alice_);
457 env.trust(USD(30'000), alice_);
458 env(pay(gw_, alice_, USD(30'000)));
459 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'000), Ter(terNO_RIPPLE));
460 Account const gw1("gw1");
461 env.fund(XRP(30'000), gw1);
462 env(fclear(gw1, asfDefaultRipple));
463 env.trust(USD(30'000), gw1);
464 env(pay(gw_, gw1, USD(30'000)));
465 auto const usD1 = gw1["USD"];
466 AMM const ammGwGw1(env, gw_, USD(10'000), usD1(10'000), Ter(terNO_RIPPLE));
467 env.trust(usD1(30'000), alice_);
468 env(pay(gw1, alice_, usD1(30'000)));
469 AMM const ammAlice1(env, alice_, USD(10'000), usD1(10'000), Ter(terNO_RIPPLE));
470 }
471 }
472
473 void
475 {
476 testcase("Invalid Deposit");
477
478 using namespace jtx;
479
480 testAMM([&](AMM& ammAlice, Env& env) {
481 // Invalid flags
482 ammAlice.deposit(alice_, 1'000'000, std::nullopt, tfWithdrawAll, Ter(temINVALID_FLAG));
483
484 // Invalid options
491 std::optional<std::uint16_t>>> const invalidOptions = {
492 // flags, tokens, asset1In, asset2in, EPrice, tfee
493 {tfLPToken, 1'000, std::nullopt, USD(100), std::nullopt, std::nullopt},
494 {tfLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, std::nullopt},
495 {tfLPToken, 1'000, std::nullopt, std::nullopt, STAmount{USD, 1, -1}, std::nullopt},
496 {
497 tfLPToken,
498 std::nullopt,
499 USD(100),
500 std::nullopt,
501 STAmount{USD, 1, -1},
502 std::nullopt,
503 },
504 {tfLPToken, 1'000, XRP(100), std::nullopt, STAmount{USD, 1, -1}, std::nullopt},
505 {tfLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, 1'000},
506 {tfSingleAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
507 {tfSingleAsset, std::nullopt, std::nullopt, USD(100), std::nullopt, std::nullopt},
508 {
509 tfSingleAsset,
510 std::nullopt,
511 std::nullopt,
512 std::nullopt,
513 STAmount{USD, 1, -1},
514 std::nullopt,
515 },
516 {tfSingleAsset, std::nullopt, USD(100), std::nullopt, std::nullopt, 1'000},
517 {tfTwoAsset, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
518 {tfTwoAsset, std::nullopt, XRP(100), USD(100), STAmount{USD, 1, -1}, std::nullopt},
519 {tfTwoAsset, std::nullopt, XRP(100), std::nullopt, std::nullopt, std::nullopt},
520 {tfTwoAsset, std::nullopt, XRP(100), USD(100), std::nullopt, 1'000},
521 {
522 tfTwoAsset,
523 std::nullopt,
524 std::nullopt,
525 USD(100),
526 STAmount{USD, 1, -1},
527 std::nullopt,
528 },
529 {tfOneAssetLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
530 {tfOneAssetLPToken, std::nullopt, XRP(100), USD(100), std::nullopt, std::nullopt},
531 {
532 tfOneAssetLPToken,
533 std::nullopt,
534 XRP(100),
535 std::nullopt,
536 STAmount{USD, 1, -1},
537 std::nullopt,
538 },
539 {tfOneAssetLPToken, 1'000, XRP(100), std::nullopt, std::nullopt, 1'000},
540 {tfLimitLPToken, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
541 {tfLimitLPToken, 1'000, USD(100), std::nullopt, std::nullopt, std::nullopt},
542 {tfLimitLPToken, std::nullopt, USD(100), XRP(100), std::nullopt, std::nullopt},
543 {tfLimitLPToken, std::nullopt, XRP(100), std::nullopt, STAmount{USD, 1, -1}, 1'000},
544 {tfTwoAssetIfEmpty, std::nullopt, std::nullopt, std::nullopt, std::nullopt, 1'000},
545 {tfTwoAssetIfEmpty, 1'000, std::nullopt, std::nullopt, std::nullopt, std::nullopt},
546 {
547 tfTwoAssetIfEmpty,
548 std::nullopt,
549 XRP(100),
550 USD(100),
551 STAmount{USD, 1, -1},
552 std::nullopt,
553 },
554 {
555 tfTwoAssetIfEmpty | tfLPToken,
556 std::nullopt,
557 XRP(100),
558 USD(100),
559 STAmount{USD, 1, -1},
560 std::nullopt,
561 },
562 };
563 for (auto const& it : invalidOptions)
564 {
565 ammAlice.deposit(
566 alice_,
567 std::get<1>(it),
568 std::get<2>(it),
569 std::get<3>(it),
570 std::get<4>(it),
571 std::get<0>(it),
572 std::nullopt,
573 std::nullopt,
574 std::get<5>(it),
576 }
577
578 {
579 // bad preflight1
581 jv[jss::Account] = alice_.human();
582 jv[jss::TransactionType] = jss::AMMDeposit;
583 jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None);
584 jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::Values::None);
585 jv[jss::Fee] = "-1";
586 env(jv, Ter(temBAD_FEE));
587 }
588
589 // Invalid tokens
590 ammAlice.deposit(alice_, 0, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
591 ammAlice.deposit(
592 alice_, IOUAmount{-1}, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
593
594 {
596 jv[jss::Account] = alice_.human();
597 jv[jss::TransactionType] = jss::AMMDeposit;
598 jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::Values::None);
599 jv[jss::Asset2] = STIssue(sfAsset, USD).getJson(JsonOptions::Values::None);
600 jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::Values::None);
601 jv[jss::Flags] = tfLPToken;
602 env(jv, Ter(temBAD_AMM_TOKENS));
603 }
604
605 // Invalid trading fee
606 ammAlice.deposit(
607 carol_,
608 std::nullopt,
609 XRP(200),
610 USD(200),
611 std::nullopt,
612 tfTwoAssetIfEmpty,
613 std::nullopt,
614 std::nullopt,
615 10'000,
616 Ter(temBAD_FEE));
617
618 // Invalid tokens - bogus currency
619 {
620 auto const iss1 = Issue{Currency(0xabc), gw_.id()};
621 auto const iss2 = Issue{Currency(0xdef), gw_.id()};
622 ammAlice.deposit(
623 alice_,
624 1'000,
625 std::nullopt,
626 std::nullopt,
627 std::nullopt,
628 std::nullopt,
629 {{iss1, iss2}},
630 std::nullopt,
631 std::nullopt,
632 Ter(terNO_AMM));
633 }
634
635 // Depositing mismatched token, invalid Asset1In.issue
636 ammAlice.deposit(
637 alice_, GBP(100), std::nullopt, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
638
639 // Depositing mismatched token, invalid Asset2In.issue
640 ammAlice.deposit(
641 alice_, USD(100), GBP(100), std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
642
643 // Depositing mismatched token, Asset1In.issue == Asset2In.issue
644 ammAlice.deposit(
645 alice_, USD(100), USD(100), std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
646
647 // Invalid amount value
648 ammAlice.deposit(
649 alice_, USD(0), std::nullopt, std::nullopt, std::nullopt, Ter(temBAD_AMOUNT));
650 ammAlice.deposit(
651 alice_, USD(-1'000), std::nullopt, std::nullopt, std::nullopt, Ter(temBAD_AMOUNT));
652 ammAlice.deposit(
653 alice_, USD(10), std::nullopt, USD(-1), std::nullopt, Ter(temBAD_AMOUNT));
654
655 // Bad currency
656 ammAlice.deposit(
657 alice_, BAD(100), std::nullopt, std::nullopt, std::nullopt, Ter(temBAD_CURRENCY));
658
659 // Invalid Account
660 Account const bad("bad");
661 env.memoize(bad);
662 ammAlice.deposit(
663 bad,
664 1'000'000,
665 std::nullopt,
666 std::nullopt,
667 std::nullopt,
668 std::nullopt,
669 std::nullopt,
670 Seq(1),
671 std::nullopt,
673
674 // Invalid AMM
675 ammAlice.deposit(
676 alice_,
677 1'000,
678 std::nullopt,
679 std::nullopt,
680 std::nullopt,
681 std::nullopt,
682 {{USD, GBP}},
683 std::nullopt,
684 std::nullopt,
685 Ter(terNO_AMM));
686
687 // Single deposit: 100000 tokens worth of USD
688 // Amount to deposit exceeds Max
689 ammAlice.deposit(
690 carol_,
691 100'000,
692 USD(200),
693 std::nullopt,
694 std::nullopt,
695 std::nullopt,
696 std::nullopt,
697 std::nullopt,
698 std::nullopt,
700
701 // Single deposit: 100000 tokens worth of XRP
702 // Amount to deposit exceeds Max
703 ammAlice.deposit(
704 carol_,
705 100'000,
706 XRP(200),
707 std::nullopt,
708 std::nullopt,
709 std::nullopt,
710 std::nullopt,
711 std::nullopt,
712 std::nullopt,
714
715 // Deposit amount is invalid
716 // Calculated amount to deposit is 98,000,000
717 ammAlice.deposit(
718 alice_,
719 USD(0),
720 std::nullopt,
721 STAmount{USD, 1, -1},
722 std::nullopt,
724 // Calculated amount is 0
725 ammAlice.deposit(
726 alice_,
727 USD(0),
728 std::nullopt,
729 STAmount{USD, 2'000, -6},
730 std::nullopt,
732
733 // Deposit non-empty AMM
734 ammAlice.deposit(
735 carol_, XRP(100), USD(100), std::nullopt, tfTwoAssetIfEmpty, Ter(tecAMM_NOT_EMPTY));
736 });
737
738 // Tiny deposit
739 testAMM(
740 [&](AMM& ammAlice, Env& env) {
741 auto const enabledV13 = env.current()->rules().enabled(fixAMMv1_3);
742 auto const err = !enabledV13 ? Ter(temBAD_AMOUNT) : Ter(tesSUCCESS);
743 // Pre-amendment XRP deposit side is rounded to 0
744 // and deposit fails.
745 // Post-amendment XRP deposit side is rounded to 1
746 // and deposit succeeds.
747 ammAlice.deposit(carol_, IOUAmount{1, -4}, std::nullopt, std::nullopt, err);
748 // Pre/post-amendment LPTokens is rounded to 0 and deposit
749 // fails with tecAMM_INVALID_TOKENS.
750 ammAlice.deposit(
751 carol_,
752 STAmount{USD, 1, -12},
753 std::nullopt,
754 std::nullopt,
755 std::nullopt,
757 },
758 std::nullopt,
759 0,
760 std::nullopt,
761 {features, features - fixAMMv1_3});
762
763 // Invalid AMM
764 testAMM([&](AMM& ammAlice, Env& env) {
765 ammAlice.withdrawAll(alice_);
766 ammAlice.deposit(alice_, 10'000, std::nullopt, std::nullopt, Ter(terNO_AMM));
767 });
768
769 // Globally frozen asset
770 testAMM(
771 [&](AMM& ammAlice, Env& env) {
772 env(fset(gw_, asfGlobalFreeze));
773 auto const freezeBlocksAll =
774 features[featureAMMClawback] || features[fixCleanup3_3_0];
775 if (!freezeBlocksAll)
776 {
777 // If the issuer set global freeze, the holder still can
778 // deposit the other non-frozen token when neither
779 // AMMClawback nor fixCleanup3_3_0 is enabled.
780 ammAlice.deposit(carol_, XRP(100));
781 }
782 else
783 {
784 // If the issuer set global freeze, the holder cannot
785 // deposit the other non-frozen token.
786 ammAlice.deposit(
787 carol_, XRP(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
788 }
789 for (auto const& account : {carol_, gw_})
790 {
791 ammAlice.deposit(
792 account,
793 USD(100),
794 std::nullopt,
795 std::nullopt,
796 std::nullopt,
797 Ter(tecFROZEN));
798 ammAlice.deposit(
799 account, 1'000'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
800 ammAlice.deposit(
801 account, XRP(100), USD(100), std::nullopt, std::nullopt, Ter(tecFROZEN));
802 }
803 },
804 std::nullopt,
805 0,
806 std::nullopt,
807 {features});
808
809 // Individually frozen (AMM) account
810 testAMM(
811 [&](AMM& ammAlice, Env& env) {
812 env(trust(gw_, carol_["USD"](0), tfSetFreeze));
813 env.close();
814 auto const freezeBlocksAll =
815 features[featureAMMClawback] || features[fixCleanup3_3_0];
816 if (!freezeBlocksAll)
817 {
818 // Can deposit non-frozen token if neither AMMClawback
819 // nor fixCleanup3_3_0 is enabled
820 ammAlice.deposit(carol_, XRP(100));
821 }
822 else
823 {
824 // Cannot deposit non-frozen token if the other token is
825 // frozen
826 ammAlice.deposit(
827 carol_, XRP(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
828 }
829
830 ammAlice.deposit(carol_, 1'000'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
831 ammAlice.deposit(
832 carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
833 env(trust(gw_, carol_["USD"](0), tfClearFreeze));
834 // Individually frozen AMM
835 env(trust(
836 gw_,
837 STAmount{Issue{gw_["USD"].currency, ammAlice.ammAccount()}, 0},
838 tfSetFreeze));
839 env.close();
840 // Post-fixCleanup3_3_0: checkDepositFreeze checks both pool
841 // assets against the AMM account, so depositing the
842 // non-frozen token is also blocked.
843 if (!features[fixCleanup3_3_0])
844 {
845 ammAlice.deposit(carol_, XRP(100));
846 }
847 else
848 {
849 ammAlice.deposit(
850 carol_, XRP(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
851 }
852 ammAlice.deposit(carol_, 1'000'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
853 ammAlice.deposit(
854 carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
855 },
856 std::nullopt,
857 0,
858 std::nullopt,
859 {features});
860
861 // Individually frozen (AMM) account with IOU/IOU AMM
862 testAMM(
863 [&](AMM& ammAlice, Env& env) {
864 env(trust(gw_, carol_["USD"](0), tfSetFreeze));
865 env(trust(gw_, carol_["BTC"](0), tfSetFreeze));
866 env.close();
867 ammAlice.deposit(carol_, 1'000'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
868 ammAlice.deposit(
869 carol_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecFROZEN));
870 env(trust(gw_, carol_["USD"](0), tfClearFreeze));
871 // Individually frozen AMM
872 env(trust(
873 gw_,
874 STAmount{Issue{gw_["USD"].currency, ammAlice.ammAccount()}, 0},
875 tfSetFreeze));
876 env.close();
877 // Cannot deposit non-frozen token
878 ammAlice.deposit(carol_, 1'000'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
879 ammAlice.deposit(
880 carol_, USD(100), BTC(0.01), std::nullopt, std::nullopt, Ter(tecFROZEN));
881 },
882 {{USD(20'000), BTC(0.5)}});
883
884 // Deposit unauthorized token.
885 {
886 Env env(*this, features);
887 env.fund(XRP(1000), gw_, alice_, bob_);
888 env(fset(gw_, asfRequireAuth));
889 env.close();
890 env(trust(gw_, alice_["USD"](100)), Txflags(tfSetfAuth));
891 env(trust(alice_, gw_["USD"](20)));
892 env.close();
893 env(pay(gw_, alice_, gw_["USD"](10)));
894 env.close();
895 env(trust(gw_, bob_["USD"](100)));
896 env.close();
897
898 AMM amm(env, alice_, XRP(10), gw_["USD"](10), Ter(tesSUCCESS));
899 env.close();
900
901 if (features[featureAMMClawback] || features[fixCleanup3_3_0])
902 {
903 // bob_ can not deposit XRP because he's not authorized to
904 // hold the paired token gw_["USD"].
905 amm.deposit(
906 bob_, XRP(10), std::nullopt, std::nullopt, std::nullopt, Ter(tecNO_AUTH));
907 }
908 else
909 {
910 amm.deposit(
911 bob_, XRP(10), std::nullopt, std::nullopt, std::nullopt, Ter(tesSUCCESS));
912 }
913 }
914
915 // Insufficient XRP balance
916 testAMM([&](AMM& ammAlice, Env& env) {
917 env.fund(XRP(1'000), bob_);
918 env.close();
919 // Adds LPT trustline
920 ammAlice.deposit(bob_, XRP(10));
921 ammAlice.deposit(
922 bob_, XRP(1'000), std::nullopt, std::nullopt, std::nullopt, Ter(tecUNFUNDED_AMM));
923 });
924
925 // Insufficient USD balance
926 testAMM([&](AMM& ammAlice, Env& env) {
927 fund(env, gw_, {bob_}, {USD(1'000)}, Fund::Acct);
928 env.close();
929 ammAlice.deposit(
930 bob_, USD(1'001), std::nullopt, std::nullopt, std::nullopt, Ter(tecUNFUNDED_AMM));
931 });
932
933 // Insufficient USD balance by tokens
934 testAMM([&](AMM& ammAlice, Env& env) {
935 fund(env, gw_, {bob_}, {USD(1'000)}, Fund::Acct);
936 env.close();
937 ammAlice.deposit(
938 bob_,
939 10'000'000,
940 std::nullopt,
941 std::nullopt,
942 std::nullopt,
943 std::nullopt,
944 std::nullopt,
945 std::nullopt,
946 std::nullopt,
948 });
949
950 // Insufficient XRP balance by tokens
951 testAMM([&](AMM& ammAlice, Env& env) {
952 env.fund(XRP(1'000), bob_);
953 env.trust(USD(100'000), bob_);
954 env.close();
955 env(pay(gw_, bob_, USD(90'000)));
956 env.close();
957 ammAlice.deposit(
958 bob_,
959 10'000'000,
960 std::nullopt,
961 std::nullopt,
962 std::nullopt,
963 std::nullopt,
964 std::nullopt,
965 std::nullopt,
966 std::nullopt,
968 });
969
970 // Insufficient reserve, XRP/IOU
971 {
972 Env env(*this);
973 auto const startingXrp = reserve(env, 4) + env.current()->fees().base * 4;
974 env.fund(XRP(10'000), gw_);
975 env.fund(XRP(10'000), alice_);
976 env.fund(startingXrp, carol_);
977 env.trust(USD(2'000), alice_);
978 env.trust(USD(2'000), carol_);
979 env.close();
980 env(pay(gw_, alice_, USD(2'000)));
981 env(pay(gw_, carol_, USD(2'000)));
982 env.close();
983 env(offer(carol_, XRP(100), USD(101)));
984 env(offer(carol_, XRP(100), USD(102)));
985 AMM ammAlice(env, alice_, XRP(1'000), USD(1'000));
986 ammAlice.deposit(
987 carol_,
988 XRP(100),
989 std::nullopt,
990 std::nullopt,
991 std::nullopt,
993
994 env(offer(carol_, XRP(100), USD(103)));
995 ammAlice.deposit(
996 carol_,
997 USD(100),
998 std::nullopt,
999 std::nullopt,
1000 std::nullopt,
1002 }
1003
1004 // Insufficient reserve, IOU/IOU
1005 {
1006 Env env(*this);
1007 auto const startingXrp = reserve(env, 4) + env.current()->fees().base * 4;
1008 env.fund(XRP(10'000), gw_);
1009 env.fund(XRP(10'000), alice_);
1010 env.fund(startingXrp, carol_);
1011 env.trust(USD(2'000), alice_);
1012 env.trust(EUR(2'000), alice_);
1013 env.trust(USD(2'000), carol_);
1014 env.trust(EUR(2'000), carol_);
1015 env.close();
1016 env(pay(gw_, alice_, USD(2'000)));
1017 env(pay(gw_, alice_, EUR(2'000)));
1018 env(pay(gw_, carol_, USD(2'000)));
1019 env(pay(gw_, carol_, EUR(2'000)));
1020 env.close();
1021 env(offer(carol_, XRP(100), USD(101)));
1022 env(offer(carol_, XRP(100), USD(102)));
1023 AMM ammAlice(env, alice_, XRP(1'000), USD(1'000));
1024 ammAlice.deposit(
1025 carol_,
1026 XRP(100),
1027 std::nullopt,
1028 std::nullopt,
1029 std::nullopt,
1031 }
1032
1033 // Invalid min
1034 testAMM([&](AMM& ammAlice, Env& env) {
1035 // min tokens can't be <= zero
1036 ammAlice.deposit(carol_, 0, XRP(100), tfSingleAsset, Ter(temBAD_AMM_TOKENS));
1037 ammAlice.deposit(carol_, -1, XRP(100), tfSingleAsset, Ter(temBAD_AMM_TOKENS));
1038 ammAlice.deposit(
1039 carol_,
1040 0,
1041 XRP(100),
1042 USD(100),
1043 std::nullopt,
1044 tfTwoAsset,
1045 std::nullopt,
1046 std::nullopt,
1047 std::nullopt,
1049 // min amounts can't be <= zero
1050 ammAlice.deposit(
1051 carol_,
1052 1'000,
1053 XRP(0),
1054 USD(100),
1055 std::nullopt,
1056 tfTwoAsset,
1057 std::nullopt,
1058 std::nullopt,
1059 std::nullopt,
1061 ammAlice.deposit(
1062 carol_,
1063 1'000,
1064 XRP(100),
1065 USD(-1),
1066 std::nullopt,
1067 tfTwoAsset,
1068 std::nullopt,
1069 std::nullopt,
1070 std::nullopt,
1072 // min amount bad currency
1073 ammAlice.deposit(
1074 carol_,
1075 1'000,
1076 XRP(100),
1077 BAD(100),
1078 std::nullopt,
1079 tfTwoAsset,
1080 std::nullopt,
1081 std::nullopt,
1082 std::nullopt,
1084 // min amount bad token pair
1085 ammAlice.deposit(
1086 carol_,
1087 1'000,
1088 XRP(100),
1089 XRP(100),
1090 std::nullopt,
1091 tfTwoAsset,
1092 std::nullopt,
1093 std::nullopt,
1094 std::nullopt,
1096 ammAlice.deposit(
1097 carol_,
1098 1'000,
1099 XRP(100),
1100 GBP(100),
1101 std::nullopt,
1102 tfTwoAsset,
1103 std::nullopt,
1104 std::nullopt,
1105 std::nullopt,
1107 });
1108
1109 // Min deposit
1110 testAMM([&](AMM& ammAlice, Env& env) {
1111 // Equal deposit by tokens
1112 ammAlice.deposit(
1113 carol_,
1114 1'000'000,
1115 XRP(1'000),
1116 USD(1'001),
1117 std::nullopt,
1118 tfLPToken,
1119 std::nullopt,
1120 std::nullopt,
1121 std::nullopt,
1123 ammAlice.deposit(
1124 carol_,
1125 1'000'000,
1126 XRP(1'001),
1127 USD(1'000),
1128 std::nullopt,
1129 tfLPToken,
1130 std::nullopt,
1131 std::nullopt,
1132 std::nullopt,
1134 // Equal deposit by asset
1135 ammAlice.deposit(
1136 carol_,
1137 100'001,
1138 XRP(100),
1139 USD(100),
1140 std::nullopt,
1141 tfTwoAsset,
1142 std::nullopt,
1143 std::nullopt,
1144 std::nullopt,
1146 // Single deposit by asset
1147 ammAlice.deposit(
1148 carol_,
1149 488'090,
1150 XRP(1'000),
1151 std::nullopt,
1152 std::nullopt,
1153 tfSingleAsset,
1154 std::nullopt,
1155 std::nullopt,
1156 std::nullopt,
1158 });
1159
1160 // Equal deposit, tokens rounded to 0
1161 testAMM([&](AMM& amm, Env& env) {
1162 amm.deposit(DepositArg{.tokens = IOUAmount{1, -12}, .err = Ter(tecAMM_INVALID_TOKENS)});
1163 });
1164
1165 // Equal deposit limit, tokens rounded to 0
1166 testAMM(
1167 [&](AMM& amm, Env& env) {
1168 amm.deposit(
1169 DepositArg{
1170 .asset1In = STAmount{USD, 1, -15},
1171 .asset2In = XRPAmount{1},
1172 .err = Ter(tecAMM_INVALID_TOKENS),
1173 });
1174 },
1175 {.pool = {{USD(1'000'000), XRP(1'000'000)}}, .features = {features - fixAMMv1_3}});
1176 testAMM([&](AMM& amm, Env& env) {
1177 amm.deposit(
1178 DepositArg{
1179 .asset1In = STAmount{USD, 1, -15},
1180 .asset2In = XRPAmount{1},
1181 .err = Ter(tecAMM_INVALID_TOKENS),
1182 });
1183 });
1184
1185 // Single deposit by asset, tokens rounded to 0
1186 testAMM([&](AMM& amm, Env& env) {
1187 amm.deposit(
1188 DepositArg{.asset1In = STAmount{USD, 1, -15}, .err = Ter(tecAMM_INVALID_TOKENS)});
1189 });
1190
1191 // Single deposit by tokens, tokens rounded to 0
1192 testAMM([&](AMM& amm, Env& env) {
1193 amm.deposit(
1194 DepositArg{
1195 .tokens = IOUAmount{1, -10},
1196 .asset1In = STAmount{USD, 1, -15},
1197 .err = Ter(tecAMM_INVALID_TOKENS),
1198 });
1199 });
1200
1201 // Single deposit with EPrice, tokens rounded to 0
1202 testAMM([&](AMM& amm, Env& env) {
1203 amm.deposit(
1204 DepositArg{
1205 .asset1In = STAmount{USD, 1, -15},
1206 .maxEP = STAmount{USD, 1, -1},
1207 .err = Ter(tecAMM_INVALID_TOKENS),
1208 });
1209 });
1210 }
1211
1212 void
1214 {
1215 testcase("Deposit");
1216
1217 auto const all = testableAmendments();
1218 using namespace jtx;
1219
1220 // Equal deposit: 1000000 tokens, 10% of the current pool
1221 testAMM([&](AMM& ammAlice, Env& env) {
1222 auto const baseFee = env.current()->fees().base;
1223 ammAlice.deposit(carol_, 1'000'000);
1224 BEAST_EXPECT(
1225 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1226 // 30,000 less deposited 1,000
1227 BEAST_EXPECT(expectHolding(env, carol_, USD(29'000)));
1228 // 30,000 less deposited 1,000 and 10 drops tx fee
1229 BEAST_EXPECT(expectLedgerEntryRoot(env, carol_, XRPAmount{29'000'000'000 - baseFee}));
1230 });
1231
1232 // equal asset deposit: unit test to exercise the rounding-down of
1233 // LPTokens in the AMMHelpers.cpp: adjustLPTokens calculations
1234 // The LPTokens need to have 16 significant digits and a fractional part
1235 for (Number const& deltaLPTokens :
1236 {Number{UINT64_C(100000'0000000009), -10}, Number{UINT64_C(100000'0000000001), -10}})
1237 {
1238 testAMM([&](AMM& ammAlice, Env& env) {
1239 // initial LPToken balance
1240 IOUAmount const initLPToken = ammAlice.getLPTokensBalance();
1241 IOUAmount const newLPTokens{deltaLPTokens};
1242
1243 // carol_ performs a two-asset deposit
1244 ammAlice.deposit(DepositArg{.account = carol_, .tokens = newLPTokens});
1245
1246 IOUAmount const finalLPToken = ammAlice.getLPTokensBalance();
1247
1248 // Change in behavior due to rounding down of LPTokens:
1249 // there is a decrease in the observed return of LPTokens --
1250 // Inputs Number{UINT64_C(100000'0000000001), -10} and
1251 // Number{UINT64_C(100000'0000000009), -10} are both rounded
1252 // down to 1e5
1253 BEAST_EXPECT((finalLPToken - initLPToken == IOUAmount{1, 5}));
1254 BEAST_EXPECT(finalLPToken - initLPToken < deltaLPTokens);
1255
1256 // fraction of newLPTokens/(existing LPToken balance). The
1257 // existing LPToken balance is 1e7
1258 Number const fr = deltaLPTokens / 1e7;
1259
1260 // The below equations are based on Equation 1, 2 from XLS-30d
1261 // specification, Section: 2.3.1.2
1262 Number const deltaXRP = fr * 1e10;
1263 Number const deltaUSD = fr * 1e4;
1264
1265 STAmount const depositUSD = STAmount{USD, deltaUSD};
1266
1267 STAmount const depositXRP = STAmount{XRP, deltaXRP};
1268
1269 // initial LPTokens (1e7) + newLPTokens
1270 BEAST_EXPECT(ammAlice.expectBalances(
1271 XRP(10'000) + depositXRP,
1272 USD(10'000) + depositUSD,
1273 IOUAmount{1, 7} + newLPTokens));
1274
1275 // 30,000 less deposited depositUSD
1276 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000) - depositUSD));
1277 // 30,000 less deposited depositXRP and 10 drops tx fee
1278 BEAST_EXPECT(
1279 expectLedgerEntryRoot(env, carol_, XRP(30'000) - depositXRP - txFee(env, 1)));
1280 });
1281 }
1282
1283 // Equal limit deposit: deposit USD100 and XRP proportionally
1284 // to the pool composition not to exceed 100XRP. If the amount
1285 // exceeds 100XRP then deposit 100XRP and USD proportionally
1286 // to the pool composition not to exceed 100USD. Fail if exceeded.
1287 // Deposit 100USD/100XRP
1288 testAMM([&](AMM& ammAlice, Env&) {
1289 ammAlice.deposit(carol_, USD(100), XRP(100));
1290 BEAST_EXPECT(
1291 ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0}));
1292 });
1293
1294 // Equal limit deposit.
1295 // Try to deposit 200USD/100XRP. Is truncated to 100USD/100XRP.
1296 testAMM([&](AMM& ammAlice, Env&) {
1297 ammAlice.deposit(carol_, USD(200), XRP(100));
1298 BEAST_EXPECT(
1299 ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0}));
1300 });
1301 // Try to deposit 100USD/200XRP. Is truncated to 100USD/100XRP.
1302 testAMM([&](AMM& ammAlice, Env&) {
1303 ammAlice.deposit(carol_, USD(100), XRP(200));
1304 BEAST_EXPECT(
1305 ammAlice.expectBalances(XRP(10'100), USD(10'100), IOUAmount{10'100'000, 0}));
1306 });
1307
1308 // Single deposit: 1000 USD
1309 testAMM([&](AMM& ammAlice, Env&) {
1310 ammAlice.deposit(carol_, USD(1'000));
1311 BEAST_EXPECT(ammAlice.expectBalances(
1312 XRP(10'000),
1313 STAmount{USD, UINT64_C(10'999'99999999999), -11},
1314 IOUAmount{10'488'088'48170151, -8}));
1315 });
1316
1317 // Single deposit: 1000 XRP
1318 testAMM([&](AMM& ammAlice, Env&) {
1319 ammAlice.deposit(carol_, XRP(1'000));
1320 BEAST_EXPECT(ammAlice.expectBalances(
1321 XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8}));
1322 });
1323
1324 // Single deposit: 100000 tokens worth of USD
1325 testAMM([&](AMM& ammAlice, Env&) {
1326 ammAlice.deposit(carol_, 100000, USD(205));
1327 BEAST_EXPECT(
1328 ammAlice.expectBalances(XRP(10'000), USD(10'201), IOUAmount{10'100'000, 0}));
1329 });
1330
1331 // Single deposit: 100000 tokens worth of XRP
1332 testAMM([&](AMM& ammAlice, Env& env) {
1333 ammAlice.deposit(carol_, 100'000, XRP(205));
1334 BEAST_EXPECT(
1335 ammAlice.expectBalances(XRP(10'201), USD(10'000), IOUAmount{10'100'000, 0}));
1336 });
1337
1338 // Single deposit with EP not exceeding specified:
1339 // 100USD with EP not to exceed 0.1 (AssetIn/TokensOut)
1340 testAMM([&](AMM& ammAlice, Env&) {
1341 ammAlice.deposit(carol_, USD(1'000), std::nullopt, STAmount{USD, 1, -1});
1342 BEAST_EXPECT(ammAlice.expectBalances(
1343 XRP(10'000),
1344 STAmount{USD, UINT64_C(10'999'99999999999), -11},
1345 IOUAmount{10'488'088'48170151, -8}));
1346 });
1347
1348 // Single deposit with EP not exceeding specified:
1349 // 100USD with EP not to exceed 0.002004 (AssetIn/TokensOut)
1350 testAMM([&](AMM& ammAlice, Env&) {
1351 ammAlice.deposit(carol_, USD(100), std::nullopt, STAmount{USD, 2004, -6});
1352 BEAST_EXPECT(ammAlice.expectBalances(
1353 XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0}));
1354 });
1355
1356 // Single deposit with EP not exceeding specified:
1357 // 0USD with EP not to exceed 0.002004 (AssetIn/TokensOut)
1358 testAMM([&](AMM& ammAlice, Env&) {
1359 ammAlice.deposit(carol_, USD(0), std::nullopt, STAmount{USD, 2004, -6});
1360 BEAST_EXPECT(ammAlice.expectBalances(
1361 XRP(10'000), STAmount{USD, 10'080'16, -2}, IOUAmount{10'040'000, 0}));
1362 });
1363
1364 // IOU to IOU + transfer fee
1365 {
1366 Env env{*this};
1367 fund(env, gw_, {alice_}, {USD(20'000), BTC(0.5)}, Fund::All);
1368 env(rate(gw_, 1.25));
1369 env.close();
1370 AMM ammAlice(env, alice_, USD(20'000), BTC(0.5));
1371 BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0}));
1372 BEAST_EXPECT(expectHolding(env, alice_, USD(0)));
1373 BEAST_EXPECT(expectHolding(env, alice_, BTC(0)));
1374 fund(env, gw_, {carol_}, {USD(2'000), BTC(0.05)}, Fund::Acct);
1375 // no transfer fee on deposit
1376 ammAlice.deposit(carol_, 10);
1377 BEAST_EXPECT(ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0}));
1378 BEAST_EXPECT(expectHolding(env, carol_, USD(0)));
1379 BEAST_EXPECT(expectHolding(env, carol_, BTC(0)));
1380 }
1381
1382 // Tiny deposits
1383 testAMM([&](AMM& ammAlice, Env&) {
1384 ammAlice.deposit(carol_, IOUAmount{1, -3});
1385 BEAST_EXPECT(ammAlice.expectBalances(
1386 XRPAmount{10'000'000'001},
1387 STAmount{USD, UINT64_C(10'000'000001), -6},
1388 IOUAmount{10'000'000'001, -3}));
1389 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{1, -3}));
1390 });
1391 testAMM([&](AMM& ammAlice, Env&) {
1392 ammAlice.deposit(carol_, XRPAmount{1});
1393 BEAST_EXPECT(ammAlice.expectBalances(
1394 XRPAmount{10'000'000'001}, USD(10'000), IOUAmount{1'000'000'000049999, -8}));
1395 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{49999, -8}));
1396 });
1397 testAMM([&](AMM& ammAlice, Env&) {
1398 ammAlice.deposit(carol_, STAmount{USD, 1, -10});
1399 BEAST_EXPECT(ammAlice.expectBalances(
1400 XRP(10'000),
1401 STAmount{USD, UINT64_C(10'000'00000000008), -11},
1402 IOUAmount{10'000'000'00000004, -8}));
1403 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{4, -8}));
1404 });
1405
1406 // Issuer create/deposit
1407 for (auto const& feat : {all, all - fixAMMv1_3})
1408 {
1409 Env env(*this, feat);
1410 env.fund(XRP(30000), gw_);
1411 AMM ammGw(env, gw_, XRP(10'000), USD(10'000));
1412 BEAST_EXPECT(ammGw.expectBalances(XRP(10'000), USD(10'000), ammGw.tokens()));
1413 ammGw.deposit(gw_, 1'000'000);
1414 BEAST_EXPECT(ammGw.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000}));
1415 ammGw.deposit(gw_, USD(1'000));
1416 BEAST_EXPECT(ammGw.expectBalances(
1417 XRP(11'000),
1418 STAmount{USD, UINT64_C(11'999'99999999998), -11},
1419 IOUAmount{11'489'125'29307605, -8}));
1420 }
1421
1422 // Issuer deposit
1423 testAMM([&](AMM& ammAlice, Env& env) {
1424 ammAlice.deposit(gw_, 1'000'000);
1425 BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000}));
1426 ammAlice.deposit(gw_, USD(1'000));
1427 BEAST_EXPECT(ammAlice.expectBalances(
1428 XRP(11'000),
1429 STAmount{USD, UINT64_C(11'999'99999999998), -11},
1430 IOUAmount{11'489'125'29307605, -8}));
1431 });
1432
1433 // Min deposit
1434 testAMM([&](AMM& ammAlice, Env& env) {
1435 // Equal deposit by tokens
1436 ammAlice.deposit(
1437 carol_,
1438 1'000'000,
1439 XRP(1'000),
1440 USD(1'000),
1441 std::nullopt,
1442 tfLPToken,
1443 std::nullopt,
1444 std::nullopt);
1445 BEAST_EXPECT(
1446 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1447 });
1448 testAMM([&](AMM& ammAlice, Env& env) {
1449 // Equal deposit by asset
1450 ammAlice.deposit(
1451 carol_,
1452 1'000'000,
1453 XRP(1'000),
1454 USD(1'000),
1455 std::nullopt,
1456 tfTwoAsset,
1457 std::nullopt,
1458 std::nullopt);
1459 BEAST_EXPECT(
1460 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1461 });
1462 testAMM([&](AMM& ammAlice, Env& env) {
1463 // Single deposit by asset
1464 ammAlice.deposit(
1465 carol_,
1466 488'088,
1467 XRP(1'000),
1468 std::nullopt,
1469 std::nullopt,
1470 tfSingleAsset,
1471 std::nullopt,
1472 std::nullopt);
1473 BEAST_EXPECT(ammAlice.expectBalances(
1474 XRP(11'000), USD(10'000), IOUAmount{10'488'088'48170151, -8}));
1475 });
1476 testAMM([&](AMM& ammAlice, Env& env) {
1477 // Single deposit by asset
1478 ammAlice.deposit(
1479 carol_,
1480 488'088,
1481 USD(1'000),
1482 std::nullopt,
1483 std::nullopt,
1484 tfSingleAsset,
1485 std::nullopt,
1486 std::nullopt);
1487 BEAST_EXPECT(ammAlice.expectBalances(
1488 XRP(10'000),
1489 STAmount{USD, UINT64_C(10'999'99999999999), -11},
1490 IOUAmount{10'488'088'48170151, -8}));
1491 });
1492 }
1493
1494 void
1496 {
1497 testcase("Invalid Withdraw");
1498
1499 auto const all = testableAmendments();
1500 using namespace jtx;
1501
1502 testAMM(
1503 [&](AMM& ammAlice, Env& env) {
1504 WithdrawArg const args{
1505 .asset1Out = XRP(100),
1506 .err = Ter(tecAMM_BALANCE),
1507 };
1508 ammAlice.withdraw(args);
1509 },
1510 {{XRP(99), USD(99)}});
1511
1512 testAMM(
1513 [&](AMM& ammAlice, Env& env) {
1514 WithdrawArg const args{
1515 .asset1Out = USD(100),
1516 .err = Ter(tecAMM_BALANCE),
1517 };
1518 ammAlice.withdraw(args);
1519 },
1520 {{XRP(99), USD(99)}});
1521
1522 {
1523 Env env{*this};
1524 env.fund(XRP(30'000), gw_, alice_, bob_);
1525 env.close();
1526 env(fset(gw_, asfRequireAuth));
1527 env.close();
1528 env(trust(alice_, gw_["USD"](30'000), 0));
1529 env(trust(gw_, alice_["USD"](0), tfSetfAuth));
1530 // Bob trusts Gateway to owe him USD...
1531 env(trust(bob_, gw_["USD"](30'000), 0));
1532 // ...but Gateway does not authorize Bob to hold its USD.
1533 env.close();
1534 env(pay(gw_, alice_, USD(10'000)));
1535 env.close();
1536 AMM ammAlice(env, alice_, XRP(10'000), USD(10'000));
1537 WithdrawArg const args{
1538 .account = bob_,
1539 .asset1Out = USD(100),
1540 .err = Ter(tecNO_AUTH),
1541 };
1542 ammAlice.withdraw(args);
1543 }
1544
1545 testAMM([&](AMM& ammAlice, Env& env) {
1546 // Invalid flags
1547 ammAlice.withdraw(
1548 alice_,
1549 1'000'000,
1550 std::nullopt,
1551 std::nullopt,
1552 std::nullopt,
1553 tfBurnable,
1554 std::nullopt,
1555 std::nullopt,
1557 ammAlice.withdraw(
1558 alice_,
1559 1'000'000,
1560 std::nullopt,
1561 std::nullopt,
1562 std::nullopt,
1563 tfTwoAssetIfEmpty,
1564 std::nullopt,
1565 std::nullopt,
1567
1568 // Invalid options
1575 NotTEC>> const invalidOptions = {
1576 // tokens, asset1Out, asset2Out, EPrice, flags, ter
1577 {
1578 std::nullopt,
1579 std::nullopt,
1580 std::nullopt,
1581 std::nullopt,
1582 std::nullopt,
1584 },
1585 {
1586 std::nullopt,
1587 std::nullopt,
1588 std::nullopt,
1589 std::nullopt,
1590 tfSingleAsset | tfTwoAsset,
1592 },
1593 {1'000, std::nullopt, std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED},
1594 {
1595 std::nullopt,
1596 USD(0),
1597 XRP(100),
1598 std::nullopt,
1599 tfWithdrawAll | tfLPToken,
1601 },
1602 {std::nullopt, std::nullopt, USD(100), std::nullopt, tfWithdrawAll, temMALFORMED},
1603 {
1604 std::nullopt,
1605 std::nullopt,
1606 std::nullopt,
1607 std::nullopt,
1608 tfWithdrawAll | tfOneAssetWithdrawAll,
1610 },
1611 {std::nullopt, USD(100), std::nullopt, std::nullopt, tfWithdrawAll, temMALFORMED},
1612 {
1613 std::nullopt,
1614 std::nullopt,
1615 std::nullopt,
1616 std::nullopt,
1617 tfOneAssetWithdrawAll,
1619 },
1620 {1'000, std::nullopt, USD(100), std::nullopt, std::nullopt, temMALFORMED},
1621 {
1622 std::nullopt,
1623 std::nullopt,
1624 std::nullopt,
1625 IOUAmount{250, 0},
1626 tfWithdrawAll,
1628 },
1629 {1'000, std::nullopt, std::nullopt, IOUAmount{250, 0}, std::nullopt, temMALFORMED},
1630 {
1631 std::nullopt,
1632 std::nullopt,
1633 USD(100),
1634 IOUAmount{250, 0},
1635 std::nullopt,
1637 },
1638 {std::nullopt, XRP(100), USD(100), IOUAmount{250, 0}, std::nullopt, temMALFORMED},
1639 {1'000, XRP(100), USD(100), std::nullopt, std::nullopt, temMALFORMED},
1640 {std::nullopt, XRP(100), USD(100), std::nullopt, tfWithdrawAll, temMALFORMED},
1641 };
1642 for (auto const& it : invalidOptions)
1643 {
1644 ammAlice.withdraw(
1645 alice_,
1646 std::get<0>(it),
1647 std::get<1>(it),
1648 std::get<2>(it),
1649 std::get<3>(it),
1650 std::get<4>(it),
1651 std::nullopt,
1652 std::nullopt,
1653 Ter(std::get<5>(it)));
1654 }
1655
1656 // Invalid tokens
1657 ammAlice.withdraw(alice_, 0, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
1658 ammAlice.withdraw(
1659 alice_, IOUAmount{-1}, std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
1660
1661 // Mismatched token, invalid Asset1Out issue
1662 ammAlice.withdraw(alice_, GBP(100), std::nullopt, std::nullopt, Ter(temBAD_AMM_TOKENS));
1663
1664 // Mismatched token, invalid Asset2Out issue
1665 ammAlice.withdraw(alice_, USD(100), GBP(100), std::nullopt, Ter(temBAD_AMM_TOKENS));
1666
1667 // Mismatched token, Asset1Out.issue == Asset2Out.issue
1668 ammAlice.withdraw(alice_, USD(100), USD(100), std::nullopt, Ter(temBAD_AMM_TOKENS));
1669
1670 // Invalid amount value
1671 ammAlice.withdraw(alice_, USD(0), std::nullopt, std::nullopt, Ter(temBAD_AMOUNT));
1672 ammAlice.withdraw(alice_, USD(-100), std::nullopt, std::nullopt, Ter(temBAD_AMOUNT));
1673 ammAlice.withdraw(alice_, USD(10), std::nullopt, IOUAmount{-1}, Ter(temBAD_AMOUNT));
1674
1675 // Invalid amount/token value, withdraw all tokens from one side
1676 // of the pool.
1677 ammAlice.withdraw(alice_, USD(10'000), std::nullopt, std::nullopt, Ter(tecAMM_BALANCE));
1678 ammAlice.withdraw(alice_, XRP(10'000), std::nullopt, std::nullopt, Ter(tecAMM_BALANCE));
1679 ammAlice.withdraw(
1680 alice_,
1681 std::nullopt,
1682 USD(0),
1683 std::nullopt,
1684 std::nullopt,
1685 tfOneAssetWithdrawAll,
1686 std::nullopt,
1687 std::nullopt,
1689
1690 // Bad currency
1691 ammAlice.withdraw(alice_, BAD(100), std::nullopt, std::nullopt, Ter(temBAD_CURRENCY));
1692
1693 // Invalid Account
1694 Account const bad("bad");
1695 env.memoize(bad);
1696 ammAlice.withdraw(
1697 bad,
1698 1'000'000,
1699 std::nullopt,
1700 std::nullopt,
1701 std::nullopt,
1702 std::nullopt,
1703 std::nullopt,
1704 Seq(1),
1706
1707 // Invalid AMM
1708 ammAlice.withdraw(
1709 alice_,
1710 1'000,
1711 std::nullopt,
1712 std::nullopt,
1713 std::nullopt,
1714 std::nullopt,
1715 {{USD, GBP}},
1716 std::nullopt,
1717 Ter(terNO_AMM));
1718
1719 // Carol is not a Liquidity Provider
1720 ammAlice.withdraw(carol_, 10'000, std::nullopt, std::nullopt, Ter(tecAMM_BALANCE));
1721
1722 // Withdrawing from one side.
1723 // XRP by tokens
1724 ammAlice.withdraw(
1725 alice_, IOUAmount(9'999'999'9999, -4), XRP(0), std::nullopt, Ter(tecAMM_BALANCE));
1726 // USD by tokens
1727 ammAlice.withdraw(
1728 alice_, IOUAmount(9'999'999'9, -1), USD(0), std::nullopt, Ter(tecAMM_BALANCE));
1729 // XRP
1730 ammAlice.withdraw(alice_, XRP(10'000), std::nullopt, std::nullopt, Ter(tecAMM_BALANCE));
1731 // USD
1732 ammAlice.withdraw(
1733 alice_,
1734 STAmount{USD, UINT64_C(9'999'9999999999999), -13},
1735 std::nullopt,
1736 std::nullopt,
1738 });
1739
1740 testAMM(
1741 [&](AMM& ammAlice, Env& env) {
1742 // Withdraw entire one side of the pool.
1743 // Pre-amendment:
1744 // Equal withdraw but due to XRP rounding
1745 // this results in full withdraw of XRP pool only,
1746 // while leaving a tiny amount in USD pool.
1747 // Post-amendment:
1748 // Most of the pool is withdrawn with remaining tiny amounts
1749 auto err = env.enabled(fixAMMv1_3) ? Ter(tesSUCCESS) : Ter(tecAMM_BALANCE);
1750 ammAlice.withdraw(
1751 alice_, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err);
1752 if (env.enabled(fixAMMv1_3))
1753 {
1754 BEAST_EXPECT(ammAlice.expectBalances(
1755 XRPAmount(1), STAmount{USD, 1, -7}, IOUAmount{1, -4}));
1756 }
1757 },
1758 std::nullopt,
1759 0,
1760 std::nullopt,
1761 {all, all - fixAMMv1_3});
1762
1763 testAMM(
1764 [&](AMM& ammAlice, Env& env) {
1765 // Similar to above with even smaller remaining amount
1766 // is it ok that the pool is unbalanced?
1767 // Withdraw entire one side of the pool.
1768 // Equal withdraw but due to XRP precision limit,
1769 // this results in full withdraw of XRP pool only,
1770 // while leaving a tiny amount in USD pool.
1771 auto err = env.enabled(fixAMMv1_3) ? Ter(tesSUCCESS) : Ter(tecAMM_BALANCE);
1772 ammAlice.withdraw(
1773 alice_, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err);
1774 if (env.enabled(fixAMMv1_3))
1775 {
1776 BEAST_EXPECT(ammAlice.expectBalances(
1777 XRPAmount(1), STAmount{USD, 1, -11}, IOUAmount{1, -8}));
1778 }
1779 },
1780 std::nullopt,
1781 0,
1782 std::nullopt,
1783 {all, all - fixAMMv1_3});
1784
1785 // Invalid AMM
1786 testAMM([&](AMM& ammAlice, Env& env) {
1787 ammAlice.withdrawAll(alice_);
1788 ammAlice.withdraw(alice_, 10'000, std::nullopt, std::nullopt, Ter(terNO_AMM));
1789 });
1790
1791 // Globally frozen asset
1792 testAMM(
1793 [&](AMM& ammAlice, Env& env) {
1794 auto const fix330 = env.current()->rules().enabled(fixCleanup3_3_0);
1795 ammAlice.deposit({.account = gw_, .asset1In = USD(1'000), .asset2In = XRP(1'000)});
1796 env(fset(gw_, asfGlobalFreeze));
1797 env.close();
1798 // Can withdraw non-frozen token
1799 for (auto const& account : {alice_, gw_})
1800 {
1801 ammAlice.withdraw(account, XRP(100));
1802 // Post-fixCleanup3_3_0 the issuer can withdraw their own
1803 // frozen token from the pool.
1804 auto const frozenErr =
1805 (fix330 && account == gw_) ? Ter(tesSUCCESS) : Ter(tecFROZEN);
1806 ammAlice.withdraw(account, USD(100), std::nullopt, std::nullopt, frozenErr);
1807 ammAlice.withdraw(account, 1'000, std::nullopt, std::nullopt, frozenErr);
1808 }
1809 },
1810 std::nullopt,
1811 0,
1812 std::nullopt,
1813 amendmentCombinations({fixCleanup3_3_0}));
1814
1815 // Individually frozen (AMM) account
1816 testAMM(
1817 [&](AMM& ammAlice, Env& env) {
1818 auto const fix330 = env.current()->rules().enabled(fixCleanup3_3_0);
1819 env(trust(gw_, alice_["USD"](0), tfSetFreeze));
1820 env.close();
1821 // Can withdraw non-frozen token
1822 ammAlice.withdraw(alice_, XRP(100));
1823 // Post-fixCleanup3_3_0 regular freeze no longer blocks
1824 // self-withdrawal; only deep freeze does.
1825 auto const indivFreezeErr = fix330 ? Ter(tesSUCCESS) : Ter(tecFROZEN);
1826 ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, indivFreezeErr);
1827 ammAlice.withdraw(alice_, USD(100), std::nullopt, std::nullopt, indivFreezeErr);
1828 env(trust(gw_, alice_["USD"](0), tfClearFreeze));
1829 // Individually frozen AMM — still blocked regardless of
1830 // fixCleanup3_3_0 because the AMM account itself is frozen.
1831 env(trust(
1832 gw_,
1833 STAmount{Issue{gw_["USD"].currency, ammAlice.ammAccount()}, 0},
1834 tfSetFreeze));
1835 ammAlice.withdraw(alice_, XRP(100));
1836 ammAlice.withdraw(alice_, 1'000, std::nullopt, std::nullopt, Ter(tecFROZEN));
1837 ammAlice.withdraw(alice_, USD(100), std::nullopt, std::nullopt, Ter(tecFROZEN));
1838 },
1839 std::nullopt,
1840 0,
1841 std::nullopt,
1842 amendmentCombinations({fixCleanup3_3_0}));
1843
1844 // Carol withdraws more than she owns
1845 testAMM([&](AMM& ammAlice, Env&) {
1846 // Single deposit of 100000 worth of tokens,
1847 // which is 10% of the pool. Carol is LP now.
1848 ammAlice.deposit(carol_, 1'000'000);
1849 BEAST_EXPECT(
1850 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1851
1852 ammAlice.withdraw(
1853 carol_, 2'000'000, std::nullopt, std::nullopt, Ter(tecAMM_INVALID_TOKENS));
1854 BEAST_EXPECT(
1855 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1856 });
1857
1858 // Withdraw with EPrice limit. Fails to withdraw, calculated tokens
1859 // to withdraw are 0.
1860 testAMM(
1861 [&](AMM& ammAlice, Env& env) {
1862 ammAlice.deposit(carol_, 1'000'000);
1863 auto const err =
1864 env.enabled(fixAMMv1_3) ? Ter(tecAMM_INVALID_TOKENS) : Ter(tecAMM_FAILED);
1865 ammAlice.withdraw(carol_, USD(100), std::nullopt, IOUAmount{500, 0}, err);
1866 },
1867 std::nullopt,
1868 0,
1869 std::nullopt,
1870 {all, all - fixAMMv1_3});
1871
1872 // Withdraw with EPrice limit. Fails to withdraw, calculated tokens
1873 // to withdraw are greater than the LP shares.
1874 testAMM([&](AMM& ammAlice, Env&) {
1875 ammAlice.deposit(carol_, 1'000'000);
1876 ammAlice.withdraw(
1877 carol_, USD(100), std::nullopt, IOUAmount{600, 0}, Ter(tecAMM_INVALID_TOKENS));
1878 });
1879
1880 // Withdraw with EPrice limit. Fails to withdraw, amount1
1881 // to withdraw is less than 1700USD.
1882 testAMM([&](AMM& ammAlice, Env&) {
1883 ammAlice.deposit(carol_, 1'000'000);
1884 ammAlice.withdraw(
1885 carol_, USD(1'700), std::nullopt, IOUAmount{520, 0}, Ter(tecAMM_FAILED));
1886 });
1887
1888 // Deposit/Withdraw the same amount with the trading fee
1889 testAMM(
1890 [&](AMM& ammAlice, Env&) {
1891 ammAlice.deposit(carol_, USD(1'000));
1892 ammAlice.withdraw(
1893 carol_, USD(1'000), std::nullopt, std::nullopt, Ter(tecAMM_INVALID_TOKENS));
1894 },
1895 std::nullopt,
1896 1'000);
1897 testAMM(
1898 [&](AMM& ammAlice, Env&) {
1899 ammAlice.deposit(carol_, XRP(1'000));
1900 ammAlice.withdraw(
1901 carol_, XRP(1'000), std::nullopt, std::nullopt, Ter(tecAMM_INVALID_TOKENS));
1902 },
1903 std::nullopt,
1904 1'000);
1905
1906 // Deposit/Withdraw the same amount fails due to the tokens adjustment
1907 testAMM([&](AMM& ammAlice, Env&) {
1908 ammAlice.deposit(carol_, STAmount{USD, 1, -6});
1909 ammAlice.withdraw(
1910 carol_,
1911 STAmount{USD, 1, -6},
1912 std::nullopt,
1913 std::nullopt,
1915 });
1916
1917 // Withdraw close to one side of the pool. Account's LP tokens
1918 // are rounded to all LP tokens.
1919 testAMM(
1920 [&](AMM& ammAlice, Env& env) {
1921 // Without fixAMMv1_3: sub-method returns tecAMM_BALANCE early.
1922 // With fixAMMv1_3 but without fixCleanup3_3_0: sub-method succeeds
1923 // but invariant check catches the precision violation.
1924 // With fixCleanup3_3_0: caught in the transaction layer before
1925 // the invariant checker runs.
1926 auto const err = [&] {
1927 if (!env.enabled(fixAMMv1_3))
1928 return Ter(tecAMM_BALANCE);
1929 if (env.enabled(fixCleanup3_3_0))
1930 return Ter(tecPRECISION_LOSS);
1931 return Ter(tecINVARIANT_FAILED);
1932 }();
1933 ammAlice.withdraw(
1934 alice_,
1935 STAmount{USD, UINT64_C(9'999'999999999999), -12},
1936 std::nullopt,
1937 std::nullopt,
1938 err);
1939 },
1940 {.features = {all, all - fixAMMv1_3, all - fixCleanup3_3_0}, .noLog = true});
1941
1942 // Tiny withdraw
1943 testAMM([&](AMM& ammAlice, Env&) {
1944 // XRP amount to withdraw is 0
1945 ammAlice.withdraw(
1946 alice_, IOUAmount{1, -5}, std::nullopt, std::nullopt, Ter(tecAMM_FAILED));
1947 // Calculated tokens to withdraw are 0
1948 ammAlice.withdraw(
1949 alice_,
1950 std::nullopt,
1951 STAmount{USD, 1, -11},
1952 std::nullopt,
1954 ammAlice.deposit(carol_, STAmount{USD, 1, -10});
1955 ammAlice.withdraw(
1956 carol_,
1957 std::nullopt,
1958 STAmount{USD, 1, -9},
1959 std::nullopt,
1961 ammAlice.withdraw(
1962 carol_, std::nullopt, XRPAmount{1}, std::nullopt, Ter(tecAMM_INVALID_TOKENS));
1963 ammAlice.withdraw(
1964 WithdrawArg{.tokens = IOUAmount{1, -10}, .err = Ter(tecAMM_INVALID_TOKENS)});
1965 ammAlice.withdraw(
1967 .asset1Out = STAmount{USD, 1, -15},
1968 .asset2Out = XRPAmount{1},
1969 .err = Ter(tecAMM_INVALID_TOKENS),
1970 });
1971 ammAlice.withdraw(
1973 .tokens = IOUAmount{1, -10},
1974 .asset1Out = STAmount{USD, 1, -15},
1975 .err = Ter(tecAMM_INVALID_TOKENS),
1976 });
1977 });
1978 }
1979
1980 void
1982 {
1983 testcase("Withdraw");
1984
1985 auto const all = testableAmendments();
1986 using namespace jtx;
1987
1988 // Equal withdrawal by Carol: 1000000 of tokens, 10% of the current
1989 // pool
1990 testAMM([&](AMM& ammAlice, Env& env) {
1991 auto const baseFee = env.current()->fees().base.drops();
1992 // Single deposit of 100000 worth of tokens,
1993 // which is 10% of the pool. Carol is LP now.
1994 ammAlice.deposit(carol_, 1'000'000);
1995 BEAST_EXPECT(
1996 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{11'000'000, 0}));
1997 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{1'000'000, 0}));
1998 // 30,000 less deposited 1,000
1999 BEAST_EXPECT(expectHolding(env, carol_, USD(29'000)));
2000 // 30,000 less deposited 1,000 and 10 drops tx fee
2001 BEAST_EXPECT(expectLedgerEntryRoot(env, carol_, XRPAmount{29'000'000'000 - baseFee}));
2002
2003 // Carol withdraws all tokens
2004 ammAlice.withdraw(carol_, 1'000'000);
2005 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount(beast::Zero())));
2006 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000)));
2007 BEAST_EXPECT(
2008 expectLedgerEntryRoot(env, carol_, XRPAmount{30'000'000'000 - (2 * baseFee)}));
2009 });
2010
2011 // Equal withdrawal by tokens 1000000, 10%
2012 // of the current pool
2013 testAMM([&](AMM& ammAlice, Env&) {
2014 ammAlice.withdraw(alice_, 1'000'000);
2015 BEAST_EXPECT(ammAlice.expectBalances(XRP(9'000), USD(9'000), IOUAmount{9'000'000, 0}));
2016 });
2017
2018 // Equal withdrawal with a limit. Withdraw XRP200.
2019 // If proportional withdraw of USD is less than 100
2020 // then withdraw that amount, otherwise withdraw USD100
2021 // and proportionally withdraw XRP. It's the latter
2022 // in this case - XRP100/USD100.
2023 testAMM([&](AMM& ammAlice, Env&) {
2024 ammAlice.withdraw(alice_, XRP(200), USD(100));
2025 BEAST_EXPECT(ammAlice.expectBalances(XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0}));
2026 });
2027
2028 // Equal withdrawal with a limit. XRP100/USD100.
2029 testAMM([&](AMM& ammAlice, Env&) {
2030 ammAlice.withdraw(alice_, XRP(100), USD(200));
2031 BEAST_EXPECT(ammAlice.expectBalances(XRP(9'900), USD(9'900), IOUAmount{9'900'000, 0}));
2032 });
2033
2034 // Single withdrawal by amount XRP1000
2035 testAMM(
2036 [&](AMM& ammAlice, Env& env) {
2037 ammAlice.withdraw(alice_, XRP(1'000));
2038 if (!env.enabled(fixAMMv1_3))
2039 {
2040 BEAST_EXPECT(ammAlice.expectBalances(
2041 XRP(9'000), USD(10'000), IOUAmount{9'486'832'98050514, -8}));
2042 }
2043 else
2044 {
2045 BEAST_EXPECT(ammAlice.expectBalances(
2046 XRPAmount{9'000'000'001}, USD(10'000), IOUAmount{9'486'832'98050514, -8}));
2047 }
2048 },
2049 std::nullopt,
2050 0,
2051 std::nullopt,
2052 {all, all - fixAMMv1_3});
2053
2054 // Single withdrawal by tokens 10000.
2055 testAMM([&](AMM& ammAlice, Env&) {
2056 ammAlice.withdraw(alice_, 10'000, USD(0));
2057 BEAST_EXPECT(
2058 ammAlice.expectBalances(XRP(10'000), USD(9980.01), IOUAmount{9'990'000, 0}));
2059 });
2060
2061 // Withdraw all tokens.
2062 testAMM([&](AMM& ammAlice, Env& env) {
2063 env(trust(carol_, STAmount{ammAlice.lptIssue(), 10'000}));
2064 // Can TrustSet only for AMM LP tokens
2065 env(trust(carol_, STAmount{Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}),
2067 env.close();
2068 ammAlice.withdrawAll(alice_);
2069 BEAST_EXPECT(!ammAlice.ammExists());
2070
2071 BEAST_EXPECT(!env.le(keylet::ownerDir(ammAlice.ammAccount())));
2072
2073 // Can create AMM for the XRP/USD pair
2074 AMM const ammCarol(env, carol_, XRP(10'000), USD(10'000));
2075 BEAST_EXPECT(
2076 ammCarol.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0}));
2077 });
2078
2079 // Single deposit 1000USD, withdraw all tokens in USD
2080 testAMM([&](AMM& ammAlice, Env& env) {
2081 ammAlice.deposit(carol_, USD(1'000));
2082 ammAlice.withdrawAll(carol_, USD(0));
2083 BEAST_EXPECT(
2084 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0}));
2085 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount(beast::Zero())));
2086 });
2087
2088 // Single deposit 1000USD, withdraw all tokens in XRP
2089 testAMM([&](AMM& ammAlice, Env&) {
2090 ammAlice.deposit(carol_, USD(1'000));
2091 ammAlice.withdrawAll(carol_, XRP(0));
2092 BEAST_EXPECT(ammAlice.expectBalances(
2093 XRPAmount(9'090'909'091),
2094 STAmount{USD, UINT64_C(10'999'99999999999), -11},
2095 IOUAmount{10'000'000, 0}));
2096 });
2097
2098 // Single deposit/withdraw by the same account
2099 testAMM(
2100 [&](AMM& ammAlice, Env& env) {
2101 // Since a smaller amount might be deposited due to
2102 // the lp tokens adjustment, withdrawing by tokens
2103 // is generally preferred to withdrawing by amount.
2104 auto lpTokens = ammAlice.deposit(carol_, USD(1'000));
2105 ammAlice.withdraw(carol_, lpTokens, USD(0));
2106 lpTokens = ammAlice.deposit(carol_, STAmount(USD, 1, -6));
2107 ammAlice.withdraw(carol_, lpTokens, USD(0));
2108 lpTokens = ammAlice.deposit(carol_, XRPAmount(1));
2109 ammAlice.withdraw(carol_, lpTokens, XRPAmount(0));
2110 if (!env.enabled(fixAMMv1_3))
2111 {
2112 BEAST_EXPECT(
2113 ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens()));
2114 }
2115 else
2116 {
2117 BEAST_EXPECT(ammAlice.expectBalances(
2118 XRPAmount(10'000'000'001), USD(10'000), ammAlice.tokens()));
2119 }
2120 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0}));
2121 },
2122 std::nullopt,
2123 0,
2124 std::nullopt,
2125 {all, all - fixAMMv1_3});
2126
2127 // Single deposit by different accounts and then withdraw
2128 // in reverse.
2129 testAMM([&](AMM& ammAlice, Env&) {
2130 auto const carolTokens = ammAlice.deposit(carol_, USD(1'000));
2131 auto const aliceTokens = ammAlice.deposit(alice_, USD(1'000));
2132 ammAlice.withdraw(alice_, aliceTokens, USD(0));
2133 ammAlice.withdraw(carol_, carolTokens, USD(0));
2134 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), ammAlice.tokens()));
2135 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0}));
2136 BEAST_EXPECT(ammAlice.expectLPTokens(alice_, ammAlice.tokens()));
2137 });
2138
2139 // Equal deposit 10%, withdraw all tokens
2140 testAMM([&](AMM& ammAlice, Env&) {
2141 ammAlice.deposit(carol_, 1'000'000);
2142 ammAlice.withdrawAll(carol_);
2143 BEAST_EXPECT(
2144 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000, 0}));
2145 });
2146
2147 // Equal deposit 10%, withdraw all tokens in USD
2148 testAMM([&](AMM& ammAlice, Env&) {
2149 ammAlice.deposit(carol_, 1'000'000);
2150 ammAlice.withdrawAll(carol_, USD(0));
2151 BEAST_EXPECT(ammAlice.expectBalances(
2152 XRP(11'000),
2153 STAmount{USD, UINT64_C(9'090'909090909092), -12},
2154 IOUAmount{10'000'000, 0}));
2155 });
2156
2157 // Equal deposit 10%, withdraw all tokens in XRP
2158 testAMM([&](AMM& ammAlice, Env&) {
2159 ammAlice.deposit(carol_, 1'000'000);
2160 ammAlice.withdrawAll(carol_, XRP(0));
2161 BEAST_EXPECT(ammAlice.expectBalances(
2162 XRPAmount(9'090'909'091), USD(11'000), IOUAmount{10'000'000, 0}));
2163 });
2164
2165 // Withdraw with EPrice limit.
2166 testAMM(
2167 [&](AMM& ammAlice, Env& env) {
2168 ammAlice.deposit(carol_, 1'000'000);
2169 ammAlice.withdraw(carol_, USD(100), std::nullopt, IOUAmount{520, 0});
2170 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{153'846'15384616, -8}));
2171 if (!env.enabled(fixAMMv1_3))
2172 {
2173 BEAST_EXPECT(ammAlice.expectBalances(
2174 XRPAmount(11'000'000'000),
2175 STAmount{USD, UINT64_C(9'372'781065088769), -12},
2176 IOUAmount{10'153'846'15384616, -8}));
2177 }
2178 else
2179 {
2180 BEAST_EXPECT(ammAlice.expectBalances(
2181 XRPAmount(11'000'000'000),
2182 STAmount{USD, UINT64_C(9'372'78106508877), -11},
2183 IOUAmount{10'153'846'15384616, -8}));
2184 }
2185 ammAlice.withdrawAll(carol_);
2186 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0}));
2187 },
2188 {.features = {all, all - fixAMMv1_3}, .noLog = true});
2189
2190 // Withdraw with EPrice limit. AssetOut is 0.
2191 testAMM(
2192 [&](AMM& ammAlice, Env& env) {
2193 ammAlice.deposit(carol_, 1'000'000);
2194 ammAlice.withdraw(carol_, USD(0), std::nullopt, IOUAmount{520, 0});
2195 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{153'846'15384616, -8}));
2196 if (!env.enabled(fixAMMv1_3))
2197 {
2198 BEAST_EXPECT(ammAlice.expectBalances(
2199 XRP(11'000),
2200 STAmount{USD, UINT64_C(9'372'781065088769), -12},
2201 IOUAmount{10'153'846'15384616, -8}));
2202 }
2203 else
2204 {
2205 BEAST_EXPECT(ammAlice.expectBalances(
2206 XRP(11'000),
2207 STAmount{USD, UINT64_C(9'372'78106508877), -11},
2208 IOUAmount{10'153'846'15384616, -8}));
2209 }
2210 },
2211 std::nullopt,
2212 0,
2213 std::nullopt,
2214 {all, all - fixAMMv1_3});
2215
2216 // IOU to IOU + transfer fee
2217 {
2218 Env env{*this};
2219 fund(env, gw_, {alice_}, {USD(20'000), BTC(0.5)}, Fund::All);
2220 env(rate(gw_, 1.25));
2221 env.close();
2222 // no transfer fee on create
2223 AMM ammAlice(env, alice_, USD(20'000), BTC(0.5));
2224 BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0}));
2225 BEAST_EXPECT(expectHolding(env, alice_, USD(0)));
2226 BEAST_EXPECT(expectHolding(env, alice_, BTC(0)));
2227 fund(env, gw_, {carol_}, {USD(2'000), BTC(0.05)}, Fund::Acct);
2228 // no transfer fee on deposit
2229 ammAlice.deposit(carol_, 10);
2230 BEAST_EXPECT(ammAlice.expectBalances(USD(22'000), BTC(0.55), IOUAmount{110, 0}));
2231 BEAST_EXPECT(expectHolding(env, carol_, USD(0)));
2232 BEAST_EXPECT(expectHolding(env, carol_, BTC(0)));
2233 // no transfer fee on withdraw
2234 ammAlice.withdraw(carol_, 10);
2235 BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(0.5), IOUAmount{100, 0}));
2236 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0, 0}));
2237 BEAST_EXPECT(expectHolding(env, carol_, USD(2'000)));
2238 BEAST_EXPECT(expectHolding(env, carol_, BTC(0.05)));
2239 }
2240
2241 // Tiny withdraw
2242 testAMM([&](AMM& ammAlice, Env&) {
2243 // By tokens
2244 ammAlice.withdraw(alice_, IOUAmount{1, -3});
2245 BEAST_EXPECT(ammAlice.expectBalances(
2246 XRPAmount{9'999'999'999},
2247 STAmount{USD, UINT64_C(9'999'999999), -6},
2248 IOUAmount{9'999'999'999, -3}));
2249 });
2250 testAMM(
2251 [&](AMM& ammAlice, Env& env) {
2252 // Single XRP pool
2253 ammAlice.withdraw(alice_, std::nullopt, XRPAmount{1});
2254 if (!env.enabled(fixAMMv1_3))
2255 {
2256 BEAST_EXPECT(ammAlice.expectBalances(
2257 XRPAmount{9'999'999'999}, USD(10'000), IOUAmount{9'999'999'9995, -4}));
2258 }
2259 else
2260 {
2261 BEAST_EXPECT(ammAlice.expectBalances(
2262 XRP(10'000), USD(10'000), IOUAmount{9'999'999'9995, -4}));
2263 }
2264 },
2265 std::nullopt,
2266 0,
2267 std::nullopt,
2268 {all, all - fixAMMv1_3});
2269 testAMM([&](AMM& ammAlice, Env&) {
2270 // Single USD pool
2271 ammAlice.withdraw(alice_, std::nullopt, STAmount{USD, 1, -10});
2272 BEAST_EXPECT(ammAlice.expectBalances(
2273 XRP(10'000),
2274 STAmount{USD, UINT64_C(9'999'9999999999), -10},
2275 IOUAmount{9'999'999'99999995, -8}));
2276 });
2277
2278 // Withdraw close to entire pool
2279 // Equal by tokens
2280 testAMM([&](AMM& ammAlice, Env&) {
2281 ammAlice.withdraw(alice_, IOUAmount{9'999'999'999, -3});
2282 BEAST_EXPECT(
2283 ammAlice.expectBalances(XRPAmount{1}, STAmount{USD, 1, -6}, IOUAmount{1, -3}));
2284 });
2285 // USD by tokens
2286 testAMM([&](AMM& ammAlice, Env&) {
2287 ammAlice.withdraw(alice_, IOUAmount{9'999'999}, USD(0));
2288 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), STAmount{USD, 1, -10}, IOUAmount{1}));
2289 });
2290 // XRP by tokens
2291 testAMM([&](AMM& ammAlice, Env&) {
2292 ammAlice.withdraw(alice_, IOUAmount{9'999'900}, XRP(0));
2293 BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, USD(10'000), IOUAmount{100}));
2294 });
2295 // USD
2296 testAMM([&](AMM& ammAlice, Env&) {
2297 ammAlice.withdraw(alice_, STAmount{USD, UINT64_C(9'999'99999999999), -11});
2298 BEAST_EXPECT(ammAlice.expectBalances(
2299 XRP(10000), STAmount{USD, 1, -11}, IOUAmount{316227765, -9}));
2300 });
2301 // XRP
2302 testAMM([&](AMM& ammAlice, Env&) {
2303 ammAlice.withdraw(alice_, XRPAmount{9'999'999'999});
2304 BEAST_EXPECT(ammAlice.expectBalances(XRPAmount{1}, USD(10'000), IOUAmount{100}));
2305 });
2306
2307 // singleWithdrawEPrice: crafted ePrice = lptAMMBalance*f/amountBalance
2308 // makes the denominator (T*f - A*E) exactly zero.
2309 // Pre-fixCleanup3_3_0: std::overflow_error escapes to the
2310 // transactor backstop and is returned as tefEXCEPTION.
2311 // Post-fixCleanup3_3_0: denominator check returns tecAMM_FAILED.
2312 //
2313 // Pool: USD(100)/EUR(100), baseFee=1000 (1%).
2314 // Alice is the creator so her discounted fee is 100 (0.1%), f=0.001.
2315 // ePrice = lptAMMBalance(100) * f(0.001) / amountBalance(100) = 0.001
2316 testAMM(
2317 [&](AMM& ammAlice, Env& env) {
2318 auto const err = env.enabled(fixCleanup3_3_0) || env.enabled(fixCleanup3_4_0)
2320 : Ter(tefEXCEPTION);
2321 ammAlice.withdraw(
2323 .account = alice_,
2324 .asset1Out = USD(0),
2325 .maxEP = IOUAmount{1, -3}, // ePrice=0.001 → denom=0
2326 .err = err,
2327 });
2328 },
2329 {{USD(100), EUR(100)}},
2330 1000,
2331 std::nullopt,
2332 {all - fixCleanup3_3_0 - fixCleanup3_4_0, all - fixCleanup3_4_0, all});
2333 }
2334
2335 void
2337 {
2338 testcase("Invalid Fee Vote");
2339 using namespace jtx;
2340
2341 testAMM([&](AMM& ammAlice, Env& env) {
2342 // Invalid flags
2343 ammAlice.vote(
2344 std::nullopt,
2345 1'000,
2346 tfWithdrawAll,
2347 std::nullopt,
2348 std::nullopt,
2350
2351 // Invalid fee.
2352 ammAlice.vote(
2353 std::nullopt, 1'001, std::nullopt, std::nullopt, std::nullopt, Ter(temBAD_FEE));
2354 BEAST_EXPECT(ammAlice.expectTradingFee(0));
2355
2356 // Invalid Account
2357 Account const bad("bad");
2358 env.memoize(bad);
2359 ammAlice.vote(bad, 1'000, std::nullopt, Seq(1), std::nullopt, Ter(terNO_ACCOUNT));
2360
2361 // Invalid AMM
2362 ammAlice.vote(alice_, 1'000, std::nullopt, std::nullopt, {{USD, GBP}}, Ter(terNO_AMM));
2363
2364 // Account is not LP
2365 ammAlice.vote(
2366 carol_,
2367 1'000,
2368 std::nullopt,
2369 std::nullopt,
2370 std::nullopt,
2372 });
2373
2374 // Invalid AMM
2375 testAMM([&](AMM& ammAlice, Env& env) {
2376 ammAlice.withdrawAll(alice_);
2377 ammAlice.vote(alice_, 1'000, std::nullopt, std::nullopt, std::nullopt, Ter(terNO_AMM));
2378 });
2379 }
2380
2381 void
2383 {
2384 testcase("Fee Vote");
2385 auto const all = testableAmendments();
2386 using namespace jtx;
2387
2388 // One vote sets fee to 1%.
2389 testAMM([&](AMM& ammAlice, Env& env) {
2390 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{0}));
2391 ammAlice.vote({}, 1'000);
2392 BEAST_EXPECT(ammAlice.expectTradingFee(1'000));
2393 // Discounted fee is 1/10 of trading fee.
2394 BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, IOUAmount{0}));
2395 });
2396
2397 auto vote = [&](AMM& ammAlice,
2398 Env& env,
2399 int i,
2400 int fundUSD = 100'000,
2401 std::uint32_t tokens = 10'000'000,
2402 std::vector<Account>* accounts = nullptr) {
2403 Account a(std::to_string(i));
2404 // post-amendment the amount to deposit is slightly higher
2405 // in order to ensure AMM invariant sqrt(asset1 * asset2) >= tokens
2406 // fund just one USD higher in this case, which is enough for
2407 // deposit to succeed
2408 if (env.enabled(fixAMMv1_3))
2409 ++fundUSD;
2410 fund(env, gw_, {a}, {USD(fundUSD)}, Fund::Acct);
2411 ammAlice.deposit(a, tokens);
2412 ammAlice.vote(a, 50 * (i + 1));
2413 if (accounts)
2414 accounts->push_back(std::move(a));
2415 };
2416
2417 // Eight votes fill all voting slots, set fee 0.175%.
2418 testAMM(
2419 [&](AMM& ammAlice, Env& env) {
2420 for (int i = 0; i < 7; ++i)
2421 vote(ammAlice, env, i, 10'000);
2422 BEAST_EXPECT(ammAlice.expectTradingFee(175));
2423 },
2424 std::nullopt,
2425 0,
2426 std::nullopt,
2427 {all});
2428
2429 // Eight votes fill all voting slots, set fee 0.175%.
2430 // New vote, same account, sets fee 0.225%
2431 testAMM([&](AMM& ammAlice, Env& env) {
2432 for (int i = 0; i < 7; ++i)
2433 vote(ammAlice, env, i);
2434 BEAST_EXPECT(ammAlice.expectTradingFee(175));
2435 Account const a("0");
2436 ammAlice.vote(a, 450);
2437 BEAST_EXPECT(ammAlice.expectTradingFee(225));
2438 });
2439
2440 // Eight votes fill all voting slots, set fee 0.175%.
2441 // New vote, new account, higher vote weight, set higher fee 0.244%
2442 testAMM([&](AMM& ammAlice, Env& env) {
2443 for (int i = 0; i < 7; ++i)
2444 vote(ammAlice, env, i);
2445 BEAST_EXPECT(ammAlice.expectTradingFee(175));
2446 vote(ammAlice, env, 7, 100'000, 20'000'000);
2447 BEAST_EXPECT(ammAlice.expectTradingFee(244));
2448 });
2449
2450 // Eight votes fill all voting slots, set fee 0.219%.
2451 // New vote, new account, higher vote weight, set smaller fee 0.206%
2452 testAMM([&](AMM& ammAlice, Env& env) {
2453 for (int i = 7; i > 0; --i)
2454 vote(ammAlice, env, i);
2455 BEAST_EXPECT(ammAlice.expectTradingFee(219));
2456 vote(ammAlice, env, 0, 100'000, 20'000'000);
2457 BEAST_EXPECT(ammAlice.expectTradingFee(206));
2458 });
2459
2460 // Eight votes fill all voting slots. The accounts then withdraw all
2461 // tokens. An account sets a new fee and the previous slots are
2462 // deleted.
2463 testAMM([&](AMM& ammAlice, Env& env) {
2464 std::vector<Account> accounts;
2465 for (int i = 0; i < 7; ++i)
2466 vote(ammAlice, env, i, 100'000, 10'000'000, &accounts);
2467 BEAST_EXPECT(ammAlice.expectTradingFee(175));
2468 for (int i = 0; i < 7; ++i)
2469 ammAlice.withdrawAll(accounts[i]);
2470 ammAlice.deposit(carol_, 10'000'000);
2471 ammAlice.vote(carol_, 1'000);
2472 // The initial LP set the fee to 1000. Carol gets 50% voting
2473 // power, and the new fee is 500.
2474 BEAST_EXPECT(ammAlice.expectTradingFee(500));
2475 });
2476
2477 // Eight votes fill all voting slots. The accounts then withdraw some
2478 // tokens. The new vote doesn't get the voting power but
2479 // the slots are refreshed and the fee is updated.
2480 testAMM([&](AMM& ammAlice, Env& env) {
2481 std::vector<Account> accounts;
2482 for (int i = 0; i < 7; ++i)
2483 vote(ammAlice, env, i, 100'000, 10'000'000, &accounts);
2484 BEAST_EXPECT(ammAlice.expectTradingFee(175));
2485 for (int i = 0; i < 7; ++i)
2486 ammAlice.withdraw(accounts[i], 9'000'000);
2487 ammAlice.deposit(carol_, 1'000);
2488 // The vote is not added to the slots
2489 ammAlice.vote(carol_, 1'000);
2490 auto const info = ammAlice.ammRpcInfo()[jss::amm][jss::vote_slots];
2491 for (auto const& entry : info)
2492 BEAST_EXPECT(entry[jss::account] != carol_.human());
2493 // But the slots are refreshed and the fee is changed
2494 BEAST_EXPECT(ammAlice.expectTradingFee(82));
2495 });
2496 }
2497
2498 void
2500 {
2501 testcase("Invalid Bid");
2502 using namespace jtx;
2503 using namespace std::chrono;
2504
2505 // burn all the LPTokens through a AMMBid transaction
2506 {
2507 Env env(*this);
2508 fund(env, gw_, {alice_}, XRP(2'000), {USD(2'000)});
2509 AMM amm(env, gw_, XRP(1'000), USD(1'000), false, 1'000);
2510
2511 // auction slot is owned by the creator of the AMM i.e. gw_
2512 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0}));
2513
2514 // gw_ attempts to burn all her LPTokens through a bid transaction
2515 // this transaction fails because AMMBid transaction can not burn
2516 // all the outstanding LPTokens
2517 env(amm.bid({
2518 .account = gw_,
2519 .bidMin = 1'000'000,
2520 }),
2522 }
2523
2524 // burn all the LPTokens through a AMMBid transaction
2525 {
2526 Env env(*this);
2527 fund(env, gw_, {alice_}, XRP(2'000), {USD(2'000)});
2528 AMM amm(env, gw_, XRP(1'000), USD(1'000), false, 1'000);
2529
2530 // auction slot is owned by the creator of the AMM i.e. gw_
2531 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0}));
2532
2533 // gw_ burns all but one of its LPTokens through a bid transaction
2534 // this transaction succeeds because the bid price is less than
2535 // the total outstanding LPToken balance
2536 env(amm.bid({
2537 .account = gw_,
2538 .bidMin = STAmount{amm.lptIssue(), UINT64_C(999'999)},
2539 }),
2540 Ter(tesSUCCESS))
2541 .close();
2542
2543 // gw_ must own the auction slot
2544 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{999'999}));
2545
2546 // 999'999 tokens are burned, only 1 LPToken is owned by gw_
2547 BEAST_EXPECT(amm.expectBalances(XRP(1'000), USD(1'000), IOUAmount{1}));
2548
2549 // gw_ owns only 1 LPToken in its balance
2550 BEAST_EXPECT(Number{amm.getLPTokensBalance(gw_)} == 1);
2551
2552 // gw_ attempts to burn the last of its LPTokens in an AMMBid
2553 // transaction. This transaction fails because it would burn all
2554 // the remaining LPTokens
2555 env(amm.bid({
2556 .account = gw_,
2557 .bidMin = 1,
2558 }),
2560 }
2561
2562 testAMM([&](AMM& ammAlice, Env& env) {
2563 // Invalid flags
2564 env(ammAlice.bid({
2565 .account = carol_,
2566 .bidMin = 0,
2567 .flags = tfWithdrawAll,
2568 }),
2570
2571 ammAlice.deposit(carol_, 1'000'000);
2572 // Invalid Bid price <= 0
2573 for (auto bid : {0, -100})
2574 {
2575 env(ammAlice.bid({
2576 .account = carol_,
2577 .bidMin = bid,
2578 }),
2579 Ter(temBAD_AMOUNT));
2580 env(ammAlice.bid({
2581 .account = carol_,
2582 .bidMax = bid,
2583 }),
2584 Ter(temBAD_AMOUNT));
2585 }
2586
2587 // Invalid Min/Max combination
2588 env(ammAlice.bid({
2589 .account = carol_,
2590 .bidMin = 200,
2591 .bidMax = 100,
2592 }),
2594
2595 // Invalid Account
2596 Account const bad("bad");
2597 env.memoize(bad);
2598 env(ammAlice.bid({
2599 .account = bad,
2600 .bidMax = 100,
2601 }),
2602 Seq(1),
2603 Ter(terNO_ACCOUNT));
2604
2605 // Account is not LP
2606 Account const dan("dan");
2607 env.fund(XRP(1'000), dan);
2608 env(ammAlice.bid({
2609 .account = dan,
2610 .bidMin = 100,
2611 }),
2613 env(ammAlice.bid({
2614 .account = dan,
2615 }),
2617
2618 // Auth account is invalid.
2619 env(ammAlice.bid({
2620 .account = carol_,
2621 .bidMin = 100,
2622 .authAccounts = {bob_},
2623 }),
2624 Ter(terNO_ACCOUNT));
2625
2626 // Invalid Assets
2627 env(ammAlice.bid({
2628 .account = alice_,
2629 .bidMax = 100,
2630 .assets = {{USD, GBP}},
2631 }),
2632 Ter(terNO_AMM));
2633
2634 // Invalid Min/Max issue
2635 env(ammAlice.bid({
2636 .account = alice_,
2637 .bidMax = STAmount{USD, 100},
2638 }),
2639 Ter(temBAD_AMM_TOKENS));
2640 env(ammAlice.bid({
2641 .account = alice_,
2642 .bidMin = STAmount{USD, 100},
2643 }),
2644 Ter(temBAD_AMM_TOKENS));
2645 });
2646
2647 // Invalid AMM
2648 testAMM([&](AMM& ammAlice, Env& env) {
2649 ammAlice.withdrawAll(alice_);
2650 env(ammAlice.bid({
2651 .account = alice_,
2652 .bidMax = 100,
2653 }),
2654 Ter(terNO_AMM));
2655 });
2656
2657 // More than four Auth accounts.
2658 testAMM([&](AMM& ammAlice, Env& env) {
2659 Account const ed("ed");
2660 Account const bill("bill");
2661 Account const scott("scott");
2662 Account const james("james");
2663 env.fund(XRP(1'000), bob_, ed, bill, scott, james);
2664 env.close();
2665 ammAlice.deposit(carol_, 1'000'000);
2666 env(ammAlice.bid({
2667 .account = carol_,
2668 .bidMin = 100,
2669 .authAccounts = {bob_, ed, bill, scott, james},
2670 }),
2671 Ter(temMALFORMED));
2672 });
2673
2674 // Bid price exceeds LP owned tokens
2675 testAMM([&](AMM& ammAlice, Env& env) {
2676 fund(env, gw_, {bob_}, XRP(1'000), {USD(100)}, Fund::Acct);
2677 ammAlice.deposit(carol_, 1'000'000);
2678 ammAlice.deposit(bob_, 10);
2679 env(ammAlice.bid({
2680 .account = carol_,
2681 .bidMin = 1'000'001,
2682 }),
2683 Ter(tecAMM_INVALID_TOKENS));
2684 env(ammAlice.bid({
2685 .account = carol_,
2686 .bidMax = 1'000'001,
2687 }),
2688 Ter(tecAMM_INVALID_TOKENS));
2689 env(ammAlice.bid({
2690 .account = carol_,
2691 .bidMin = 1'000,
2692 }));
2693 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{1'000}));
2694 // Slot purchase price is more than 1000 but bob_ only has 10 tokens
2695 env(ammAlice.bid({
2696 .account = bob_,
2697 }),
2698 Ter(tecAMM_INVALID_TOKENS));
2699 });
2700
2701 // Bid all tokens, still own the slot
2702 {
2703 Env env(*this);
2704 fund(env, gw_, {alice_, bob_}, XRP(1'000), {USD(1'000)});
2705 AMM amm(env, gw_, XRP(10), USD(1'000));
2706 auto const lpIssue = amm.lptIssue();
2707 env.trust(STAmount{lpIssue, 100}, alice_);
2708 env.trust(STAmount{lpIssue, 50}, bob_);
2709 env(pay(gw_, alice_, STAmount{lpIssue, 100}));
2710 env(pay(gw_, bob_, STAmount{lpIssue, 50}));
2711 env(amm.bid({.account = alice_, .bidMin = 100}));
2712 // Alice doesn't have any more tokens, but
2713 // she still owns the slot.
2714 env(amm.bid({
2715 .account = bob_,
2716 .bidMax = 50,
2717 }),
2718 Ter(tecAMM_FAILED));
2719 }
2720 }
2721
2722 void
2724 {
2725 testcase("Bid");
2726 using namespace jtx;
2727 using namespace std::chrono;
2728
2729 // Auction slot initially is owned by AMM creator, who pays 0 price.
2730
2731 // Bid 110 tokens. Pay bidMin.
2732 testAMM(
2733 [&](AMM& ammAlice, Env& env) {
2734 ammAlice.deposit(carol_, 1'000'000);
2735 env(ammAlice.bid({.account = carol_, .bidMin = 110}));
2736 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110}));
2737 // 110 tokens are burned.
2738 BEAST_EXPECT(
2739 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890, 0}));
2740 },
2741 std::nullopt,
2742 0,
2743 std::nullopt,
2744 {features});
2745
2746 // Bid with min/max when the pay price is less than min.
2747 testAMM(
2748 [&](AMM& ammAlice, Env& env) {
2749 ammAlice.deposit(carol_, 1'000'000);
2750 // Bid exactly 110. Pay 110 because the pay price is < 110.
2751 env(ammAlice.bid({.account = carol_, .bidMin = 110, .bidMax = 110}));
2752 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110}));
2753 BEAST_EXPECT(
2754 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'890}));
2755 // Bid exactly 180-200. Pay 180 because the pay price is < 180.
2756 env(ammAlice.bid({.account = alice_, .bidMin = 180, .bidMax = 200}));
2757 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{180}));
2758 BEAST_EXPECT(
2759 ammAlice.expectBalances(XRP(11'000), USD(11'000), IOUAmount{10'999'814'5, -1}));
2760 },
2761 std::nullopt,
2762 0,
2763 std::nullopt,
2764 {features});
2765
2766 // Start bid at bidMin 110.
2767 testAMM(
2768 [&](AMM& ammAlice, Env& env) {
2769 ammAlice.deposit(carol_, 1'000'000);
2770 // Bid, pay bidMin.
2771 env(ammAlice.bid({.account = carol_, .bidMin = 110}));
2772 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110}));
2773
2774 fund(env, gw_, {bob_}, {USD(10'000)}, Fund::Acct);
2775 ammAlice.deposit(bob_, 1'000'000);
2776 // Bid, pay the computed price.
2777 env(ammAlice.bid({.account = bob_}));
2778 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount(1155, -1)));
2779
2780 // Bid bidMax fails because the computed price is higher.
2781 env(ammAlice.bid({
2782 .account = carol_,
2783 .bidMax = 120,
2784 }),
2786 // Bid MaxSlotPrice succeeds - pay computed price
2787 env(ammAlice.bid({.account = carol_, .bidMax = 600}));
2788 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{121'275, -3}));
2789
2790 // Bid Min/MaxSlotPrice fails because the computed price is not
2791 // in range
2792 env(ammAlice.bid({
2793 .account = carol_,
2794 .bidMin = 10,
2795 .bidMax = 100,
2796 }),
2798 // Bid Min/MaxSlotPrice succeeds - pay computed price
2799 env(ammAlice.bid({.account = carol_, .bidMin = 100, .bidMax = 600}));
2800 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{127'33875, -5}));
2801 },
2802 std::nullopt,
2803 0,
2804 std::nullopt,
2805 {features});
2806
2807 // Slot states.
2808 testAMM(
2809 [&](AMM& ammAlice, Env& env) {
2810 ammAlice.deposit(carol_, 1'000'000);
2811
2812 fund(env, gw_, {bob_}, {USD(10'000)}, Fund::Acct);
2813 ammAlice.deposit(bob_, 1'000'000);
2814 if (!features[fixAMMv1_3])
2815 {
2816 BEAST_EXPECT(ammAlice.expectBalances(
2817 XRP(12'000), USD(12'000), IOUAmount{12'000'000, 0}));
2818 }
2819 else
2820 {
2821 BEAST_EXPECT(ammAlice.expectBalances(
2822 XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{12'000'000, 0}));
2823 }
2824
2825 // Initial state. Pay bidMin.
2826 env(ammAlice.bid({.account = carol_, .bidMin = 110})).close();
2827 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110}));
2828
2829 // 1st Interval after close, price for 0th interval.
2830 env(ammAlice.bid({.account = bob_}));
2832 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 1, IOUAmount{1'155, -1}));
2833
2834 // 10th Interval after close, price for 1st interval.
2835 env(ammAlice.bid({.account = carol_}));
2837 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 10, IOUAmount{121'275, -3}));
2838
2839 // 20th Interval (expired) after close, price for 10th interval.
2840 env(ammAlice.bid({.account = bob_}));
2842 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5}));
2843
2844 // 0 Interval.
2845 env(ammAlice.bid({.account = carol_, .bidMin = 110})).close();
2846 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{110}));
2847 // ~321.09 tokens burnt on bidding fees.
2848 if (!features[fixAMMv1_3])
2849 {
2850 BEAST_EXPECT(ammAlice.expectBalances(
2851 XRP(12'000), USD(12'000), IOUAmount{11'999'678'91, -2}));
2852 }
2853 else
2854 {
2855 BEAST_EXPECT(ammAlice.expectBalances(
2856 XRPAmount{12'000'000'001}, USD(12'000), IOUAmount{11'999'678'91, -2}));
2857 }
2858 },
2859 std::nullopt,
2860 0,
2861 std::nullopt,
2862 {features});
2863
2864 // Pool's fee 1%. Bid bidMin.
2865 // Auction slot owner and auth account trade at discounted fee -
2866 // 1/10 of the trading fee.
2867 // Other accounts trade at 1% fee.
2868 testAMM(
2869 [&](AMM& ammAlice, Env& env) {
2870 Account const dan("dan");
2871 Account const ed("ed");
2872 fund(env, gw_, {bob_, dan, ed}, {USD(20'000)}, Fund::Acct);
2873 ammAlice.deposit(bob_, 1'000'000);
2874 ammAlice.deposit(ed, 1'000'000);
2875 ammAlice.deposit(carol_, 500'000);
2876 ammAlice.deposit(dan, 500'000);
2877 auto ammTokens = ammAlice.getLPTokensBalance();
2878 env(ammAlice.bid({
2879 .account = carol_,
2880 .bidMin = 120,
2881 .authAccounts = {bob_, ed},
2882 }));
2883 auto const slotPrice = IOUAmount{5'200};
2884 ammTokens -= slotPrice;
2885 BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, slotPrice));
2886 if (!features[fixAMMv1_3])
2887 {
2888 BEAST_EXPECT(ammAlice.expectBalances(XRP(13'000), USD(13'000), ammTokens));
2889 }
2890 else
2891 {
2892 BEAST_EXPECT(
2893 ammAlice.expectBalances(XRPAmount{13'000'000'003}, USD(13'000), ammTokens));
2894 }
2895 // Discounted trade
2896 for (int i = 0; i < 10; ++i)
2897 {
2898 auto tokens = ammAlice.deposit(carol_, USD(100));
2899 ammAlice.withdraw(carol_, tokens, USD(0));
2900 tokens = ammAlice.deposit(bob_, USD(100));
2901 ammAlice.withdraw(bob_, tokens, USD(0));
2902 tokens = ammAlice.deposit(ed, USD(100));
2903 ammAlice.withdraw(ed, tokens, USD(0));
2904 }
2905 // carol_, bob_, and ed pay ~0.99USD in fees.
2906 BEAST_EXPECT(
2907 env.balance(carol_, USD) == STAmount(USD, UINT64_C(29'499'00572620544), -11));
2908 BEAST_EXPECT(
2909 env.balance(bob_, USD) == STAmount(USD, UINT64_C(18'999'00572616194), -11));
2910 BEAST_EXPECT(
2911 env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'0057261184), -10));
2912 // USD pool is slightly higher because of the fees.
2913 if (!features[fixAMMv1_3])
2914 {
2915 BEAST_EXPECT(ammAlice.expectBalances(
2916 XRP(13'000), STAmount(USD, UINT64_C(13'002'98282151422), -11), ammTokens));
2917 }
2918 else
2919 {
2920 BEAST_EXPECT(ammAlice.expectBalances(
2921 XRPAmount{13'000'000'003},
2922 STAmount(USD, UINT64_C(13'002'98282151422), -11),
2923 ammTokens));
2924 }
2925 ammTokens = ammAlice.getLPTokensBalance();
2926 // Trade with the fee
2927 for (int i = 0; i < 10; ++i)
2928 {
2929 auto const tokens = ammAlice.deposit(dan, USD(100));
2930 ammAlice.withdraw(dan, tokens, USD(0));
2931 }
2932 // dan pays ~9.94USD, which is ~10 times more in fees than
2933 // carol_, bob_, ed. the discounted fee is 10 times less
2934 // than the trading fee.
2935 if (!features[fixAMMv1_3])
2936 {
2937 BEAST_EXPECT(
2938 env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274399), -11));
2939 }
2940 else
2941 {
2942 BEAST_EXPECT(
2943 env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274398), -11));
2944 }
2945 // USD pool gains more in dan's fees.
2946 if (!features[fixAMMv1_3])
2947 {
2948 BEAST_EXPECT(ammAlice.expectBalances(
2949 XRP(13'000), STAmount{USD, UINT64_C(13'012'92609877023), -11}, ammTokens));
2950 }
2951 else
2952 {
2953 BEAST_EXPECT(ammAlice.expectBalances(
2954 XRPAmount{13'000'000'003},
2955 STAmount{USD, UINT64_C(13'012'92609877024), -11},
2956 ammTokens));
2957 }
2958 // Discounted fee payment
2959 ammAlice.deposit(carol_, USD(100));
2960 ammTokens = ammAlice.getLPTokensBalance();
2961 if (!features[fixAMMv1_3])
2962 {
2963 BEAST_EXPECT(ammAlice.expectBalances(
2964 XRP(13'000), STAmount{USD, UINT64_C(13'112'92609877023), -11}, ammTokens));
2965 }
2966 else
2967 {
2968 BEAST_EXPECT(ammAlice.expectBalances(
2969 XRPAmount{13'000'000'003},
2970 STAmount{USD, UINT64_C(13'112'92609877024), -11},
2971 ammTokens));
2972 }
2973 env(pay(carol_, bob_, USD(100)), Path(~USD), Sendmax(XRP(110)));
2974 env.close();
2975 // carol_ pays 100000 drops in fees
2976 // 99900668XRP swapped in for 100USD
2977 if (!features[fixAMMv1_3])
2978 {
2979 BEAST_EXPECT(ammAlice.expectBalances(
2980 XRPAmount{13'100'000'668},
2981 STAmount{USD, UINT64_C(13'012'92609877023), -11},
2982 ammTokens));
2983 }
2984 else
2985 {
2986 BEAST_EXPECT(ammAlice.expectBalances(
2987 XRPAmount{13'100'000'671},
2988 STAmount{USD, UINT64_C(13'012'92609877024), -11},
2989 ammTokens));
2990 }
2991 // Payment with the trading fee
2992 env(pay(alice_, carol_, XRP(100)), Path(~XRP), Sendmax(USD(110)));
2993 env.close();
2994 // alice_ pays ~1.011USD in fees, which is ~10 times more
2995 // than carol_'s fee
2996 // 100.099431529USD swapped in for 100XRP
2997 if (!features[fixAMMv1_3])
2998 {
2999 BEAST_EXPECT(ammAlice.expectBalances(
3000 XRPAmount{13'000'000'668},
3001 STAmount{USD, UINT64_C(13'114'03663047269), -11},
3002 ammTokens));
3003 }
3004 else
3005 {
3006 BEAST_EXPECT(ammAlice.expectBalances(
3007 XRPAmount{13'000'000'671},
3008 STAmount{USD, UINT64_C(13'114'03663044937), -11},
3009 ammTokens));
3010 }
3011 // Auction slot expired, no discounted fee
3013 // clock is parent's based
3014 env.close();
3015 if (!features[fixAMMv1_3])
3016 {
3017 BEAST_EXPECT(
3018 env.balance(carol_, USD) ==
3019 STAmount(USD, UINT64_C(29'399'00572620544), -11));
3020 }
3021 ammTokens = ammAlice.getLPTokensBalance();
3022 for (int i = 0; i < 10; ++i)
3023 {
3024 auto const tokens = ammAlice.deposit(carol_, USD(100));
3025 ammAlice.withdraw(carol_, tokens, USD(0));
3026 }
3027 // carol_ pays ~9.94USD in fees, which is ~10 times more in
3028 // trading fees vs discounted fee.
3029 if (!features[fixAMMv1_3])
3030 {
3031 BEAST_EXPECT(
3032 env.balance(carol_, USD) ==
3033 STAmount(USD, UINT64_C(29'389'06197177124), -11));
3034 BEAST_EXPECT(ammAlice.expectBalances(
3035 XRPAmount{13'000'000'668},
3036 STAmount{USD, UINT64_C(13'123'98038490689), -11},
3037 ammTokens));
3038 }
3039 else
3040 {
3041 BEAST_EXPECT(
3042 env.balance(carol_, USD) ==
3043 STAmount(USD, UINT64_C(29'389'06197177129), -11));
3044 BEAST_EXPECT(ammAlice.expectBalances(
3045 XRPAmount{13'000'000'671},
3046 STAmount{USD, UINT64_C(13'123'98038488352), -11},
3047 ammTokens));
3048 }
3049 env(pay(carol_, bob_, USD(100)), Path(~USD), Sendmax(XRP(110)));
3050 env.close();
3051 // carol_ pays ~1.008XRP in trading fee, which is
3052 // ~10 times more than the discounted fee.
3053 // 99.815876XRP is swapped in for 100USD
3054 if (!features[fixAMMv1_3])
3055 {
3056 BEAST_EXPECT(ammAlice.expectBalances(
3057 XRPAmount(13'100'824'790),
3058 STAmount{USD, UINT64_C(13'023'98038490689), -11},
3059 ammTokens));
3060 }
3061 else
3062 {
3063 BEAST_EXPECT(ammAlice.expectBalances(
3064 XRPAmount(13'100'824'793),
3065 STAmount{USD, UINT64_C(13'023'98038488352), -11},
3066 ammTokens));
3067 }
3068 },
3069 std::nullopt,
3070 1'000,
3071 std::nullopt,
3072 {features});
3073
3074 // Zero-fee bid without an explicit price pays a floor with fixCleanup3_4_0.
3075 testAMM(
3076 [&](AMM& ammAlice, Env& env) {
3077 auto const minBidPrice = IOUAmount{ammAuctionMinSlotPrice(ammAlice.tokens(), 1)};
3078 auto const cleanup340 = features[fixCleanup3_4_0];
3079 auto const expectedPrice = cleanup340 ? minBidPrice : IOUAmount{0};
3080 auto const expectedTokens = cleanup340
3081 ? IOUAmount{Number{ammAlice.tokens()} - Number{minBidPrice}}
3082 : ammAlice.tokens();
3083
3084 env.close(seconds(kTotalTimeSlotSecs + 1));
3085 env.close();
3086 env(ammAlice.bid({.account = alice_}));
3087 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, expectedPrice));
3088 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), expectedTokens));
3089
3090 ammAlice.vote(alice_, 1'000);
3091 BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, expectedPrice));
3092 },
3093 std::nullopt,
3094 0,
3095 std::nullopt,
3096 {features});
3097
3098 // Bid tiny amount
3099 testAMM(
3100 [&](AMM& ammAlice, Env& env) {
3101 // Bid a tiny amount
3102 auto const tiny = Number{STAmount::kMinValue, STAmount::kMinOffset};
3103 auto const cleanup340 = features[fixCleanup3_4_0];
3104 auto const minBidPrice = IOUAmount{ammAuctionMinSlotPrice(ammAlice.tokens(), 1)};
3105 auto const firstPrice = cleanup340 ? minBidPrice : IOUAmount{tiny};
3106 env(ammAlice.bid({.account = alice_, .bidMin = IOUAmount{tiny}}));
3107 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, firstPrice));
3108 BEAST_EXPECT(ammAlice.expectBalances(
3109 XRP(10'000),
3110 USD(10'000),
3111 cleanup340 ? IOUAmount{Number{ammAlice.tokens()} - Number{minBidPrice}}
3112 : ammAlice.tokens()));
3113 // Bid the tiny amount
3114 env(ammAlice.bid({
3115 .account = alice_,
3116 .bidMin = IOUAmount{STAmount::kMinValue, STAmount::kMinOffset},
3117 }));
3118 // Pay slightly higher price
3119 BEAST_EXPECT(ammAlice.expectAuctionSlot(
3120 0, 0, IOUAmount{Number{firstPrice} * Number{105, -2}}));
3121 BEAST_EXPECT(ammAlice.expectBalances(
3122 XRP(10'000),
3123 USD(10'000),
3124 cleanup340
3125 ? IOUAmount{Number{ammAlice.tokens()} - Number{minBidPrice} * Number{11, -1}}
3126 : ammAlice.tokens()));
3127 },
3128 std::nullopt,
3129 0,
3130 std::nullopt,
3131 {features});
3132
3133 // Reset auth account
3134 testAMM(
3135 [&](AMM& ammAlice, Env& env) {
3136 env(ammAlice.bid({
3137 .account = alice_,
3138 .bidMin = IOUAmount{100},
3139 .authAccounts = {carol_},
3140 }));
3141 BEAST_EXPECT(ammAlice.expectAuctionSlot({carol_}));
3142 env(ammAlice.bid({.account = alice_, .bidMin = IOUAmount{100}}));
3143 BEAST_EXPECT(ammAlice.expectAuctionSlot({}));
3144 Account const bob("bob");
3145 Account const dan("dan");
3146 fund(env, {bob, dan}, XRP(1'000));
3147 env(ammAlice.bid({
3148 .account = alice_,
3149 .bidMin = IOUAmount{100},
3150 .authAccounts = {bob, dan},
3151 }));
3152 BEAST_EXPECT(ammAlice.expectAuctionSlot({bob, dan}));
3153 },
3154 std::nullopt,
3155 0,
3156 std::nullopt,
3157 {features});
3158
3159 // Bid all tokens, still own the slot and trade at a discount
3160 {
3161 Env env(*this, features);
3162 fund(env, gw_, {alice_, bob_}, XRP(2'000), {USD(2'000)});
3163 AMM amm(env, gw_, XRP(1'000), USD(1'010), false, 1'000);
3164 auto const lpIssue = amm.lptIssue();
3165 env.trust(STAmount{lpIssue, 500}, alice_);
3166 env.trust(STAmount{lpIssue, 50}, bob_);
3167 env(pay(gw_, alice_, STAmount{lpIssue, 500}));
3168 env(pay(gw_, bob_, STAmount{lpIssue, 50}));
3169 // Alice doesn't have anymore lp tokens
3170 env(amm.bid({.account = alice_, .bidMin = 500}));
3171 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{500}));
3172 BEAST_EXPECT(expectHolding(env, alice_, STAmount{lpIssue, 0}));
3173 // But trades with the discounted fee since she still owns the slot.
3174 // Alice pays 10011 drops in fees
3175 env(pay(alice_, bob_, USD(10)), Path(~USD), Sendmax(XRP(11)));
3176 BEAST_EXPECT(amm.expectBalances(
3177 XRPAmount{1'010'010'011}, USD(1'000), IOUAmount{1'004'487'562112089, -9}));
3178 // Bob pays the full fee ~0.1USD
3179 env(pay(bob_, alice_, XRP(10)), Path(~XRP), Sendmax(USD(11)));
3180 BEAST_EXPECT(amm.expectBalances(
3181 XRPAmount{1'000'010'011},
3182 STAmount{USD, UINT64_C(1'010'100908980811), -12},
3183 IOUAmount{1'004'487'562112089, -9}));
3184 }
3185
3186 // preflight tests
3187 {
3188 Env env(*this, features);
3189 auto const baseFee = env.current()->fees().base;
3190
3191 fund(env, gw_, {alice_, bob_}, XRP(2'000), {USD(2'000)});
3192 AMM amm(env, gw_, XRP(1'000), USD(1'010), false, 1'000);
3193 json::Value const tx = amm.bid({.account = alice_, .bidMin = 500});
3194
3195 {
3196 auto jtx = env.jt(tx, Seq(1), Fee(baseFee));
3197 jtx.jv["TxnSignature"] = "deadbeef";
3198 jtx.stx = env.ust(jtx);
3199 PreflightContext const pfCtx(
3200 env.app(), *jtx.stx, env.current()->rules(), TapNone, env.journal);
3201 auto const pf = Transactor::invokePreflight<AMMBid>(pfCtx);
3202 BEAST_EXPECT(!isTesSuccess(pf));
3203 }
3204
3205 {
3206 auto jtx = env.jt(tx, Seq(1), Fee(baseFee));
3207 jtx.jv["Asset2"]["currency"] = "XRP";
3208 jtx.jv["Asset2"].removeMember("issuer");
3209 jtx.stx = env.ust(jtx);
3210 PreflightContext const pfCtx(
3211 env.app(), *jtx.stx, env.current()->rules(), TapNone, env.journal);
3212 auto const pf = Transactor::invokePreflight<AMMBid>(pfCtx);
3213 BEAST_EXPECT(pf == temBAD_AMM_TOKENS);
3214 }
3215 }
3216 }
3217
3218 void
3220 {
3221 testcase("Invalid AMM Payment");
3222 using namespace jtx;
3223 using namespace std::chrono;
3224 using namespace std::literals::chrono_literals;
3225
3226 // Can't pay into AMM account.
3227 // Can't pay out since there is no keys
3228 for (auto const& acct : {gw_, alice_})
3229 {
3230 {
3231 Env env(*this);
3232 fund(env, gw_, {alice_, carol_}, XRP(1'000), {USD(100)});
3233 // XRP balance is below reserve
3234 AMM const ammAlice(env, acct, XRP(10), USD(10));
3235 // Pay below reserve
3236 env(pay(carol_, ammAlice.ammAccount(), XRP(10)), Ter(tecNO_PERMISSION));
3237 // Pay above reserve
3238 env(pay(carol_, ammAlice.ammAccount(), XRP(300)), Ter(tecNO_PERMISSION));
3239 // Pay IOU
3240 env(pay(carol_, ammAlice.ammAccount(), USD(10)), Ter(tecNO_PERMISSION));
3241 }
3242 {
3243 Env env(*this);
3244 fund(env, gw_, {alice_, carol_}, XRP(10'000'000), {USD(10'000)});
3245 // XRP balance is above reserve
3246 AMM const ammAlice(env, acct, XRP(1'000'000), USD(100));
3247 // Pay below reserve
3248 env(pay(carol_, ammAlice.ammAccount(), XRP(10)), Ter(tecNO_PERMISSION));
3249 // Pay above reserve
3250 env(pay(carol_, ammAlice.ammAccount(), XRP(1'000'000)), Ter(tecNO_PERMISSION));
3251 }
3252 }
3253
3254 // Can't pay into AMM with escrow.
3255 testAMM([&](AMM& ammAlice, Env& env) {
3256 auto const baseFee = env.current()->fees().base;
3257 env(escrow::create(carol_, ammAlice.ammAccount(), XRP(1)),
3259 escrow::kFinishTime(env.now() + 1s),
3260 escrow::kCancelTime(env.now() + 2s),
3261 Fee(baseFee * 150),
3263 });
3264
3265 // Can't pay into AMM with paychan.
3266 testAMM([&](AMM& ammAlice, Env& env) {
3267 auto const pk = carol_.pk();
3268 auto const settleDelay = 100s;
3269 NetClock::time_point const cancelAfter = env.current()->header().parentCloseTime + 200s;
3270 env(paychan::create(
3271 carol_, ammAlice.ammAccount(), XRP(1'000), settleDelay, pk, cancelAfter),
3273 });
3274
3275 // Can't pay into AMM with checks.
3276 testAMM([&](AMM& ammAlice, Env& env) {
3277 env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)),
3279 });
3280
3281 // Pay amounts close to one side of the pool
3282 testAMM(
3283 [&](AMM& ammAlice, Env& env) {
3284 // Can't consume whole pool
3285 env(pay(alice_, carol_, USD(100)),
3286 Path(~USD),
3287 Sendmax(XRP(1'000'000'000)),
3289 env(pay(alice_, carol_, XRP(100)),
3290 Path(~XRP),
3291 Sendmax(USD(1'000'000'000)),
3293 // Overflow
3294 env(pay(alice_, carol_, STAmount{USD, UINT64_C(99'999999999), -9}),
3295 Path(~USD),
3296 Sendmax(XRP(1'000'000'000)),
3298 env(pay(alice_, carol_, STAmount{USD, UINT64_C(999'99999999), -8}),
3299 Path(~USD),
3300 Sendmax(XRP(1'000'000'000)),
3302 env(pay(alice_, carol_, STAmount{xrpIssue(), 99'999'999}),
3303 Path(~XRP),
3304 Sendmax(USD(1'000'000'000)),
3306 // Sender doesn't have enough funds
3307 env(pay(alice_, carol_, USD(99.99)),
3308 Path(~USD),
3309 Sendmax(XRP(1'000'000'000)),
3311 env(pay(alice_, carol_, STAmount{xrpIssue(), 99'990'000}),
3312 Path(~XRP),
3313 Sendmax(USD(1'000'000'000)),
3315 },
3316 {{XRP(100), USD(100)}});
3317
3318 // Globally frozen
3319 testAMM([&](AMM& ammAlice, Env& env) {
3320 env(fset(gw_, asfGlobalFreeze));
3321 env.close();
3322 env(pay(alice_, carol_, USD(1)),
3323 Path(~USD),
3324 Txflags(tfPartialPayment | tfNoRippleDirect),
3325 Sendmax(XRP(10)),
3326 Ter(tecPATH_DRY));
3327 env(pay(alice_, carol_, XRP(1)),
3328 Path(~XRP),
3329 Txflags(tfPartialPayment | tfNoRippleDirect),
3330 Sendmax(USD(10)),
3331 Ter(tecPATH_DRY));
3332 });
3333
3334 // Individually frozen AMM
3335 testAMM([&](AMM& ammAlice, Env& env) {
3336 env(trust(
3337 gw_, STAmount{Issue{gw_["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze));
3338 env.close();
3339 env(pay(alice_, carol_, USD(1)),
3340 Path(~USD),
3341 Txflags(tfPartialPayment | tfNoRippleDirect),
3342 Sendmax(XRP(10)),
3343 Ter(tecPATH_DRY));
3344 env(pay(alice_, carol_, XRP(1)),
3345 Path(~XRP),
3346 Txflags(tfPartialPayment | tfNoRippleDirect),
3347 Sendmax(USD(10)),
3348 Ter(tecPATH_DRY));
3349 });
3350
3351 // Individually frozen accounts
3352 testAMM([&](AMM& ammAlice, Env& env) {
3353 env(trust(gw_, carol_["USD"](0), tfSetFreeze));
3354 env(trust(gw_, alice_["USD"](0), tfSetFreeze));
3355 env.close();
3356 env(pay(alice_, carol_, XRP(1)),
3357 Path(~XRP),
3358 Sendmax(USD(10)),
3359 Txflags(tfNoRippleDirect | tfPartialPayment),
3360 Ter(tecPATH_DRY));
3361 });
3362 }
3363
3364 void
3366 {
3367 testcase("Basic Payment");
3368 using namespace jtx;
3369
3370 // Payment 100USD for 100XRP.
3371 // Force one path with tfNoRippleDirect.
3372 testAMM(
3373 [&](AMM& ammAlice, Env& env) {
3374 env.fund(jtx::XRP(30'000), bob_);
3375 env.close();
3376 env(pay(bob_, carol_, USD(100)),
3377 Path(~USD),
3378 Sendmax(XRP(100)),
3379 Txflags(tfNoRippleDirect));
3380 env.close();
3381 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens()));
3382 // Initial balance 30,000 + 100
3383 BEAST_EXPECT(expectHolding(env, carol_, USD(30'100)));
3384 // Initial balance 30,000 - 100(sendmax) - 10(tx fee)
3385 BEAST_EXPECT(
3386 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(100) - txFee(env, 1)));
3387 },
3388 {{XRP(10'000), USD(10'100)}},
3389 0,
3390 std::nullopt,
3391 {features});
3392
3393 // Payment 100USD for 100XRP, use default path.
3394 testAMM(
3395 [&](AMM& ammAlice, Env& env) {
3396 env.fund(jtx::XRP(30'000), bob_);
3397 env.close();
3398 env(pay(bob_, carol_, USD(100)), Sendmax(XRP(100)));
3399 env.close();
3400 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens()));
3401 // Initial balance 30,000 + 100
3402 BEAST_EXPECT(expectHolding(env, carol_, USD(30'100)));
3403 // Initial balance 30,000 - 100(sendmax) - 10(tx fee)
3404 BEAST_EXPECT(
3405 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(100) - txFee(env, 1)));
3406 },
3407 {{XRP(10'000), USD(10'100)}},
3408 0,
3409 std::nullopt,
3410 {features});
3411
3412 // This payment is identical to above. While it has
3413 // both default path and path, activeStrands has one path.
3414 testAMM(
3415 [&](AMM& ammAlice, Env& env) {
3416 env.fund(jtx::XRP(30'000), bob_);
3417 env.close();
3418 env(pay(bob_, carol_, USD(100)), Path(~USD), Sendmax(XRP(100)));
3419 env.close();
3420 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens()));
3421 // Initial balance 30,000 + 100
3422 BEAST_EXPECT(expectHolding(env, carol_, USD(30'100)));
3423 // Initial balance 30,000 - 100(sendmax) - 10(tx fee)
3424 BEAST_EXPECT(
3425 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(100) - txFee(env, 1)));
3426 },
3427 {{XRP(10'000), USD(10'100)}},
3428 0,
3429 std::nullopt,
3430 {features});
3431
3432 // Payment with limitQuality set.
3433 testAMM(
3434 [&](AMM& ammAlice, Env& env) {
3435 env.fund(jtx::XRP(30'000), bob_);
3436 env.close();
3437 // Pays 10USD for 10XRP. A larger payment of ~99.11USD/100XRP
3438 // would have been sent has it not been for limitQuality.
3439 env(pay(bob_, carol_, USD(100)),
3440 Path(~USD),
3441 Sendmax(XRP(100)),
3442 Txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality));
3443 env.close();
3444 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'010), USD(10'000), ammAlice.tokens()));
3445 // Initial balance 30,000 + 10(limited by limitQuality)
3446 BEAST_EXPECT(expectHolding(env, carol_, USD(30'010)));
3447 // Initial balance 30,000 - 10(limited by limitQuality) - 10(tx
3448 // fee)
3449 BEAST_EXPECT(
3450 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(10) - txFee(env, 1)));
3451
3452 // Fails because of limitQuality. Would have sent
3453 // ~98.91USD/110XRP has it not been for limitQuality.
3454 env(pay(bob_, carol_, USD(100)),
3455 Path(~USD),
3456 Sendmax(XRP(100)),
3457 Txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality),
3458 Ter(tecPATH_DRY));
3459 env.close();
3460 },
3461 {{XRP(10'000), USD(10'010)}},
3462 0,
3463 std::nullopt,
3464 {features});
3465
3466 // Payment with limitQuality and transfer fee set.
3467 testAMM(
3468 [&](AMM& ammAlice, Env& env) {
3469 env(rate(gw_, 1.1));
3470 env.close();
3471 env.fund(jtx::XRP(30'000), bob_);
3472 env.close();
3473 // Pays 10USD for 10XRP. A larger payment of ~99.11USD/100XRP
3474 // would have been sent has it not been for limitQuality and
3475 // the transfer fee.
3476 env(pay(bob_, carol_, USD(100)),
3477 Path(~USD),
3478 Sendmax(XRP(110)),
3479 Txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality));
3480 env.close();
3481 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'010), USD(10'000), ammAlice.tokens()));
3482 // 10USD - 10% transfer fee
3483 BEAST_EXPECT(
3484 expectHolding(env, carol_, STAmount{USD, UINT64_C(30'009'09090909091), -11}));
3485 BEAST_EXPECT(
3486 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(10) - txFee(env, 1)));
3487 },
3488 {{XRP(10'000), USD(10'010)}},
3489 0,
3490 std::nullopt,
3491 {features});
3492
3493 // Fail when partial payment is not set.
3494 testAMM(
3495 [&](AMM& ammAlice, Env& env) {
3496 env.fund(jtx::XRP(30'000), bob_);
3497 env.close();
3498 env(pay(bob_, carol_, USD(100)),
3499 Path(~USD),
3500 Sendmax(XRP(100)),
3501 Txflags(tfNoRippleDirect),
3503 },
3504 {{XRP(10'000), USD(10'000)}},
3505 0,
3506 std::nullopt,
3507 {features});
3508
3509 // Non-default path (with AMM) has a better quality than default path.
3510 // The max possible liquidity is taken out of non-default
3511 // path ~29.9XRP/29.9EUR, ~29.9EUR/~29.99USD. The rest
3512 // is taken from the offer.
3513 {
3514 Env env(*this, features);
3515 fund(env, gw_, {alice_, carol_}, {USD(30'000), EUR(30'000)}, Fund::All);
3516 env.close();
3517 env.fund(XRP(1'000), bob_);
3518 env.close();
3519 auto const ammEurXrp = AMM(env, alice_, XRP(10'000), EUR(10'000));
3520 auto const ammUsdEur = AMM(env, alice_, EUR(10'000), USD(10'000));
3521 env(offer(alice_, XRP(101), USD(100)), Txflags(tfPassive));
3522 env.close();
3523 env(pay(bob_, carol_, USD(100)),
3524 Path(~EUR, ~USD),
3525 Sendmax(XRP(102)),
3526 Txflags(tfPartialPayment));
3527 env.close();
3528 BEAST_EXPECT(ammEurXrp.expectBalances(
3529 XRPAmount(10'030'082'730),
3530 STAmount(EUR, UINT64_C(9'970'007498125468), -12),
3531 ammEurXrp.tokens()));
3532 BEAST_EXPECT(ammUsdEur.expectBalances(
3533 STAmount(USD, UINT64_C(9'970'097277662172), -12),
3534 STAmount(EUR, UINT64_C(10'029'99250187452), -11),
3535 ammUsdEur.tokens()));
3536
3537 // fixReducedOffersV2 changes the expected results slightly.
3538 Amounts const expectedAmounts = env.closed()->rules().enabled(fixReducedOffersV2)
3539 ? Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782839), -14)}
3540 : Amounts{XRPAmount(30'201'749), STAmount(USD, UINT64_C(29'90272233782840), -14)};
3541
3542 BEAST_EXPECT(expectOffers(env, alice_, 1, {{expectedAmounts}}));
3543 // Initial 30,000 + 100
3544 BEAST_EXPECT(expectHolding(env, carol_, STAmount{USD, 30'100}));
3545 // Initial 1,000 - 30082730(AMM pool) - 70798251(offer) - 10(tx fee)
3546 BEAST_EXPECT(expectLedgerEntryRoot(
3547 env,
3548 bob_,
3549 XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - txFee(env, 1)));
3550 }
3551
3552 // Default path (with AMM) has a better quality than a non-default path.
3553 // The max possible liquidity is taken out of default
3554 // path ~49XRP/49USD. The rest is taken from the offer.
3555 testAMM(
3556 [&](AMM& ammAlice, Env& env) {
3557 env.fund(XRP(1'000), bob_);
3558 env.close();
3559 env.trust(EUR(2'000), alice_);
3560 env.close();
3561 env(pay(gw_, alice_, EUR(1'000)));
3562 env(offer(alice_, XRP(101), EUR(100)), Txflags(tfPassive));
3563 env.close();
3564 env(offer(alice_, EUR(100), USD(100)), Txflags(tfPassive));
3565 env.close();
3566 env(pay(bob_, carol_, USD(100)),
3567 Path(~EUR, ~USD),
3568 Sendmax(XRP(102)),
3569 Txflags(tfPartialPayment));
3570 env.close();
3571 BEAST_EXPECT(ammAlice.expectBalances(
3572 XRPAmount(10'050'238'637),
3573 STAmount(USD, UINT64_C(9'950'01249687578), -11),
3574 ammAlice.tokens()));
3575 BEAST_EXPECT(expectOffers(
3576 env,
3577 alice_,
3578 2,
3579 {{Amounts{XRPAmount(50'487'378), STAmount(EUR, UINT64_C(49'98750312422), -11)},
3580 Amounts{
3581 STAmount(EUR, UINT64_C(49'98750312422), -11),
3582 STAmount(USD, UINT64_C(49'98750312422), -11)}}}));
3583 // Initial 30,000 + 99.99999999999
3584 BEAST_EXPECT(
3585 expectHolding(env, carol_, STAmount{USD, UINT64_C(30'099'99999999999), -11}));
3586 // Initial 1,000 - 50238637(AMM pool) - 50512622(offer) - 10(tx
3587 // fee)
3588 BEAST_EXPECT(expectLedgerEntryRoot(
3589 env,
3590 bob_,
3591 XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - txFee(env, 1)));
3592 },
3593 std::nullopt,
3594 0,
3595 std::nullopt,
3596 {features});
3597
3598 // Default path with AMM and Order Book offer. AMM is consumed first,
3599 // remaining amount is consumed by the offer.
3600 testAMM(
3601 [&](AMM& ammAlice, Env& env) {
3602 fund(env, gw_, {bob_}, {USD(100)}, Fund::Acct);
3603 env.close();
3604 env(offer(bob_, XRP(100), USD(100)), Txflags(tfPassive));
3605 env.close();
3606 env(pay(alice_, carol_, USD(200)), Sendmax(XRP(200)), Txflags(tfPartialPayment));
3607 env.close();
3608 BEAST_EXPECT(ammAlice.expectBalances(
3609 XRP(10'100),
3610 STAmount(USD, UINT64_C(10'000'00000000001), -11),
3611 ammAlice.tokens()));
3612 BEAST_EXPECT(
3613 expectHolding(env, carol_, STAmount(USD, UINT64_C(30'199'99999999999), -11)));
3614 // Initial 30,000 - 10000(AMM pool LP) - 100(AMM offer) -
3615 // - 100(offer) - 10(tx fee) - one reserve
3616 BEAST_EXPECT(expectLedgerEntryRoot(
3617 env,
3618 alice_,
3619 XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - ammCrtFee(env) -
3620 txFee(env, 1)));
3621 BEAST_EXPECT(expectOffers(env, bob_, 0));
3622 },
3623 {{XRP(10'000), USD(10'100)}},
3624 0,
3625 std::nullopt,
3626 {features});
3627
3628 // Default path with AMM and Order Book offer.
3629 // Order Book offer is consumed first.
3630 // Remaining amount is consumed by AMM.
3631 {
3632 Env env(*this, features);
3633 fund(env, gw_, {alice_, bob_, carol_}, XRP(20'000), {USD(2'000)});
3634 env.close();
3635 env(offer(bob_, XRP(50), USD(150)), Txflags(tfPassive));
3636 env.close();
3637 AMM const ammAlice(env, alice_, XRP(1'000), USD(1'050));
3638 env(pay(alice_, carol_, USD(200)), Sendmax(XRP(200)), Txflags(tfPartialPayment));
3639 env.close();
3640 BEAST_EXPECT(ammAlice.expectBalances(XRP(1'050), USD(1'000), ammAlice.tokens()));
3641 BEAST_EXPECT(expectHolding(env, carol_, USD(2'200)));
3642 BEAST_EXPECT(expectOffers(env, bob_, 0));
3643 }
3644
3645 // Offer crossing XRP/IOU
3646 testAMM(
3647 [&](AMM& ammAlice, Env& env) {
3648 fund(env, gw_, {bob_}, {USD(1'000)}, Fund::Acct);
3649 env.close();
3650 env(offer(bob_, USD(100), XRP(100)));
3651 env.close();
3652 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), USD(10'000), ammAlice.tokens()));
3653 // Initial 1,000 + 100
3654 BEAST_EXPECT(expectHolding(env, bob_, USD(1'100)));
3655 // Initial 30,000 - 100(offer) - 10(tx fee)
3656 BEAST_EXPECT(
3657 expectLedgerEntryRoot(env, bob_, XRP(30'000) - XRP(100) - txFee(env, 1)));
3658 BEAST_EXPECT(expectOffers(env, bob_, 0));
3659 },
3660 {{XRP(10'000), USD(10'100)}},
3661 0,
3662 std::nullopt,
3663 {features});
3664
3665 // Offer crossing IOU/IOU and transfer rate
3666 // Single path AMM offer
3667 testAMM(
3668 [&](AMM& ammAlice, Env& env) {
3669 env(rate(gw_, 1.25));
3670 env.close();
3671 // This offer crosses because the strand's out amount is small enough to match
3672 // limitQuality value and limitOut() function in StrandFlow
3673 // doesn't require an adjustment to out value.
3674 env(offer(carol_, EUR(100), GBP(100)));
3675 env.close();
3676 // No transfer fee
3677 BEAST_EXPECT(ammAlice.expectBalances(GBP(1'100), EUR(1'000), ammAlice.tokens()));
3678 // Initial 30,000 - 100(offer) - 25% transfer fee
3679 BEAST_EXPECT(expectHolding(env, carol_, GBP(29'875)));
3680 // Initial 30,000 + 100(offer)
3681 BEAST_EXPECT(expectHolding(env, carol_, EUR(30'100)));
3682 BEAST_EXPECT(expectOffers(env, bob_, 0));
3683 },
3684 {{GBP(1'000), EUR(1'100)}},
3685 0,
3686 std::nullopt,
3687 {features});
3688 // Single-path AMM offer
3689 testAMM(
3690 [&](AMM& amm, Env& env) {
3691 env(rate(gw_, 1.001));
3692 env.close();
3693 env(offer(carol_, XRP(100), USD(55)));
3694 env.close();
3695 BEAST_EXPECT(amm.expectBalances(
3696 XRPAmount(909'090'909),
3697 STAmount{USD, UINT64_C(550'000000055), -9},
3698 amm.tokens()));
3699 BEAST_EXPECT(expectOffers(
3700 env,
3701 carol_,
3702 1,
3703 {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}}));
3704 BEAST_EXPECT(
3705 env.balance(carol_, USD) == STAmount(USD, UINT64_C(29'949'94999999494), -11));
3706 },
3707 {{XRP(1'000), USD(500)}},
3708 0,
3709 std::nullopt,
3710 {features});
3711 testAMM(
3712 [&](AMM& amm, Env& env) {
3713 env(rate(gw_, 1.001));
3714 env.close();
3715 env(offer(carol_, XRP(10), USD(5.5)));
3716 env.close();
3717 BEAST_EXPECT(amm.expectBalances(
3718 XRP(990), STAmount{USD, UINT64_C(505'0505050505051), -13}, amm.tokens()));
3719 BEAST_EXPECT(expectOffers(env, carol_, 0));
3720 },
3721 {{XRP(1'000), USD(500)}},
3722 0,
3723 std::nullopt,
3724 {features});
3725 // Multi-path AMM offer
3726 testAMM(
3727 [&](AMM& ammAlice, Env& env) {
3728 Account const ed("ed");
3729 fund(env, gw_, {bob_, ed}, XRP(30'000), {GBP(2'000), EUR(2'000)}, Fund::Acct);
3730 env(rate(gw_, 1.25));
3731 env.close();
3732 // The auto-bridge is worse quality than AMM, is not consumed
3733 // first and initially forces multi-path AMM offer generation.
3734 // Multi-path AMM offers are consumed until their quality
3735 // is less than the auto-bridge offers quality. Auto-bridge
3736 // offers are consumed afterward.
3737 env(offer(bob_, GBP(10), XRP(10)), Txflags(tfPassive));
3738 env(offer(ed, XRP(10), EUR(10)), Txflags(tfPassive));
3739 env.close();
3740 env(offer(carol_, EUR(100), GBP(100)));
3741 env.close();
3742 // After the auto-bridge offers are consumed, single path
3743 // AMM offer is generated with the limit out taking
3744 // into consideration the transfer fee. This results
3745 // in an overall quality offer matching the limit quality
3746 // and the single path AMM offer is consumed.
3747 // Total consumed ~60.68GBP/62.93EUR
3748 BEAST_EXPECT(ammAlice.expectBalances(
3749 STAmount{GBP, UINT64_C(1'060'684828792832), -12},
3750 STAmount{EUR, UINT64_C(1'037'06583722134), -11},
3751 ammAlice.tokens()));
3752 // Consumed offer ~72.93EUR/72.93GBP
3753 BEAST_EXPECT(expectOffers(
3754 env,
3755 carol_,
3756 1,
3757 {Amounts{
3758 STAmount{EUR, UINT64_C(27'06583722134028), -14},
3759 STAmount{GBP, UINT64_C(27'06583722134028), -14}}}));
3760 BEAST_EXPECT(expectOffers(env, bob_, 0));
3761 BEAST_EXPECT(expectOffers(env, ed, 0));
3762
3763 // Initial 30,000 - ~70.68(offers = 60.68(AMM) + 10(LOB))
3764 // * 1.25
3765 // = 88.35 = ~29911.64
3766 // carol_ bought ~72.93EUR at the cost of ~70.68GBP
3767 // the offer is partially consumed
3768 BEAST_EXPECT(
3769 expectHolding(env, carol_, STAmount{GBP, UINT64_C(29'911'64396400896), -11}));
3770 // Initial 30,000 + ~72.93(offers = 62.93(AMM) + 10(LOB))
3771 BEAST_EXPECT(
3772 expectHolding(env, carol_, STAmount{EUR, UINT64_C(30'072'93416277865), -11}));
3773 // Initial 2000 + 10 = 2010
3774 BEAST_EXPECT(expectHolding(env, bob_, GBP(2'010)));
3775 // Initial 2000 - 10 * 1.25 = 1987.5
3776 BEAST_EXPECT(expectHolding(env, ed, EUR(1'987.5)));
3777 },
3778 {{GBP(1'000), EUR(1'100)}},
3779 0,
3780 std::nullopt,
3781 {features});
3782
3783 // Payment and transfer fee
3784 // Scenario:
3785 // Bob sends 125GBP to pay 80EUR to Carol
3786 // Payment execution:
3787 // bob_'s 125GBP/1.25 = 100GBP
3788 // 100GBP/100EUR AMM offer
3789 // 100EUR/1.25 = 80EUR paid to carol_
3790 testAMM(
3791 [&](AMM& ammAlice, Env& env) {
3792 fund(env, gw_, {bob_}, {GBP(200), EUR(200)}, Fund::Acct);
3793 env(rate(gw_, 1.25));
3794 env.close();
3795 env(pay(bob_, carol_, EUR(100)),
3796 Path(~EUR),
3797 Sendmax(GBP(125)),
3798 Txflags(tfPartialPayment));
3799 env.close();
3800 BEAST_EXPECT(ammAlice.expectBalances(GBP(1'100), EUR(1'000), ammAlice.tokens()));
3801 BEAST_EXPECT(expectHolding(env, bob_, GBP(75)));
3802 BEAST_EXPECT(expectHolding(env, carol_, EUR(30'080)));
3803 },
3804 {{GBP(1'000), EUR(1'100)}},
3805 0,
3806 std::nullopt,
3807 {features});
3808
3809 // Payment and transfer fee, multiple steps
3810 // Scenario:
3811 // Dan's offer 200CAN/200GBP
3812 // AMM 1000GBP/10125EUR
3813 // Ed's offer 200EUR/200USD
3814 // Bob sends 195.3125CAN to pay 100USD to Carol
3815 // Payment execution:
3816 // bob_'s 195.3125CAN/1.25 = 156.25CAN -> dan's offer
3817 // 156.25CAN/156.25GBP 156.25GBP/1.25 = 125GBP -> AMM's offer
3818 // 125GBP/125EUR 125EUR/1.25 = 100EUR -> ed's offer
3819 // 100EUR/100USD 100USD/1.25 = 80USD paid to carol_
3820 testAMM(
3821 [&](AMM& ammAlice, Env& env) {
3822 Account const dan("dan");
3823 Account const ed("ed");
3824 auto const can = gw_["CAN"];
3825 fund(env, gw_, {dan}, {can(200), GBP(200)}, Fund::Acct);
3826 fund(env, gw_, {ed}, {EUR(200), USD(200)}, Fund::Acct);
3827 fund(env, gw_, {bob_}, {can(195.3125)}, Fund::Acct);
3828 env(trust(carol_, USD(100)));
3829 env(rate(gw_, 1.25));
3830 env.close();
3831 env(offer(dan, can(200), GBP(200)));
3832 env(offer(ed, EUR(200), USD(200)));
3833 env.close();
3834 env(pay(bob_, carol_, USD(100)),
3835 Path(~GBP, ~EUR, ~USD),
3836 Sendmax(can(195.3125)),
3837 Txflags(tfPartialPayment));
3838 env.close();
3839 BEAST_EXPECT(expectHolding(env, bob_, can(0)));
3840 BEAST_EXPECT(expectHolding(env, dan, can(356.25), GBP(43.75)));
3841 BEAST_EXPECT(ammAlice.expectBalances(GBP(10'125), EUR(10'000), ammAlice.tokens()));
3842 BEAST_EXPECT(expectHolding(env, ed, EUR(300), USD(100)));
3843 BEAST_EXPECT(expectHolding(env, carol_, USD(80)));
3844 },
3845 {{GBP(10'000), EUR(10'125)}},
3846 0,
3847 std::nullopt,
3848 {features});
3849
3850 // Pay amounts close to one side of the pool
3851 testAMM(
3852 [&](AMM& ammAlice, Env& env) {
3853 env(pay(alice_, carol_, USD(99.99)),
3854 Path(~USD),
3855 Sendmax(XRP(1)),
3856 Txflags(tfPartialPayment),
3857 Ter(tesSUCCESS));
3858 env(pay(alice_, carol_, USD(100)),
3859 Path(~USD),
3860 Sendmax(XRP(1)),
3861 Txflags(tfPartialPayment),
3862 Ter(tesSUCCESS));
3863 env(pay(alice_, carol_, XRP(100)),
3864 Path(~XRP),
3865 Sendmax(USD(1)),
3866 Txflags(tfPartialPayment),
3867 Ter(tesSUCCESS));
3868 env(pay(alice_, carol_, STAmount{xrpIssue(), 99'999'900}),
3869 Path(~XRP),
3870 Sendmax(USD(1)),
3871 Txflags(tfPartialPayment),
3872 Ter(tesSUCCESS));
3873 },
3874 {{XRP(100), USD(100)}},
3875 0,
3876 std::nullopt,
3877 {features});
3878
3879 // Multiple paths/steps
3880 {
3881 Env env(*this, features);
3882 auto const eth = gw_["ETH"];
3883 fund(
3884 env,
3885 gw_,
3886 {alice_},
3887 XRP(100'000),
3888 {EUR(50'000), BTC(50'000), eth(50'000), USD(50'000)});
3889 fund(env, gw_, {carol_, bob_}, XRP(1'000), {USD(200)}, Fund::Acct);
3890 AMM const xrpEur(env, alice_, XRP(10'100), EUR(10'000));
3891 AMM const eurBtc(env, alice_, EUR(10'000), BTC(10'200));
3892 AMM const btcUsd(env, alice_, BTC(10'100), USD(10'000));
3893 AMM const xrpUsd(env, alice_, XRP(10'150), USD(10'200));
3894 AMM const xrpEth(env, alice_, XRP(10'000), eth(10'100));
3895 AMM const ethEur(env, alice_, eth(10'900), EUR(11'000));
3896 AMM const eurUsd(env, alice_, EUR(10'100), USD(10'000));
3897 env(pay(bob_, carol_, USD(100)),
3898 Path(~EUR, ~BTC, ~USD),
3899 Path(~USD),
3900 Path(~eth, ~EUR, ~USD),
3901 Sendmax(XRP(200)));
3902 BEAST_EXPECT(xrpEth.expectBalances(
3903 XRPAmount(10'026'208'900),
3904 STAmount{eth, UINT64_C(10'073'65779244461), -11},
3905 xrpEth.tokens()));
3906 BEAST_EXPECT(ethEur.expectBalances(
3907 STAmount{eth, UINT64_C(10'926'34220755539), -11},
3908 STAmount{EUR, UINT64_C(10'973'5423207872), -10},
3909 ethEur.tokens()));
3910 BEAST_EXPECT(eurUsd.expectBalances(
3911 STAmount{EUR, UINT64_C(10'126'4576792128), -10},
3912 STAmount{USD, UINT64_C(9'973'93151712057), -11},
3913 eurUsd.tokens()));
3914 // XRP-USD path
3915 // This path provides ~73.9USD/74.1XRP
3916 BEAST_EXPECT(xrpUsd.expectBalances(
3917 XRPAmount(10'224'106'246),
3918 STAmount{USD, UINT64_C(10'126'06848287943), -11},
3919 xrpUsd.tokens()));
3920
3921 // XRP-EUR-BTC-USD
3922 // This path doesn't provide any liquidity due to how
3923 // offers are generated in multi-path. Analytical solution
3924 // shows a different distribution:
3925 // XRP-EUR-BTC-USD 11.6USD/11.64XRP, XRP-USD 60.7USD/60.8XRP,
3926 // XRP-ETH-EUR-USD 27.6USD/27.6XRP
3927 BEAST_EXPECT(xrpEur.expectBalances(XRP(10'100), EUR(10'000), xrpEur.tokens()));
3928 BEAST_EXPECT(eurBtc.expectBalances(EUR(10'000), BTC(10'200), eurBtc.tokens()));
3929 BEAST_EXPECT(btcUsd.expectBalances(BTC(10'100), USD(10'000), btcUsd.tokens()));
3930
3931 BEAST_EXPECT(expectHolding(env, carol_, USD(300)));
3932 }
3933
3934 // Dependent AMM
3935 {
3936 Env env(*this, features);
3937 auto const eth = gw_["ETH"];
3938 fund(
3939 env,
3940 gw_,
3941 {alice_},
3942 XRP(40'000),
3943 {EUR(50'000), BTC(50'000), eth(50'000), USD(50'000)});
3944 fund(env, gw_, {carol_, bob_}, XRP(1000), {USD(200)}, Fund::Acct);
3945 AMM const xrpEur(env, alice_, XRP(10'100), EUR(10'000));
3946 AMM const eurBtc(env, alice_, EUR(10'000), BTC(10'200));
3947 AMM const btcUsd(env, alice_, BTC(10'100), USD(10'000));
3948 AMM const xrpEth(env, alice_, XRP(10'000), eth(10'100));
3949 AMM const ethEur(env, alice_, eth(10'900), EUR(11'000));
3950 env(pay(bob_, carol_, USD(100)),
3951 Path(~EUR, ~BTC, ~USD),
3952 Path(~eth, ~EUR, ~BTC, ~USD),
3953 Sendmax(XRP(200)));
3954 BEAST_EXPECT(xrpEur.expectBalances(
3955 XRPAmount(10'118'738'472),
3956 STAmount{EUR, UINT64_C(9'981'544436337923), -12},
3957 xrpEur.tokens()));
3958 BEAST_EXPECT(eurBtc.expectBalances(
3959 STAmount{EUR, UINT64_C(10'101'16096785188), -11},
3960 STAmount{BTC, UINT64_C(10'097'91426968059), -11},
3961 eurBtc.tokens()));
3962 BEAST_EXPECT(btcUsd.expectBalances(
3963 STAmount{BTC, UINT64_C(10'202'08573031941), -11}, USD(9'900), btcUsd.tokens()));
3964 BEAST_EXPECT(xrpEth.expectBalances(
3965 XRPAmount(10'082'446'397),
3966 STAmount{eth, UINT64_C(10'017'41072777996), -11},
3967 xrpEth.tokens()));
3968 BEAST_EXPECT(ethEur.expectBalances(
3969 STAmount{eth, UINT64_C(10'982'58927222004), -11},
3970 STAmount{EUR, UINT64_C(10'917'2945958102), -10},
3971 ethEur.tokens()));
3972 BEAST_EXPECT(expectHolding(env, carol_, USD(300)));
3973 }
3974
3975 // AMM offers limit
3976 // Consuming 30 CLOB offers, results in hitting 30 AMM offers limit.
3977 testAMM(
3978 [&](AMM& ammAlice, Env& env) {
3979 env.fund(XRP(1'000), bob_);
3980 fund(env, gw_, {bob_}, {EUR(400)}, Fund::TokenOnly);
3981 env(trust(alice_, EUR(200)));
3982 for (int i = 0; i < 30; ++i)
3983 env(offer(alice_, EUR(1.0 + (0.01 * i)), XRP(1)));
3984 // This is worse quality offer than 30 offers above.
3985 // It will not be consumed because of AMM offers limit.
3986 env(offer(alice_, EUR(140), XRP(100)));
3987 env(pay(bob_, carol_, USD(100)),
3988 Path(~XRP, ~USD),
3989 Sendmax(EUR(400)),
3990 Txflags(tfPartialPayment | tfNoRippleDirect));
3991 BEAST_EXPECT(ammAlice.expectBalances(
3992 XRP(10'030),
3993 STAmount{USD, UINT64_C(9'970'089730807827), -12},
3994 ammAlice.tokens()));
3995 BEAST_EXPECT(
3996 expectHolding(env, carol_, STAmount{USD, UINT64_C(30'029'91026919217), -11}));
3997 BEAST_EXPECT(expectOffers(env, alice_, 1, {{{EUR(140), XRP(100)}}}));
3998 },
3999 std::nullopt,
4000 0,
4001 std::nullopt,
4002 {features});
4003 // This payment is fulfilled
4004 testAMM(
4005 [&](AMM& ammAlice, Env& env) {
4006 env.fund(XRP(1'000), bob_);
4007 fund(env, gw_, {bob_}, {EUR(400)}, Fund::TokenOnly);
4008 env(trust(alice_, EUR(200)));
4009 for (int i = 0; i < 29; ++i)
4010 env(offer(alice_, EUR(1.0 + (0.01 * i)), XRP(1)));
4011 // This is worse quality offer than 30 offers above.
4012 // It will not be consumed because of AMM offers limit.
4013 env(offer(alice_, EUR(140), XRP(100)));
4014 env(pay(bob_, carol_, USD(100)),
4015 Path(~XRP, ~USD),
4016 Sendmax(EUR(400)),
4017 Txflags(tfPartialPayment | tfNoRippleDirect));
4018 BEAST_EXPECT(ammAlice.expectBalances(
4019 XRPAmount{10'101'010'102}, USD(9'900), ammAlice.tokens()));
4020 BEAST_EXPECT(expectHolding(env, carol_, USD(30'100)));
4021 BEAST_EXPECT(expectOffers(
4022 env,
4023 alice_,
4024 1,
4025 {{{STAmount{EUR, UINT64_C(39'1858572), -7}, XRPAmount{27'989'898}}}}));
4026 },
4027 std::nullopt,
4028 0,
4029 std::nullopt,
4030 {features});
4031
4032 // Offer crossing with AMM and another offer. AMM has a better
4033 // quality and is consumed first.
4034 {
4035 Env env(*this, features);
4036 fund(env, gw_, {alice_, carol_, bob_}, XRP(30'000), {USD(30'000)});
4037 env(offer(bob_, XRP(100), USD(100.001)));
4038 AMM const ammAlice(env, alice_, XRP(10'000), USD(10'100));
4039 env(offer(carol_, USD(100), XRP(100)));
4040 BEAST_EXPECT(ammAlice.expectBalances(
4041 XRPAmount{10'049'825'372},
4042 STAmount{USD, UINT64_C(10'049'92587049303), -11},
4043 ammAlice.tokens()));
4044 BEAST_EXPECT(expectOffers(
4045 env,
4046 bob_,
4047 1,
4048 {{{XRPAmount{50'074'628}, STAmount{USD, UINT64_C(50'07512950697), -11}}}}));
4049 BEAST_EXPECT(expectHolding(env, carol_, USD(30'100)));
4050 }
4051
4052 // Individually frozen account
4053 testAMM(
4054 [&](AMM& ammAlice, Env& env) {
4055 env(trust(gw_, carol_["USD"](0), tfSetFreeze));
4056 env(trust(gw_, alice_["USD"](0), tfSetFreeze));
4057 env.close();
4058 env(pay(alice_, carol_, USD(1)),
4059 Path(~USD),
4060 Sendmax(XRP(10)),
4061 Txflags(tfNoRippleDirect | tfPartialPayment),
4062 Ter(tesSUCCESS));
4063 },
4064 std::nullopt,
4065 0,
4066 std::nullopt,
4067 {features});
4068 }
4069
4070 void
4072 {
4073 testcase("AMM Tokens");
4074 using namespace jtx;
4075
4076 // Offer crossing with AMM LPTokens and XRP.
4077 testAMM([&](AMM& ammAlice, Env& env) {
4078 auto const baseFee = env.current()->fees().base.drops();
4079 auto const token1 = ammAlice.lptIssue();
4080 auto priceXRP = ammAssetOut(
4081 STAmount{XRPAmount{10'000'000'000}},
4082 STAmount{token1, 10'000'000},
4083 STAmount{token1, 5'000'000},
4084 0);
4085 // Carol places an order to buy LPTokens
4086 env(offer(carol_, STAmount{token1, 5'000'000}, priceXRP));
4087 // Alice places an order to sell LPTokens
4088 env(offer(alice_, priceXRP, STAmount{token1, 5'000'000}));
4089 // Pool's LPTokens balance doesn't change
4090 BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000}));
4091 // Carol is Liquidity Provider
4092 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{5'000'000}));
4093 BEAST_EXPECT(ammAlice.expectLPTokens(alice_, IOUAmount{5'000'000}));
4094 // Carol votes
4095 ammAlice.vote(carol_, 1'000);
4096 BEAST_EXPECT(ammAlice.expectTradingFee(500));
4097 ammAlice.vote(carol_, 0);
4098 BEAST_EXPECT(ammAlice.expectTradingFee(0));
4099 // Carol bids
4100 env(ammAlice.bid({.account = carol_, .bidMin = 100}));
4101 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{4'999'900}));
4102 BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{100}));
4103 BEAST_EXPECT(
4104 accountBalance(env, carol_) == std::to_string(22500000000 - (4 * baseFee)));
4105 priceXRP = ammAssetOut(
4106 STAmount{XRPAmount{10'000'000'000}},
4107 STAmount{token1, 9'999'900},
4108 STAmount{token1, 4'999'900},
4109 0);
4110 // Carol withdraws
4111 ammAlice.withdrawAll(carol_, XRP(0));
4112 BEAST_EXPECT(
4113 accountBalance(env, carol_) == std::to_string(29999949999 - (5 * baseFee)));
4114 BEAST_EXPECT(ammAlice.expectBalances(
4115 XRPAmount{10'000'000'000} - priceXRP, USD(10'000), IOUAmount{5'000'000}));
4116 BEAST_EXPECT(ammAlice.expectLPTokens(alice_, IOUAmount{5'000'000}));
4117 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0}));
4118 });
4119
4120 // Offer crossing with two AMM LPTokens.
4121 testAMM([&](AMM& ammAlice, Env& env) {
4122 ammAlice.deposit(carol_, 1'000'000);
4123 fund(env, gw_, {alice_, carol_}, {EUR(10'000)}, Fund::TokenOnly);
4124 AMM ammAlice1(env, alice_, XRP(10'000), EUR(10'000));
4125 ammAlice1.deposit(carol_, 1'000'000);
4126 auto const token1 = ammAlice.lptIssue();
4127 auto const token2 = ammAlice1.lptIssue();
4128 env(offer(alice_, STAmount{token1, 100}, STAmount{token2, 100}), Txflags(tfPassive));
4129 env.close();
4130 BEAST_EXPECT(expectOffers(env, alice_, 1));
4131 env(offer(carol_, STAmount{token2, 100}, STAmount{token1, 100}));
4132 env.close();
4133 BEAST_EXPECT(
4134 expectHolding(env, alice_, STAmount{token1, 10'000'100}) &&
4135 expectHolding(env, alice_, STAmount{token2, 9'999'900}));
4136 BEAST_EXPECT(
4137 expectHolding(env, carol_, STAmount{token2, 1'000'100}) &&
4138 expectHolding(env, carol_, STAmount{token1, 999'900}));
4139 BEAST_EXPECT(expectOffers(env, alice_, 0) && expectOffers(env, carol_, 0));
4140 });
4141
4142 // LPs pay LPTokens directly. Must trust set because the trust line
4143 // is checked for the limit, which is 0 in the AMM auto-created
4144 // trust line.
4145 testAMM([&](AMM& ammAlice, Env& env) {
4146 auto const token1 = ammAlice.lptIssue();
4147 env.trust(STAmount{token1, 2'000'000}, carol_);
4148 env.close();
4149 ammAlice.deposit(carol_, 1'000'000);
4150 BEAST_EXPECT(
4151 ammAlice.expectLPTokens(alice_, IOUAmount{10'000'000, 0}) &&
4152 ammAlice.expectLPTokens(carol_, IOUAmount{1'000'000, 0}));
4153 // Pool balance doesn't change, only tokens moved from
4154 // one line to another.
4155 env(pay(alice_, carol_, STAmount{token1, 100}));
4156 env.close();
4157 BEAST_EXPECT(
4158 // Alice initial token1 10,000,000 - 100
4159 ammAlice.expectLPTokens(alice_, IOUAmount{9'999'900, 0}) &&
4160 // Carol initial token1 1,000,000 + 100
4161 ammAlice.expectLPTokens(carol_, IOUAmount{1'000'100, 0}));
4162
4163 env.trust(STAmount{token1, 20'000'000}, alice_);
4164 env.close();
4165 env(pay(carol_, alice_, STAmount{token1, 100}));
4166 env.close();
4167 // Back to the original balance
4168 BEAST_EXPECT(
4169 ammAlice.expectLPTokens(alice_, IOUAmount{10'000'000, 0}) &&
4170 ammAlice.expectLPTokens(carol_, IOUAmount{1'000'000, 0}));
4171 });
4172 }
4173
4174 void
4176 {
4177 testcase("Flags");
4178 using namespace jtx;
4179
4180 testAMM([&](AMM& ammAlice, Env& env) {
4181 auto const info = env.rpc(
4182 "json",
4183 "account_info",
4184 std::string(R"({"account": ")" + to_string(ammAlice.ammAccount()) + "\"}"));
4185 auto const flags = info[jss::result][jss::account_data][jss::Flags].asUInt();
4186 BEAST_EXPECT(flags == (lsfDisableMaster | lsfDefaultRipple | lsfDepositAuth));
4187 });
4188 }
4189
4190 void
4192 {
4193 testcase("Rippling");
4194 using namespace jtx;
4195
4196 // Rippling via AMM fails because AMM trust line has 0 limit.
4197 // Set up two issuers, A and B. Have each issue a token called TST.
4198 // Have another account C hold TST from both issuers,
4199 // and create an AMM for this pair.
4200 // Have a fourth account, D, create a trust line to the AMM for TST.
4201 // Send a payment delivering TST.AMM from C to D, using SendMax in
4202 // TST.A (or B) and a path through the AMM account. By normal
4203 // rippling rules, this would have caused the AMM's balances
4204 // to shift at a 1:1 rate with no fee applied has it not been
4205 // for 0 limit.
4206 {
4207 Env env(*this);
4208 auto const a = Account("A");
4209 auto const b = Account("B");
4210 auto const tsta = a["TST"];
4211 auto const tstb = b["TST"];
4212 auto const c = Account("C");
4213 auto const d = Account("D");
4214
4215 env.fund(XRP(10'000), a);
4216 env.fund(XRP(10'000), b);
4217 env.fund(XRP(10'000), c);
4218 env.fund(XRP(10'000), d);
4219
4220 env.trust(tsta(10'000), c);
4221 env.trust(tstb(10'000), c);
4222 env(pay(a, c, tsta(10'000)));
4223 env(pay(b, c, tstb(10'000)));
4224 AMM const amm(env, c, tsta(5'000), tstb(5'000));
4225 auto const ammIss = Issue(tsta.currency, amm.ammAccount());
4226
4227 // Can TrustSet only for AMM LP tokens
4228 env(trust(d, STAmount{ammIss, 10'000}), Ter(tecNO_PERMISSION));
4229 env.close();
4230
4231 // The payment would fail because of above, but check just in case
4232 env(pay(c, d, STAmount{ammIss, 10}),
4233 Sendmax(tsta(100)),
4234 Path(amm.ammAccount()),
4235 Txflags(tfPartialPayment | tfNoRippleDirect),
4236 Ter(tecPATH_DRY));
4237 }
4238 }
4239
4240 void
4242 {
4243 testcase("AMMAndCLOB, offer quality change");
4244 using namespace jtx;
4245 auto const gw = Account("gw");
4246 auto const tst = gw["TST"];
4247 auto const lP1 = Account("LP1");
4248 auto const lP2 = Account("LP2");
4249
4250 auto const prep = [&](auto const& offerCb, auto const& expectCb) {
4251 Env env(*this, features);
4252 env.fund(XRP(30'000'000'000), gw);
4253 env(offer(gw, XRP(11'500'000'000), tst(1'000'000'000)));
4254
4255 env.fund(XRP(10'000), lP1);
4256 env.fund(XRP(10'000), lP2);
4257 env(offer(lP1, tst(25), XRPAmount(287'500'000)));
4258
4259 // Either AMM or CLOB offer
4260 offerCb(env);
4261
4262 env(offer(lP2, tst(25), XRPAmount(287'500'000)));
4263
4264 expectCb(env);
4265 };
4266
4267 // If we replace AMM with an equivalent CLOB offer, which AMM generates
4268 // when it is consumed, then the result must be equivalent, too.
4269 std::string lp2TSTBalance;
4270 std::string lp2TakerGets;
4271 std::string lp2TakerPays;
4272 // Execute with AMM first
4273 prep(
4274 [&](Env& env) { AMM const amm(env, lP1, tst(25), XRP(250)); },
4275 [&](Env& env) {
4276 lp2TSTBalance = getAccountLines(env, lP2, tst)["lines"][0u]["balance"].asString();
4277 auto const offer = getAccountOffers(env, lP2)["offers"][0u];
4278 lp2TakerGets = offer["taker_gets"].asString();
4279 lp2TakerPays = offer["taker_pays"]["value"].asString();
4280 });
4281 // Execute with CLOB offer
4282 prep(
4283 [&](Env& env) {
4284 env(offer(
4285 lP1, XRPAmount{18'095'132}, STAmount{tst, UINT64_C(1'68737976189735), -14}),
4286 Txflags(tfPassive));
4287 },
4288 [&](Env& env) {
4289 BEAST_EXPECT(
4290 lp2TSTBalance ==
4291 getAccountLines(env, lP2, tst)["lines"][0u]["balance"].asString());
4292 auto const offer = getAccountOffers(env, lP2)["offers"][0u];
4293 BEAST_EXPECT(lp2TakerGets == offer["taker_gets"].asString());
4294 BEAST_EXPECT(lp2TakerPays == offer["taker_pays"]["value"].asString());
4295 });
4296 }
4297
4298 void
4300 {
4301 testcase("Trading Fee");
4302 using namespace jtx;
4303
4304 // Single Deposit, 1% fee
4305 testAMM(
4306 [&](AMM& ammAlice, Env& env) {
4307 // No fee
4308 ammAlice.deposit(carol_, USD(3'000));
4309 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{1'000}));
4310 ammAlice.withdrawAll(carol_, USD(3'000));
4311 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{0}));
4312 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000)));
4313 // Set fee to 1%
4314 ammAlice.vote(alice_, 1'000);
4315 BEAST_EXPECT(ammAlice.expectTradingFee(1'000));
4316 // Carol gets fewer LPToken ~994, because of the single deposit
4317 // fee
4318 ammAlice.deposit(carol_, USD(3'000));
4319 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{994'981155689671, -12}));
4320 BEAST_EXPECT(expectHolding(env, carol_, USD(27'000)));
4321 // Set fee to 0
4322 ammAlice.vote(alice_, 0);
4323 ammAlice.withdrawAll(carol_, USD(0));
4324 // Carol gets back less than the original deposit
4325 BEAST_EXPECT(
4326 expectHolding(env, carol_, STAmount{USD, UINT64_C(29'994'96220068281), -11}));
4327 },
4328 {{USD(1'000), EUR(1'000)}},
4329 0,
4330 std::nullopt,
4331 {features});
4332
4333 // Single deposit with EP not exceeding specified:
4334 // 100USD with EP not to exceed 0.1 (AssetIn/TokensOut). 1% fee.
4335 testAMM(
4336 [&](AMM& ammAlice, Env& env) {
4337 auto const balance = env.balance(carol_, USD);
4338 auto const tokensFee =
4339 ammAlice.deposit(carol_, USD(1'000), std::nullopt, STAmount{USD, 1, -1});
4340 auto const deposit = balance - env.balance(carol_, USD);
4341 ammAlice.withdrawAll(carol_, USD(0));
4342 ammAlice.vote(alice_, 0);
4343 BEAST_EXPECT(ammAlice.expectTradingFee(0));
4344 auto const tokensNoFee = ammAlice.deposit(carol_, deposit);
4345 // carol_ pays ~2008 LPTokens in fees or ~0.5% of the no-fee
4346 // LPTokens
4347 BEAST_EXPECT(tokensFee == IOUAmount(485'636'0611129, -7));
4348 BEAST_EXPECT(tokensNoFee == IOUAmount(487'644'85901109, -8));
4349 },
4350 std::nullopt,
4351 1'000,
4352 std::nullopt,
4353 {features});
4354
4355 // Single deposit with EP not exceeding specified:
4356 // 200USD with EP not to exceed 0.002020 (AssetIn/TokensOut). 1% fee
4357 testAMM(
4358 [&](AMM& ammAlice, Env& env) {
4359 auto const balance = env.balance(carol_, USD);
4360 auto const tokensFee =
4361 ammAlice.deposit(carol_, USD(200), std::nullopt, STAmount{USD, 2020, -6});
4362 auto const deposit = balance - env.balance(carol_, USD);
4363 ammAlice.withdrawAll(carol_, USD(0));
4364 ammAlice.vote(alice_, 0);
4365 BEAST_EXPECT(ammAlice.expectTradingFee(0));
4366 auto const tokensNoFee = ammAlice.deposit(carol_, deposit);
4367 // carol_ pays ~475 LPTokens in fees or ~0.5% of the no-fee
4368 // LPTokens
4369 BEAST_EXPECT(tokensFee == IOUAmount(98'000'00000002, -8));
4370 BEAST_EXPECT(tokensNoFee == IOUAmount(98'475'81871545, -8));
4371 },
4372 std::nullopt,
4373 1'000,
4374 std::nullopt,
4375 {features});
4376
4377 // Single Withdrawal, 1% fee
4378 testAMM(
4379 [&](AMM& ammAlice, Env& env) {
4380 // No fee
4381 ammAlice.deposit(carol_, USD(3'000));
4382
4383 BEAST_EXPECT(ammAlice.expectLPTokens(carol_, IOUAmount{1'000}));
4384 BEAST_EXPECT(expectHolding(env, carol_, USD(27'000)));
4385 // Set fee to 1%
4386 ammAlice.vote(alice_, 1'000);
4387 BEAST_EXPECT(ammAlice.expectTradingFee(1'000));
4388 // Single withdrawal. Carol gets ~5USD less than deposited.
4389 ammAlice.withdrawAll(carol_, USD(0));
4390 BEAST_EXPECT(
4391 expectHolding(env, carol_, STAmount{USD, UINT64_C(29'994'97487437186), -11}));
4392 },
4393 {{USD(1'000), EUR(1'000)}},
4394 0,
4395 std::nullopt,
4396 {features});
4397
4398 // Withdraw with EPrice limit, 1% fee.
4399 testAMM(
4400 [&](AMM& ammAlice, Env& env) {
4401 ammAlice.deposit(carol_, 1'000'000);
4402 auto const tokensFee =
4403 ammAlice.withdraw(carol_, USD(100), std::nullopt, IOUAmount{520, 0});
4404 // carol_ withdraws ~1,443.44USD
4405 auto const balanceAfterWithdraw = [&] {
4406 if (!features[fixAMMv1_3])
4407 {
4408 return STAmount(USD, UINT64_C(30'443'43891402714), -11);
4409 }
4410
4411 return STAmount(USD, UINT64_C(30'443'43891402713), -11);
4412 }();
4413 BEAST_EXPECT(env.balance(carol_, USD) == balanceAfterWithdraw);
4414 // Set to original pool size
4415 auto const deposit = balanceAfterWithdraw - USD(29'000);
4416 ammAlice.deposit(carol_, deposit);
4417 // fee 0%
4418 ammAlice.vote(alice_, 0);
4419 BEAST_EXPECT(ammAlice.expectTradingFee(0));
4420 auto const tokensNoFee = ammAlice.withdraw(carol_, deposit);
4421 if (!features[fixAMMv1_3])
4422 {
4423 BEAST_EXPECT(
4424 env.balance(carol_, USD) ==
4425 STAmount(USD, UINT64_C(30'443'43891402716), -11));
4426 }
4427 else
4428 {
4429 BEAST_EXPECT(
4430 env.balance(carol_, USD) ==
4431 STAmount(USD, UINT64_C(30'443'43891402713), -11));
4432 }
4433 // carol_ pays ~4008 LPTokens in fees or ~0.5% of the no-fee
4434 // LPTokens
4435 if (!features[fixAMMv1_3])
4436 {
4437 BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779912, -8));
4438 }
4439 else
4440 {
4441 BEAST_EXPECT(tokensNoFee == IOUAmount(746'579'80779911, -8));
4442 }
4443 BEAST_EXPECT(tokensFee == IOUAmount(750'588'23529411, -8));
4444 },
4445 std::nullopt,
4446 1'000,
4447 std::nullopt,
4448 {features});
4449
4450 // Payment, 1% fee
4451 testAMM(
4452 [&](AMM& ammAlice, Env& env) {
4453 fund(env, gw_, {bob_}, XRP(1'000), {USD(1'000), EUR(1'000)}, Fund::Acct);
4454 // Alice contributed 1010EUR and 1000USD to the pool
4455 BEAST_EXPECT(expectHolding(env, alice_, EUR(28'990)));
4456 BEAST_EXPECT(expectHolding(env, alice_, USD(29'000)));
4457 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000)));
4458 // Carol pays to Alice with no fee
4459 env(pay(carol_, alice_, EUR(10)),
4460 Path(~EUR),
4461 Sendmax(USD(10)),
4462 Txflags(tfNoRippleDirect));
4463 env.close();
4464 // Alice has 10EUR more and Carol has 10USD less
4465 BEAST_EXPECT(expectHolding(env, alice_, EUR(29'000)));
4466 BEAST_EXPECT(expectHolding(env, alice_, USD(29'000)));
4467 BEAST_EXPECT(expectHolding(env, carol_, USD(29'990)));
4468
4469 // Set fee to 1%
4470 ammAlice.vote(alice_, 1'000);
4471 BEAST_EXPECT(ammAlice.expectTradingFee(1'000));
4472 // Bob pays to Carol with 1% fee
4473 env(pay(bob_, carol_, USD(10)),
4474 Path(~USD),
4475 Sendmax(EUR(15)),
4476 Txflags(tfNoRippleDirect));
4477 env.close();
4478 // Bob sends 10.1~EUR to pay 10USD
4479 BEAST_EXPECT(
4480 expectHolding(env, bob_, STAmount{EUR, UINT64_C(989'8989898989899), -13}));
4481 // Carol got 10USD
4482 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000)));
4483 BEAST_EXPECT(ammAlice.expectBalances(
4484 USD(1'000),
4485 STAmount{EUR, UINT64_C(1'010'10101010101), -11},
4486 ammAlice.tokens()));
4487 },
4488 {{USD(1'000), EUR(1'010)}},
4489 0,
4490 std::nullopt,
4491 {features});
4492
4493 // Offer crossing, 0.5% fee
4494 testAMM(
4495 [&](AMM& ammAlice, Env& env) {
4496 // No fee
4497 env(offer(carol_, EUR(10), USD(10)));
4498 env.close();
4499 BEAST_EXPECT(expectHolding(env, carol_, USD(29'990)));
4500 BEAST_EXPECT(expectHolding(env, carol_, EUR(30'010)));
4501 // Change pool composition back
4502 env(offer(carol_, USD(10), EUR(10)));
4503 env.close();
4504 // Set fee to 0.5%
4505 ammAlice.vote(alice_, 500);
4506 BEAST_EXPECT(ammAlice.expectTradingFee(500));
4507 env(offer(carol_, EUR(10), USD(10)));
4508 env.close();
4509 // Alice gets fewer ~4.97EUR for ~5.02USD, the difference goes
4510 // to the pool
4511 BEAST_EXPECT(
4512 expectHolding(env, carol_, STAmount{USD, UINT64_C(29'995'02512562814), -11}));
4513 BEAST_EXPECT(
4514 expectHolding(env, carol_, STAmount{EUR, UINT64_C(30'004'97487437186), -11}));
4515 BEAST_EXPECT(expectOffers(
4516 env,
4517 carol_,
4518 1,
4519 {{Amounts{
4520 STAmount{EUR, UINT64_C(5'025125628140703), -15},
4521 STAmount{USD, UINT64_C(5'025125628140703), -15}}}}));
4522 BEAST_EXPECT(ammAlice.expectBalances(
4523 STAmount{USD, UINT64_C(1'004'97487437186), -11},
4524 STAmount{EUR, UINT64_C(1'005'025125628141), -12},
4525 ammAlice.tokens()));
4526 },
4527 {{USD(1'000), EUR(1'010)}},
4528 0,
4529 std::nullopt,
4530 {features});
4531
4532 // Payment with AMM and CLOB offer, 0 fee
4533 // AMM liquidity is consumed first up to CLOB offer quality
4534 // CLOB offer is fully consumed next
4535 // Remaining amount is consumed via AMM liquidity
4536 {
4537 Env env(*this, features);
4538 Account const ed("ed");
4539 fund(env, gw_, {alice_, bob_, carol_, ed}, XRP(1'000), {USD(2'000), EUR(2'000)});
4540 env(offer(carol_, EUR(5), USD(5)));
4541 AMM const ammAlice(env, alice_, USD(1'005), EUR(1'000));
4542 env(pay(bob_, ed, USD(10)), Path(~USD), Sendmax(EUR(15)), Txflags(tfNoRippleDirect));
4543 BEAST_EXPECT(expectHolding(env, ed, USD(2'010)));
4544 BEAST_EXPECT(expectHolding(env, bob_, STAmount(EUR, UINT64_C(1989'999999999999), -12)));
4545 BEAST_EXPECT(ammAlice.expectBalances(
4546 USD(1'000), STAmount(EUR, UINT64_C(1005'000000000001), -12), ammAlice.tokens()));
4547 BEAST_EXPECT(expectOffers(env, carol_, 0));
4548 }
4549
4550 // Payment with AMM and CLOB offer. Same as above but with 0.25%
4551 // fee.
4552 {
4553 Env env(*this, features);
4554 Account const ed("ed");
4555 fund(env, gw_, {alice_, bob_, carol_, ed}, XRP(1'000), {USD(2'000), EUR(2'000)});
4556 env(offer(carol_, EUR(5), USD(5)));
4557 // Set 0.25% fee
4558 AMM const ammAlice(env, alice_, USD(1'005), EUR(1'000), false, 250);
4559 env(pay(bob_, ed, USD(10)), Path(~USD), Sendmax(EUR(15)), Txflags(tfNoRippleDirect));
4560 BEAST_EXPECT(expectHolding(env, ed, USD(2'010)));
4561 BEAST_EXPECT(
4562 expectHolding(env, bob_, STAmount{EUR, UINT64_C(1'989'987453007628), -12}));
4563 BEAST_EXPECT(ammAlice.expectBalances(
4564 USD(1'000), STAmount{EUR, UINT64_C(1'005'012546992372), -12}, ammAlice.tokens()));
4565 BEAST_EXPECT(expectOffers(env, carol_, 0));
4566 }
4567
4568 // Payment with AMM and CLOB offer. AMM has a better
4569 // spot price quality, but 1% fee offsets that. As the result
4570 // the entire trade is executed via LOB.
4571 {
4572 Env env(*this, features);
4573 Account const ed("ed");
4574 fund(env, gw_, {alice_, bob_, carol_, ed}, XRP(1'000), {USD(2'000), EUR(2'000)});
4575 env(offer(carol_, EUR(10), USD(10)));
4576 // Set 1% fee
4577 AMM const ammAlice(env, alice_, USD(1'005), EUR(1'000), false, 1'000);
4578 env(pay(bob_, ed, USD(10)), Path(~USD), Sendmax(EUR(15)), Txflags(tfNoRippleDirect));
4579 BEAST_EXPECT(expectHolding(env, ed, USD(2'010)));
4580 BEAST_EXPECT(expectHolding(env, bob_, EUR(1'990)));
4581 BEAST_EXPECT(ammAlice.expectBalances(USD(1'005), EUR(1'000), ammAlice.tokens()));
4582 BEAST_EXPECT(expectOffers(env, carol_, 0));
4583 }
4584
4585 // Payment with AMM and CLOB offer. AMM has a better
4586 // spot price quality, but 1% fee offsets that.
4587 // The CLOB offer is consumed first and the remaining
4588 // amount is consumed via AMM liquidity.
4589 {
4590 Env env(*this, features);
4591 Account const ed("ed");
4592 fund(env, gw_, {alice_, bob_, carol_, ed}, XRP(1'000), {USD(2'000), EUR(2'000)});
4593 env(offer(carol_, EUR(9), USD(9)));
4594 // Set 1% fee
4595 AMM const ammAlice(env, alice_, USD(1'005), EUR(1'000), false, 1'000);
4596 env(pay(bob_, ed, USD(10)), Path(~USD), Sendmax(EUR(15)), Txflags(tfNoRippleDirect));
4597 BEAST_EXPECT(expectHolding(env, ed, USD(2'010)));
4598 BEAST_EXPECT(
4599 expectHolding(env, bob_, STAmount{EUR, UINT64_C(1'989'993923296712), -12}));
4600 BEAST_EXPECT(ammAlice.expectBalances(
4601 USD(1'004), STAmount{EUR, UINT64_C(1'001'006076703288), -12}, ammAlice.tokens()));
4602 BEAST_EXPECT(expectOffers(env, carol_, 0));
4603 }
4604 }
4605
4606 void
4608 {
4609 testcase("Adjusted Deposit/Withdraw Tokens");
4610
4611 using namespace jtx;
4612
4613 // Deposit/Withdraw in USD
4614 testAMM(
4615 [&](AMM& ammAlice, Env& env) {
4616 Account const bob("bob");
4617 Account const ed("ed");
4618 Account const paul("paul");
4619 Account const dan("dan");
4620 Account const chris("chris");
4621 Account const simon("simon");
4622 Account const ben("ben");
4623 Account const natalie("natalie");
4624 fund(
4625 env,
4626 gw_,
4627 {bob, ed, paul, dan, chris, simon, ben, natalie},
4628 {USD(1'500'000)},
4629 Fund::Acct);
4630 for (int i = 0; i < 10; ++i)
4631 {
4632 ammAlice.deposit(ben, STAmount{USD, 1, -10});
4633 ammAlice.withdrawAll(ben, USD(0));
4634 ammAlice.deposit(simon, USD(0.1));
4635 ammAlice.withdrawAll(simon, USD(0));
4636 ammAlice.deposit(chris, USD(1));
4637 ammAlice.withdrawAll(chris, USD(0));
4638 ammAlice.deposit(dan, USD(10));
4639 ammAlice.withdrawAll(dan, USD(0));
4640 ammAlice.deposit(bob, USD(100));
4641 ammAlice.withdrawAll(bob, USD(0));
4642 ammAlice.deposit(carol_, USD(1'000));
4643 ammAlice.withdrawAll(carol_, USD(0));
4644 ammAlice.deposit(ed, USD(10'000));
4645 ammAlice.withdrawAll(ed, USD(0));
4646 ammAlice.deposit(paul, USD(100'000));
4647 ammAlice.withdrawAll(paul, USD(0));
4648 ammAlice.deposit(natalie, USD(1'000'000));
4649 ammAlice.withdrawAll(natalie, USD(0));
4650 }
4651 // Due to round off some accounts have a tiny gain, while
4652 // other have a tiny loss. The last account to withdraw
4653 // gets everything in the pool.
4654 if (features[fixAMMv1_3])
4655 {
4656 BEAST_EXPECT(ammAlice.expectBalances(
4657 XRP(10'000),
4658 STAmount{USD, UINT64_C(10'000'0000000003), -10},
4659 IOUAmount{10'000'000}));
4660 }
4661 else
4662 {
4663 BEAST_EXPECT(
4664 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000}));
4665 }
4666 BEAST_EXPECT(expectHolding(env, ben, USD(1'500'000)));
4667 BEAST_EXPECT(expectHolding(env, simon, USD(1'500'000)));
4668 BEAST_EXPECT(expectHolding(env, chris, USD(1'500'000)));
4669 BEAST_EXPECT(expectHolding(env, dan, USD(1'500'000)));
4670 BEAST_EXPECT(expectHolding(env, carol_, USD(30'000)));
4671 BEAST_EXPECT(expectHolding(env, ed, USD(1'500'000)));
4672 BEAST_EXPECT(expectHolding(env, paul, USD(1'500'000)));
4673 if (!features[fixAMMv1_3])
4674 {
4675 BEAST_EXPECT(expectHolding(
4676 env, natalie, STAmount{USD, UINT64_C(1'500'000'000000005), -9}));
4677 }
4678 else
4679 {
4680 BEAST_EXPECT(expectHolding(env, natalie, USD(1'500'000)));
4681 }
4682 ammAlice.withdrawAll(alice_);
4683 BEAST_EXPECT(!ammAlice.ammExists());
4684 if (features[fixAMMv1_3])
4685 {
4686 BEAST_EXPECT(expectHolding(
4687 env, alice_, STAmount{USD, UINT64_C(30'000'0000000003), -10}));
4688 }
4689 else
4690 {
4691 BEAST_EXPECT(expectHolding(env, alice_, USD(30'000)));
4692 }
4693 // alice_ XRP balance is 30,000 initial - 50 AMMCreate fee -
4694 // 10drops fee
4695 BEAST_EXPECT(
4696 accountBalance(env, alice_) ==
4697 std::to_string(29950000000 - env.current()->fees().base.drops()));
4698 },
4699 std::nullopt,
4700 0,
4701 std::nullopt,
4702 {features});
4703
4704 // Same as above but deposit/withdraw in XRP
4705 testAMM(
4706 [&](AMM& ammAlice, Env& env) {
4707 Account const bob("bob");
4708 Account const ed("ed");
4709 Account const paul("paul");
4710 Account const dan("dan");
4711 Account const chris("chris");
4712 Account const simon("simon");
4713 Account const ben("ben");
4714 Account const natalie("natalie");
4715 fund(
4716 env,
4717 gw_,
4718 {bob, ed, paul, dan, chris, simon, ben, natalie},
4719 XRP(2'000'000),
4720 {},
4721 Fund::Acct);
4722 for (int i = 0; i < 10; ++i)
4723 {
4724 ammAlice.deposit(ben, XRPAmount{1});
4725 ammAlice.withdrawAll(ben, XRP(0));
4726 ammAlice.deposit(simon, XRPAmount(1'000));
4727 ammAlice.withdrawAll(simon, XRP(0));
4728 ammAlice.deposit(chris, XRP(1));
4729 ammAlice.withdrawAll(chris, XRP(0));
4730 ammAlice.deposit(dan, XRP(10));
4731 ammAlice.withdrawAll(dan, XRP(0));
4732 ammAlice.deposit(bob, XRP(100));
4733 ammAlice.withdrawAll(bob, XRP(0));
4734 ammAlice.deposit(carol_, XRP(1'000));
4735 ammAlice.withdrawAll(carol_, XRP(0));
4736 ammAlice.deposit(ed, XRP(10'000));
4737 ammAlice.withdrawAll(ed, XRP(0));
4738 ammAlice.deposit(paul, XRP(100'000));
4739 ammAlice.withdrawAll(paul, XRP(0));
4740 ammAlice.deposit(natalie, XRP(1'000'000));
4741 ammAlice.withdrawAll(natalie, XRP(0));
4742 }
4743 auto const baseFee = env.current()->fees().base.drops();
4744 if (!features[fixAMMv1_3])
4745 {
4746 // No round off with XRP in this test
4747 BEAST_EXPECT(
4748 ammAlice.expectBalances(XRP(10'000), USD(10'000), IOUAmount{10'000'000}));
4749 ammAlice.withdrawAll(alice_);
4750 BEAST_EXPECT(!ammAlice.ammExists());
4751 // 20,000 initial - (deposit+withdraw) * 10
4752 auto const xrpBalance = (XRP(2'000'000) - txFee(env, 20)).getText();
4753 BEAST_EXPECT(accountBalance(env, ben) == xrpBalance);
4754 BEAST_EXPECT(accountBalance(env, simon) == xrpBalance);
4755 BEAST_EXPECT(accountBalance(env, chris) == xrpBalance);
4756 BEAST_EXPECT(accountBalance(env, dan) == xrpBalance);
4757
4758 // 30,000 initial - (deposit+withdraw) * 10
4759 BEAST_EXPECT(
4760 accountBalance(env, carol_) ==
4761 std::to_string(30'000'000'000 - (20 * baseFee)));
4762 BEAST_EXPECT(accountBalance(env, ed) == xrpBalance);
4763 BEAST_EXPECT(accountBalance(env, paul) == xrpBalance);
4764 BEAST_EXPECT(accountBalance(env, natalie) == xrpBalance);
4765 // 30,000 initial - 50 AMMCreate fee - 10drops withdraw fee
4766 BEAST_EXPECT(
4767 accountBalance(env, alice_) == std::to_string(29'950'000'000 - baseFee));
4768 }
4769 else
4770 {
4771 // post-amendment the rounding takes place to ensure
4772 // AMM invariant
4773 BEAST_EXPECT(ammAlice.expectBalances(
4774 XRPAmount(10'000'000'080), USD(10'000), IOUAmount{10'000'000}));
4775 ammAlice.withdrawAll(alice_);
4776 BEAST_EXPECT(!ammAlice.ammExists());
4777 auto const xrpBalance = XRP(2'000'000) - txFee(env, 20) - drops(10);
4778 auto const xrpBalanceText = xrpBalance.getText();
4779 BEAST_EXPECT(accountBalance(env, ben) == xrpBalanceText);
4780 BEAST_EXPECT(accountBalance(env, simon) == xrpBalanceText);
4781 BEAST_EXPECT(accountBalance(env, chris) == xrpBalanceText);
4782 BEAST_EXPECT(accountBalance(env, dan) == xrpBalanceText);
4783 BEAST_EXPECT(
4784 accountBalance(env, carol_) ==
4785 std::to_string(30'000'000'000 - (20 * baseFee) - 10));
4786 BEAST_EXPECT(accountBalance(env, ed) == (xrpBalance + drops(2)).getText());
4787 BEAST_EXPECT(accountBalance(env, paul) == (xrpBalance + drops(3)).getText());
4788 BEAST_EXPECT(accountBalance(env, natalie) == (xrpBalance + drops(5)).getText());
4789 BEAST_EXPECT(
4790 accountBalance(env, alice_) ==
4791 std::to_string(29'950'000'000 - baseFee + 80));
4792 }
4793 },
4794 std::nullopt,
4795 0,
4796 std::nullopt,
4797 {features});
4798 }
4799
4800 void
4802 {
4803 testcase("Auto Delete");
4804
4805 using namespace jtx;
4806 FeatureBitset const all{testableAmendments()};
4807
4808 {
4809 Env env(
4810 *this,
4812 cfg->fees.referenceFee = XRPAmount(1);
4813 return cfg;
4814 }),
4815 all);
4816 fund(env, gw_, {alice_}, XRP(20'000), {USD(10'000)});
4817 AMM amm(env, gw_, XRP(10'000), USD(10'000));
4818 for (auto i = 0; i < kMaxDeletableAmmTrustLines + 10; ++i)
4819 {
4820 Account const a{std::to_string(i)};
4821 env.fund(XRP(1'000), a);
4822 env(trust(a, STAmount{amm.lptIssue(), 10'000}));
4823 env.close();
4824 }
4825 // The trustlines are partially deleted,
4826 // AMM is set to an empty state.
4827 amm.withdrawAll(gw_);
4828 BEAST_EXPECT(amm.ammExists());
4829
4830 // Bid,Vote,Deposit,Withdraw,TrustSet failing with
4831 // tecAMM_EMPTY. Deposit succeeds with tfTwoAssetIfEmpty option.
4832 env(amm.bid({
4833 .account = alice_,
4834 .bidMin = 1000,
4835 }),
4836 Ter(tecAMM_EMPTY));
4837 amm.vote(
4838 std::nullopt, 100, std::nullopt, std::nullopt, std::nullopt, Ter(tecAMM_EMPTY));
4839 amm.withdraw(alice_, 100, std::nullopt, std::nullopt, Ter(tecAMM_EMPTY));
4840 amm.deposit(
4841 alice_, USD(100), std::nullopt, std::nullopt, std::nullopt, Ter(tecAMM_EMPTY));
4842 env(trust(alice_, STAmount{amm.lptIssue(), 10'000}), Ter(tecAMM_EMPTY));
4843
4844 // Can deposit with tfTwoAssetIfEmpty option
4845 amm.deposit(
4846 alice_,
4847 std::nullopt,
4848 XRP(10'000),
4849 USD(10'000),
4850 std::nullopt,
4851 tfTwoAssetIfEmpty,
4852 std::nullopt,
4853 std::nullopt,
4854 1'000);
4855 BEAST_EXPECT(amm.expectBalances(XRP(10'000), USD(10'000), amm.tokens()));
4856 BEAST_EXPECT(amm.expectTradingFee(1'000));
4857 BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0}));
4858
4859 // Withdrawing all tokens deletes AMM since the number
4860 // of remaining trustlines is less than max
4861 amm.withdrawAll(alice_);
4862 BEAST_EXPECT(!amm.ammExists());
4863 BEAST_EXPECT(!env.le(keylet::ownerDir(amm.ammAccount())));
4864 }
4865
4866 {
4867 Env env(
4868 *this,
4870 cfg->fees.referenceFee = XRPAmount(1);
4871 return cfg;
4872 }),
4873 all);
4874 fund(env, gw_, {alice_}, XRP(20'000), {USD(10'000)});
4875 AMM amm(env, gw_, XRP(10'000), USD(10'000));
4876 for (auto i = 0; i < (kMaxDeletableAmmTrustLines * 2) + 10; ++i)
4877 {
4878 Account const a{std::to_string(i)};
4879 env.fund(XRP(1'000), a);
4880 env(trust(a, STAmount{amm.lptIssue(), 10'000}));
4881 env.close();
4882 }
4883 // The trustlines are partially deleted.
4884 amm.withdrawAll(gw_);
4885 BEAST_EXPECT(amm.ammExists());
4886
4887 // AMMDelete has to be called twice to delete AMM.
4888 amm.ammDelete(alice_, Ter(tecINCOMPLETE));
4889 BEAST_EXPECT(amm.ammExists());
4890 // Deletes remaining trustlines and deletes AMM.
4891 amm.ammDelete(alice_);
4892 BEAST_EXPECT(!amm.ammExists());
4893 BEAST_EXPECT(!env.le(keylet::ownerDir(amm.ammAccount())));
4894
4895 // Try redundant delete
4896 amm.ammDelete(alice_, Ter(terNO_AMM));
4897 }
4898 }
4899
4900 void
4902 {
4903 testcase("Clawback");
4904 using namespace jtx;
4905 Env env(*this);
4906 env.fund(XRP(2'000), gw_);
4907 env.fund(XRP(2'000), alice_);
4908 AMM const amm(env, gw_, XRP(1'000), USD(1'000));
4909 env(fset(gw_, asfAllowTrustLineClawback), Ter(tecOWNERS));
4910 }
4911
4912 void
4914 {
4915 testcase("AMMID");
4916 using namespace jtx;
4917 testAMM([&](AMM& amm, Env& env) {
4918 amm.setClose(false);
4919 auto const info = env.rpc(
4920 "json",
4921 "account_info",
4922 std::string(R"({"account": ")" + to_string(amm.ammAccount()) + "\"}"));
4923 try
4924 {
4925 BEAST_EXPECT(
4926 info[jss::result][jss::account_data][jss::AMMID].asString() ==
4927 to_string(amm.ammID()));
4928 }
4929 catch (...)
4930 {
4931 fail();
4932 }
4933 amm.deposit(carol_, 1'000);
4934 auto const affected =
4935 env.meta()->getJson(JsonOptions::Values::None)[sfAffectedNodes.fieldName];
4936 try
4937 {
4938 bool found = false;
4939 for (auto const& node : affected)
4940 {
4941 if (node.isMember(sfModifiedNode.fieldName) &&
4942 node[sfModifiedNode.fieldName][sfLedgerEntryType.fieldName].asString() ==
4943 "AccountRoot" &&
4944 node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Account]
4945 .asString() == to_string(amm.ammAccount()))
4946 {
4947 found = node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::AMMID]
4948 .asString() == to_string(amm.ammID());
4949 break;
4950 }
4951 }
4952 BEAST_EXPECT(found);
4953 }
4954 catch (...)
4955 {
4956 fail();
4957 }
4958 });
4959 }
4960
4961 void
4963 {
4964 testcase("Offer/Strand Selection");
4965 using namespace jtx;
4966 Account const ed("ed");
4967 Account const gw1("gw1");
4968 auto const eth = gw1["ETH"];
4969 auto const can = gw1["CAN"];
4970
4971 // These tests are expected to fail if the OwnerPaysFee feature
4972 // is ever supported. Updates will need to be made to AMM handling
4973 // in the payment engine, and these tests will need to be updated.
4974
4975 auto const prep = [&](Env& env, auto gwRate, auto gw1Rate) {
4976 fund(env, gw_, {alice_, carol_, bob_, ed}, XRP(2'000), {USD(2'000)});
4977 env.fund(XRP(2'000), gw1);
4978 fund(env, gw1, {alice_, carol_, bob_, ed}, {eth(2'000), can(2'000)}, Fund::TokenOnly);
4979 env(rate(gw_, gwRate));
4980 env(rate(gw1, gw1Rate));
4981 env.close();
4982 };
4983
4984 for (auto const& rates : {std::make_pair(1.5, 1.9), std::make_pair(1.9, 1.5)})
4985 {
4986 // Offer Selection
4987
4988 // Cross-currency payment: AMM has the same spot price quality
4989 // as CLOB's offer and can't generate a better quality offer.
4990 // The transfer fee in this case doesn't change the CLOB quality
4991 // because trIn is ignored on adjustment and trOut on payment is
4992 // also ignored because ownerPaysTransferFee is false in this
4993 // case. Run test for 0) offer, 1) AMM, 2) offer and AMM to
4994 // verify that the quality is better in the first case, and CLOB
4995 // is selected in the second case.
4996 {
4998 for (auto i = 0; i < 3; ++i)
4999 {
5000 Env env(*this, features);
5001 prep(env, rates.first, rates.second);
5003 if (i == 0 || i == 2)
5004 {
5005 env(offer(ed, eth(400), USD(400)), Txflags(tfPassive));
5006 env.close();
5007 }
5008 if (i > 0)
5009 amm.emplace(env, ed, USD(1'000), eth(1'000));
5010 env(pay(carol_, bob_, USD(100)), Path(~USD), Sendmax(eth(500)));
5011 env.close();
5012 // CLOB and AMM, AMM is not selected
5013 if (i == 2)
5014 {
5015 BEAST_EXPECT(
5016 amm.has_value() &&
5017 amm->expectBalances(USD(1'000), eth(1'000), amm->tokens()));
5018 }
5019 BEAST_EXPECT(expectHolding(env, bob_, USD(2'100)));
5020 q[i] = Quality(
5021 Amounts{
5022 eth(2'000) - env.balance(carol_, eth),
5023 env.balance(bob_, USD) - USD(2'000)});
5024 }
5025 // CLOB is better quality than AMM
5026 BEAST_EXPECT(q[0] > q[1]);
5027 // AMM is not selected with CLOB
5028 BEAST_EXPECT(q[0] == q[2]);
5029 }
5030 // Offer crossing: AMM has the same spot price quality
5031 // as CLOB's offer and can't generate a better quality offer.
5032 // The transfer fee in this case doesn't change the CLOB quality
5033 // because the quality adjustment is ignored for the offer
5034 // crossing.
5035 for (auto i = 0; i < 3; ++i)
5036 {
5037 Env env(*this, features);
5038 prep(env, rates.first, rates.second);
5040 if (i == 0 || i == 2)
5041 {
5042 env(offer(ed, eth(400), USD(400)), Txflags(tfPassive));
5043 env.close();
5044 }
5045 if (i > 0)
5046 amm.emplace(env, ed, USD(1'000), eth(1'000));
5047 env(offer(alice_, USD(400), eth(400)));
5048 env.close();
5049 // AMM is not selected
5050 if (i > 0)
5051 {
5052 BEAST_EXPECT(
5053 amm.has_value() &&
5054 amm->expectBalances(USD(1'000), eth(1'000), amm->tokens()));
5055 }
5056 if (i == 0 || i == 2)
5057 {
5058 // Fully crosses
5059 BEAST_EXPECT(expectOffers(env, alice_, 0));
5060 }
5061 // Fails to cross because AMM is not selected
5062 else
5063 {
5064 BEAST_EXPECT(expectOffers(env, alice_, 1, {Amounts{USD(400), eth(400)}}));
5065 }
5066 BEAST_EXPECT(expectOffers(env, ed, 0));
5067 }
5068
5069 // Show that the CLOB quality reduction
5070 // results in AMM offer selection.
5071
5072 // Same as the payment but reduced offer quality
5073 {
5075 for (auto i = 0; i < 3; ++i)
5076 {
5077 Env env(*this, features);
5078 prep(env, rates.first, rates.second);
5080 if (i == 0 || i == 2)
5081 {
5082 env(offer(ed, eth(400), USD(300)), Txflags(tfPassive));
5083 env.close();
5084 }
5085 if (i > 0)
5086 amm.emplace(env, ed, USD(1'000), eth(1'000));
5087 env(pay(carol_, bob_, USD(100)), Path(~USD), Sendmax(eth(500)));
5088 env.close();
5089 // AMM and CLOB are selected
5090 if (i > 0)
5091 {
5092 BEAST_EXPECT(
5093 amm.has_value() &&
5094 !amm->expectBalances(USD(1'000), eth(1'000), amm->tokens()));
5095 }
5096 if (i == 2)
5097 {
5098 if (rates.first == 1.5)
5099 {
5100 BEAST_EXPECT(expectOffers(
5101 env,
5102 ed,
5103 1,
5104 {{Amounts{
5105 STAmount{eth, UINT64_C(378'6327949540812), -13},
5106 STAmount{USD, UINT64_C(283'9745962155609), -13}}}}));
5107 }
5108 else
5109 {
5110 BEAST_EXPECT(expectOffers(
5111 env,
5112 ed,
5113 1,
5114 {{Amounts{
5115 STAmount{eth, UINT64_C(325'2994616207479), -13},
5116 STAmount{USD, UINT64_C(243'9745962155609), -13}}}}));
5117 }
5118 }
5119 BEAST_EXPECT(expectHolding(env, bob_, USD(2'100)));
5120 q[i] = Quality(
5121 Amounts{
5122 eth(2'000) - env.balance(carol_, eth),
5123 env.balance(bob_, USD) - USD(2'000)});
5124 }
5125 // AMM is better quality
5126 BEAST_EXPECT(q[1] > q[0]);
5127 // AMM and CLOB produce better quality
5128 BEAST_EXPECT(q[2] > q[1]);
5129 }
5130
5131 // Same as the offer-crossing but reduced offer quality
5132 for (auto i = 0; i < 3; ++i)
5133 {
5134 Env env(*this, features);
5135 prep(env, rates.first, rates.second);
5137 if (i == 0 || i == 2)
5138 {
5139 env(offer(ed, eth(400), USD(250)), Txflags(tfPassive));
5140 env.close();
5141 }
5142 if (i > 0)
5143 amm.emplace(env, ed, USD(1'000), eth(1'000));
5144 env(offer(alice_, USD(250), eth(400)));
5145 env.close();
5146 // AMM is selected in both cases
5147 if (i > 0)
5148 {
5149 BEAST_EXPECT(
5150 amm.has_value() &&
5151 !amm->expectBalances(USD(1'000), eth(1'000), amm->tokens()));
5152 }
5153 // Partially crosses, AMM is selected, CLOB fails
5154 // limitQuality
5155 if (i == 2)
5156 {
5157 if (rates.first == 1.5)
5158 {
5159 // Ed offer is partially crossed.
5160 // Rounding in favor of the AMM makes limitQuality work
5161 BEAST_EXPECT(expectOffers(
5162 env,
5163 ed,
5164 1,
5165 {{Amounts{
5166 STAmount{eth, UINT64_C(335'0889359326475), -13},
5167 STAmount{USD, UINT64_C(209'4305849579047), -13},
5168 }}}));
5169 BEAST_EXPECT(expectOffers(env, alice_, 0));
5170 }
5171 else
5172 {
5173 // Ed offer is partially crossed.
5174 BEAST_EXPECT(expectOffers(
5175 env,
5176 ed,
5177 1,
5178 {{Amounts{
5179 STAmount{eth, UINT64_C(335'0889359326475), -13},
5180 STAmount{USD, UINT64_C(209'4305849579047), -13},
5181 }}}));
5182 BEAST_EXPECT(expectOffers(env, alice_, 0));
5183 }
5184 }
5185 }
5186
5187 // Strand selection
5188
5189 // Two book steps strand quality is 1.
5190 // AMM strand's best quality is equal to AMM's spot price
5191 // quality, which is 1. Both strands (steps) are adjusted
5192 // for the transfer fee in qualityUpperBound. In case
5193 // of two strands, AMM offers have better quality and are
5194 // consumed first, remaining liquidity is generated by CLOB
5195 // offers. Liquidity from two strands is better in this case
5196 // than in case of one strand with two book steps. Liquidity
5197 // from one strand with AMM has better quality than either one
5198 // strand with two book steps or two strands. It may appear
5199 // unintuitive, but one strand with AMM is optimized and
5200 // generates one AMM offer, while in case of two strands,
5201 // multiple AMM offers are generated, which results in slightly
5202 // worse overall quality.
5203 {
5205 for (auto i = 0; i < 3; ++i)
5206 {
5207 Env env(*this, features);
5208 prep(env, rates.first, rates.second);
5210
5211 if (i == 0 || i == 2)
5212 {
5213 env(offer(ed, eth(400), can(400)), Txflags(tfPassive));
5214 env(offer(ed, can(400), USD(400))), Txflags(tfPassive);
5215 env.close();
5216 }
5217
5218 if (i > 0)
5219 amm.emplace(env, ed, eth(1'000), USD(1'000));
5220
5221 env(pay(carol_, bob_, USD(100)),
5222 Path(~USD),
5223 Path(~can, ~USD),
5224 Sendmax(eth(600)));
5225 env.close();
5226
5227 BEAST_EXPECT(expectHolding(env, bob_, USD(2'100)));
5228
5229 if (i == 2)
5230 {
5231 if (rates.first == 1.5)
5232 {
5233 // Liquidity is consumed from AMM strand only
5234 BEAST_EXPECT(
5235 amm.has_value() &&
5236 amm->expectBalances(
5237 STAmount{eth, UINT64_C(1'176'660389557593), -12},
5238 USD(850),
5239 amm->tokens()));
5240 }
5241 else
5242 {
5243 BEAST_EXPECT(
5244 amm.has_value() &&
5245 amm->expectBalances(
5246 STAmount{eth, UINT64_C(1'179'54009433964), -11},
5247 STAmount{USD, UINT64_C(847'7880529867501), -13},
5248 amm->tokens()));
5249 BEAST_EXPECT(expectOffers(
5250 env,
5251 ed,
5252 2,
5253 {{Amounts{
5254 STAmount{eth, UINT64_C(343'3179205198749), -13},
5255 STAmount{can, UINT64_C(343'3179205198749), -13},
5256 },
5257 Amounts{
5258 STAmount{can, UINT64_C(362'2119470132499), -13},
5259 STAmount{USD, UINT64_C(362'2119470132499), -13},
5260 }}}));
5261 }
5262 }
5263 q[i] = Quality(
5264 Amounts{
5265 eth(2'000) - env.balance(carol_, eth),
5266 env.balance(bob_, USD) - USD(2'000)});
5267 }
5268 BEAST_EXPECT(q[1] > q[0]);
5269 BEAST_EXPECT(q[2] > q[0] && q[2] < q[1]);
5270 }
5271 }
5272 }
5273
5274 void
5276 {
5277 testcase("Fix Default Inner Object");
5278 using namespace jtx;
5279 FeatureBitset const all{testableAmendments()};
5280
5281 auto const test = [&](FeatureBitset features,
5282 TER const& err1,
5283 TER const& err2,
5284 TER const& err3,
5285 TER const& err4,
5286 std::uint16_t tfee,
5287 bool closeLedger,
5288 std::optional<std::uint16_t> extra = std::nullopt) {
5289 Env env(*this, features);
5290 fund(env, gw_, {alice_}, XRP(1'000), {USD(10)});
5291 AMM amm(env, gw_, XRP(10), USD(10), {.tfee = tfee, .close = closeLedger});
5292 amm.deposit(alice_, USD(10), XRP(10));
5293 amm.vote(VoteArg{.account = alice_, .tfee = tfee, .err = Ter(err1)});
5294 amm.withdraw(WithdrawArg{.account = gw_, .asset1Out = USD(1), .err = Ter(err2)});
5295 // with the amendment disabled and ledger not closed,
5296 // second vote succeeds if the first vote sets the trading fee
5297 // to non-zero; if the first vote sets the trading fee to >0 &&
5298 // <9 then the second withdraw succeeds if the second vote sets
5299 // the trading fee so that the discounted fee is non-zero
5300 amm.vote(VoteArg{.account = alice_, .tfee = 20, .err = Ter(err3)});
5301 amm.withdraw(WithdrawArg{.account = gw_, .asset1Out = USD(2), .err = Ter(err4)});
5302 };
5303
5304 // ledger is closed after each transaction, vote/withdraw don't fail
5306 // ledger is not closed after each transaction
5307 test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 0, false);
5308 // if non-zero trading/discounted fee then vote/withdraw
5309 // don't fail whether the ledger is closed or not
5310 test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, true);
5311 test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 10, false);
5312 // non-zero trading fee but discounted fee is 0, vote doesn't fail
5313 // but withdraw fails
5314 test(all, tesSUCCESS, tesSUCCESS, tesSUCCESS, tesSUCCESS, 9, false);
5315 }
5316
5317 void
5319 {
5320 testcase("Fix changeSpotPriceQuality");
5321 using namespace jtx;
5322
5323 std::string logs;
5324
5325 enum class Status {
5326 SucceedShouldSucceedResize, // Succeeds because of offer resizing
5327 FailShouldSucceed, // Succeeds because the XRP side
5328 // is generated first
5329 SucceedShouldFail, // Fails due to small quality difference
5330 Fail, // Fails because the quality can't be matched
5331 Succeed, // Succeeds
5332 };
5333 using enum Status;
5334 auto const xrpIouAmounts10100 = TAmounts{XRPAmount{10}, IOUAmount{100}};
5335 auto const iouXrpAmounts10100 = TAmounts{IOUAmount{10}, XRPAmount{100}};
5336 // clang-format off
5338 //Pool In , Pool Out, Quality , Fee, Status
5339 {"0.001519763260828713", "1558701", Quality{5414253689393440221}, 1000, FailShouldSucceed},
5340 {"0.01099814367603737", "1892611", Quality{5482264816516900274}, 1000, FailShouldSucceed},
5341 {"0.78", "796599", Quality{5630392334958379008}, 1000, FailShouldSucceed},
5342 {"105439.2955578965", "49398693", Quality{5910869983721805038}, 400, FailShouldSucceed},
5343 {"12408293.23445213", "4340810521", Quality{5911611095910090752}, 997, FailShouldSucceed},
5344 {"1892611", "0.01099814367603737", Quality{6703103457950430139}, 1000, FailShouldSucceed},
5345 {"423028.8508101858", "3392804520", Quality{5837920340654162816}, 600, FailShouldSucceed},
5346 {"44565388.41001027", "73890647", Quality{6058976634606450001}, 1000, FailShouldSucceed},
5347 {"66831.68494832662", "16", Quality{6346111134641742975}, 0, FailShouldSucceed},
5348 {"675.9287302203422", "1242632304", Quality{5625960929244093294}, 300, FailShouldSucceed},
5349 {"7047.112186735699", "1649845866", Quality{5696855348026306945}, 504, FailShouldSucceed},
5350 {"840236.4402981238", "47419053", Quality{5982561601648018688}, 499, FailShouldSucceed},
5351 {"992715.618909774", "189445631733", Quality{5697835648288106944}, 815, SucceedShouldSucceedResize},
5352 {"504636667521", "185545883.9506651", Quality{6343802275337659280}, 503, SucceedShouldSucceedResize},
5353 {"992706.7218636649", "189447316000", Quality{5697835648288106944}, 797, SucceedShouldSucceedResize},
5354 {"1.068737911388205", "127860278877", Quality{5268604356368739396}, 293, SucceedShouldSucceedResize},
5355 {"17932506.56880419", "189308.6043676173", Quality{6206460598195440068}, 311, SucceedShouldSucceedResize},
5356 {"1.066379294658174", "128042251493", Quality{5268559341368739328}, 270, SucceedShouldSucceedResize},
5357 {"350131413924", "1576879.110907892", Quality{6487411636539049449}, 650, Fail},
5358 {"422093460", "2.731797662057464", Quality{6702911108534394924}, 1000, Fail},
5359 {"76128132223", "367172.7148422662", Quality{6487263463413514240}, 548, Fail},
5360 {"132701839250", "280703770.7695443", Quality{6273750681188885075}, 562, Fail},
5361 {"994165.7604612011", "189551302411", Quality{5697835592690668727}, 815, Fail},
5362 {"45053.33303227917", "86612695359", Quality{5625695218943638190}, 500, Fail},
5363 {"199649.077043865", "14017933007", Quality{5766034667318524880}, 324, Fail},
5364 {"27751824831.70903", "78896950", Quality{6272538159621630432}, 500, Fail},
5365 {"225.3731275781907", "156431793648", Quality{5477818047604078924}, 989, Fail},
5366 {"199649.077043865", "14017933007", Quality{5766036094462806309}, 324, Fail},
5367 {"3.590272027140361", "20677643641", Quality{5406056147042156356}, 808, Fail},
5368 {"1.070884664490231", "127604712776", Quality{5268620608623825741}, 293, Fail},
5369 {"3272.448829820197", "6275124076", Quality{5625710328924117902}, 81, Fail},
5370 {"0.009059512633902926", "7994028", Quality{5477511954775533172}, 1000, Fail},
5371 {"1", "1.0", Quality{0}, 100, Fail},
5372 {"1.0", "1", Quality{0}, 100, Fail},
5373 {"10", "10.0", Quality{xrpIouAmounts10100}, 100, Fail},
5374 {"10.0", "10", Quality{iouXrpAmounts10100}, 100, Fail},
5375 {"69864389131", "287631.4543025075", Quality{6487623473313516078}, 451, Succeed},
5376 {"4328342973", "12453825.99247381", Quality{6272522264364865181}, 997, Succeed},
5377 {"32347017", "7003.93031579449", Quality{6347261126087916670}, 1000, Succeed},
5378 {"61697206161", "36631.4583206413", Quality{6558965195382476659}, 500, Succeed},
5379 {"1654524979", "7028.659825511603", Quality{6487551345110052981}, 504, Succeed},
5380 {"88621.22277293179", "5128418948", Quality{5766347291552869205}, 380, Succeed},
5381 {"1892611", "0.01099814367603737", Quality{6703102780512015436}, 1000, Succeed},
5382 {"4542.639373338766", "24554809", Quality{5838994982188783710}, 0, Succeed},
5383 {"5132932546", "88542.99750172683", Quality{6419203342950054537}, 380, Succeed},
5384 {"78929964.1549083", "1506494795", Quality{5986890029845558688}, 589, Succeed},
5385 {"10096561906", "44727.72453735605", Quality{6487455290284644551}, 250, Succeed},
5386 {"5092.219565514988", "8768257694", Quality{5626349534958379008}, 503, Succeed},
5387 {"1819778294", "8305.084302902864", Quality{6487429398998540860}, 415, Succeed},
5388 {"6970462.633911943", "57359281", Quality{6054087899185946624}, 850, Succeed},
5389 {"3983448845", "2347.543644281467", Quality{6558965195382476659}, 856, Succeed},
5390 // This is a tiny offer 12drops/19321952e-15. It is resized to 11drops/17711789e-15
5391 // but the quality is still less than the target quality and the offer fails.
5392 {"771493171", "1.243473020567508", Quality{6707566798038544272}, 100, SucceedShouldFail},
5393 };
5394 // clang-format on
5395
5396 boost::regex const rx("^\\d+$");
5397 boost::smatch match;
5398 Env const env(*this, features, std::make_unique<CaptureLogs>(&logs));
5399 auto const rules = env.current()->rules();
5400 CurrentTransactionRulesGuard const rg(rules);
5402
5403 for (auto const& t : tests)
5404 {
5405 auto const getPool = [&](std::string const& v, bool isXRP) {
5406 if (isXRP)
5407 return amountFromString(xrpIssue(), v);
5408 return amountFromString(noIssue(), v);
5409 };
5410 auto const& quality = std::get<Quality>(t);
5411 auto const tfee = std::get<std::uint16_t>(t);
5412 auto const status = std::get<Status>(t);
5413 auto const poolInIsXRP = boost::regex_search(std::get<0>(t), match, rx);
5414 auto const poolOutIsXRP = boost::regex_search(std::get<1>(t), match, rx);
5415 assert(!(poolInIsXRP && poolOutIsXRP));
5416 auto const poolIn = getPool(std::get<0>(t), poolInIsXRP);
5417 auto const poolOut = getPool(std::get<1>(t), poolOutIsXRP);
5418 auto const amounts =
5419 changeSpotPriceQuality(Amounts{poolIn, poolOut}, quality, tfee, env.journal);
5420 if (amounts)
5421 {
5422 if (status == SucceedShouldSucceedResize)
5423 {
5424 BEAST_EXPECT(Quality{*amounts} >= quality);
5425 }
5426 else if (status == Succeed)
5427 {
5428 BEAST_EXPECT(Quality{*amounts} >= quality);
5429 }
5430 else if (status == FailShouldSucceed)
5431 {
5432 BEAST_EXPECT(Quality{*amounts} >= quality);
5433 }
5434 else if (status == SucceedShouldFail)
5435 {
5436 // The offer is no longer generated at a worse quality
5437 // than requested, so reaching here is a failure.
5438 BEAST_EXPECT(false);
5439 }
5440 }
5441 else
5442 {
5443 // Fails because the quality can't be matched. Verify by
5444 // generating a tiny offer, which doesn't match the quality.
5445 // Exclude zero quality since no offer is generated in this
5446 // case.
5447 if (status == Fail && quality != Quality{0})
5448 {
5449 auto const tinyOffer = [&] {
5450 if (isXRP(poolIn))
5451 {
5452 auto const takerPays = STAmount{xrpIssue(), 1};
5453 return Amounts{
5454 takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)};
5455 }
5456 if (isXRP(poolOut))
5457 {
5458 auto const takerGets = STAmount{xrpIssue(), 1};
5459 return Amounts{
5460 swapAssetOut(Amounts{poolIn, poolOut}, takerGets, tfee), takerGets};
5461 }
5462 auto const takerPays =
5463 toAmount<STAmount>(getAsset(poolIn), Number{1, -10} * poolIn);
5464 return Amounts{
5465 takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)};
5466 }();
5467 BEAST_EXPECT(Quality(tinyOffer) < quality);
5468 }
5469 else if (status == FailShouldSucceed)
5470 {
5471 // The offer is now generated, so reaching here is a failure.
5472 BEAST_EXPECT(false);
5473 }
5474 else if (status == SucceedShouldFail)
5475 {
5476 // The offer is no longer generated, which is expected here.
5477 pass();
5478 }
5479 }
5480 }
5481
5482 // Test negative discriminant
5483 {
5484 // b**2 - 4 * a * c -> 1 * 1 - 4 * 1 * 1 = -3
5485 auto const res = solveQuadraticEqSmallest(Number{1}, Number{1}, Number{1});
5486 BEAST_EXPECT(!res.has_value());
5487 }
5488 }
5489
5490 void
5492 {
5493 using namespace jtx;
5494
5495 testAMM([&](AMM& ammAlice, Env& env) {
5496 WithdrawArg const args{
5497 .flags = tfSingleAsset,
5498 .err = Ter(temMALFORMED),
5499 };
5500 ammAlice.withdraw(args);
5501 });
5502
5503 testAMM([&](AMM& ammAlice, Env& env) {
5504 WithdrawArg const args{
5505 .flags = tfOneAssetLPToken,
5506 .err = Ter(temMALFORMED),
5507 };
5508 ammAlice.withdraw(args);
5509 });
5510
5511 testAMM([&](AMM& ammAlice, Env& env) {
5512 WithdrawArg const args{
5513 .flags = tfLimitLPToken,
5514 .err = Ter(temMALFORMED),
5515 };
5516 ammAlice.withdraw(args);
5517 });
5518
5519 testAMM([&](AMM& ammAlice, Env& env) {
5520 WithdrawArg const args{
5521 .asset1Out = XRP(100),
5522 .asset2Out = XRP(100),
5523 .err = Ter(temBAD_AMM_TOKENS),
5524 };
5525 ammAlice.withdraw(args);
5526 });
5527
5528 testAMM([&](AMM& ammAlice, Env& env) {
5529 WithdrawArg const args{
5530 .asset1Out = XRP(100),
5531 .asset2Out = BAD(100),
5532 .err = Ter(temBAD_CURRENCY),
5533 };
5534 ammAlice.withdraw(args);
5535 });
5536
5537 testAMM([&](AMM& ammAlice, Env& env) {
5538 json::Value jv;
5539 jv[jss::TransactionType] = jss::AMMWithdraw;
5540 jv[jss::Flags] = tfLimitLPToken;
5541 jv[jss::Account] = alice_.human();
5542 ammAlice.setTokens(jv);
5543 XRP(100).value().setJson(jv[jss::Amount]);
5544 USD(100).value().setJson(jv[jss::EPrice]);
5545 env(jv, Ter(temBAD_AMM_TOKENS));
5546 });
5547 }
5548
5549 void
5550 // NOLINTNEXTLINE(readability-convert-member-functions-to-static)
5552 {
5553 using namespace jtx;
5554 using namespace std::chrono;
5555 FeatureBitset const all{featuresInitial};
5556
5557 std::string logs;
5558
5559 Account const gatehub{"gatehub"};
5560 Account const bitstamp{"bitstamp"};
5561 Account const trader{"trader"};
5562 auto const usdGH = gatehub["USD"];
5563 auto const btcGH = gatehub["BTC"];
5564 auto const usdBIT = bitstamp["USD"];
5565
5566 struct InputSet
5567 {
5568 char const* testCase;
5569 double const poolUsdBIT;
5570 double const poolUsdGH;
5571 Sendmax const sendMaxUsdBIT;
5572 STAmount const sendUsdGH;
5573 STAmount const goodUsdGH;
5574 STAmount const goodUsdBIT;
5575 IOUAmount const lpTokenBalance;
5576 std::optional<IOUAmount> const lpTokenBalanceAlt = std::nullopt;
5577 double const offer1BtcGH = 0.1;
5578 double const offer2BtcGH = 0.1;
5579 double const offer2UsdGH = 1;
5580 double const rateBIT = 0.0;
5581 double const rateGH = 0.0;
5582 };
5583
5584 using Uint64T = std::uint64_t;
5585
5586 for (auto const& input : {
5587 InputSet{
5588 .testCase = "Test Fix Overflow Offer", //
5589 .poolUsdBIT = 3, //
5590 .poolUsdGH = 273, //
5591 .sendMaxUsdBIT{usdBIT(50)}, //
5592 .sendUsdGH{usdGH, Uint64T(272'455089820359), -12}, //
5593 .goodUsdGH{usdGH, Uint64T(96'7543114222965), -13}, //
5594 .goodUsdBIT{usdBIT, Uint64T(8'464739069098152), -15}, //
5595 .lpTokenBalance = {28'61817604250837, -14}, //
5596 .lpTokenBalanceAlt = IOUAmount{28'61817604250836, -14}, //
5597 .offer1BtcGH = 0.1, //
5598 .offer2BtcGH = 0.1, //
5599 .offer2UsdGH = 1, //
5600 .rateBIT = 1.15, //
5601 .rateGH = 1.2, //
5602 },
5603 InputSet{
5604 .testCase = "Overflow test {1, 100, 0.111}", //
5605 .poolUsdBIT = 1, //
5606 .poolUsdGH = 100, //
5607 .sendMaxUsdBIT{usdBIT(0.111)}, //
5608 .sendUsdGH{usdGH, 100}, //
5609 .goodUsdGH{usdGH, Uint64T(90'04347888284201), -14}, //
5610 .goodUsdBIT{usdBIT, Uint64T(1'111), -3}, //
5611 .lpTokenBalance{10, 0}, //
5612 .offer1BtcGH = 1e-5, //
5613 .offer2BtcGH = 1, //
5614 .offer2UsdGH = 1e-5, //
5615 .rateBIT = 0, //
5616 .rateGH = 0, //
5617 },
5618 InputSet{
5619 .testCase = "Overflow test {1, 100, 1.00}", //
5620 .poolUsdBIT = 1, //
5621 .poolUsdGH = 100, //
5622 .sendMaxUsdBIT{usdBIT(1.00)}, //
5623 .sendUsdGH{usdGH, 100}, //
5624 .goodUsdGH{usdGH, Uint64T(52'94379354424135), -14}, //
5625 .goodUsdBIT{usdBIT, Uint64T(2), 0}, //
5626 .lpTokenBalance{10, 0}, //
5627 .offer1BtcGH = 1e-5, //
5628 .offer2BtcGH = 1, //
5629 .offer2UsdGH = 1e-5, //
5630 .rateBIT = 0, //
5631 .rateGH = 0, //
5632 },
5633 InputSet{
5634 .testCase = "Overflow test {1, 100, 4.6432}", //
5635 .poolUsdBIT = 1, //
5636 .poolUsdGH = 100, //
5637 .sendMaxUsdBIT{usdBIT(4.6432)}, //
5638 .sendUsdGH{usdGH, 100}, //
5639 .goodUsdGH{usdGH, Uint64T(35'44113971506987), -14}, //
5640 .goodUsdBIT{usdBIT, Uint64T(2'821579689703954), -15}, //
5641 .lpTokenBalance{10, 0}, //
5642 .offer1BtcGH = 1e-5, //
5643 .offer2BtcGH = 1, //
5644 .offer2UsdGH = 1e-5, //
5645 .rateBIT = 0, //
5646 .rateGH = 0, //
5647 },
5648 InputSet{
5649 .testCase = "Overflow test {1, 100, 10}", //
5650 .poolUsdBIT = 1, //
5651 .poolUsdGH = 100, //
5652 .sendMaxUsdBIT{usdBIT(10)}, //
5653 .sendUsdGH{usdGH, 100}, //
5654 .goodUsdGH{usdGH, Uint64T(35'44113971506987), -14}, //
5655 .goodUsdBIT{usdBIT, Uint64T(2'821579689703954), -15}, //
5656 .lpTokenBalance{10, 0}, //
5657 .offer1BtcGH = 1e-5, //
5658 .offer2BtcGH = 1, //
5659 .offer2UsdGH = 1e-5, //
5660 .rateBIT = 0, //
5661 .rateGH = 0, //
5662 },
5663 InputSet{
5664 .testCase = "Overflow test {50, 100, 5.55}", //
5665 .poolUsdBIT = 50, //
5666 .poolUsdGH = 100, //
5667 .sendMaxUsdBIT{usdBIT(5.55)}, //
5668 .sendUsdGH{usdGH, 100}, //
5669 .goodUsdGH{usdGH, Uint64T(90'0434788828413), -13}, //
5670 .goodUsdBIT{usdBIT, Uint64T(55'55), -2}, //
5671 .lpTokenBalance{Uint64T(70'71067811865475), -14}, //
5672 .offer1BtcGH = 1e-5, //
5673 .offer2BtcGH = 1, //
5674 .offer2UsdGH = 1e-5, //
5675 .rateBIT = 0, //
5676 .rateGH = 0, //
5677 },
5678 InputSet{
5679 .testCase = "Overflow test {50, 100, 50.00}", //
5680 .poolUsdBIT = 50, //
5681 .poolUsdGH = 100, //
5682 .sendMaxUsdBIT{usdBIT(50.00)}, //
5683 .sendUsdGH{usdGH, 100}, //
5684 .goodUsdGH{usdGH, Uint64T(52'94379354424092), -14}, //
5685 .goodUsdBIT{usdBIT, Uint64T(100), 0}, //
5686 .lpTokenBalance{Uint64T(70'71067811865475), -14}, //
5687 .offer1BtcGH = 1e-5, //
5688 .offer2BtcGH = 1, //
5689 .offer2UsdGH = 1e-5, //
5690 .rateBIT = 0, //
5691 .rateGH = 0, //
5692 },
5693 InputSet{
5694 .testCase = "Overflow test {50, 100, 232.16}", //
5695 .poolUsdBIT = 50, //
5696 .poolUsdGH = 100, //
5697 .sendMaxUsdBIT{usdBIT(232.16)}, //
5698 .sendUsdGH{usdGH, 100}, //
5699 .goodUsdGH{usdGH, Uint64T(35'44113971506987), -14}, //
5700 .goodUsdBIT{usdBIT, Uint64T(141'0789844851962), -13}, //
5701 .lpTokenBalance{70'71067811865475, -14}, //
5702 .offer1BtcGH = 1e-5, //
5703 .offer2BtcGH = 1, //
5704 .offer2UsdGH = 1e-5, //
5705 .rateBIT = 0, //
5706 .rateGH = 0, //
5707 },
5708 InputSet{
5709 .testCase = "Overflow test {50, 100, 500}", //
5710 .poolUsdBIT = 50, //
5711 .poolUsdGH = 100, //
5712 .sendMaxUsdBIT{usdBIT(500)}, //
5713 .sendUsdGH{usdGH, 100}, //
5714 .goodUsdGH{usdGH, Uint64T(35'44113971506987), -14}, //
5715 .goodUsdBIT{usdBIT, Uint64T(141'0789844851962), -13}, //
5716 .lpTokenBalance{70'71067811865475, -14}, //
5717 .offer1BtcGH = 1e-5, //
5718 .offer2BtcGH = 1, //
5719 .offer2UsdGH = 1e-5, //
5720 .rateBIT = 0, //
5721 .rateGH = 0, //
5722 },
5723 })
5724 {
5725 testcase(input.testCase);
5726 for (auto const& features : {all - fixAMMv1_3, all})
5727 {
5728 Env env(*this, features, std::make_unique<CaptureLogs>(&logs));
5729
5730 env.fund(XRP(5'000), gatehub, bitstamp, trader);
5731 env.close();
5732
5733 if (input.rateGH != 0.0)
5734 env(rate(gatehub, input.rateGH));
5735 if (input.rateBIT != 0.0)
5736 env(rate(bitstamp, input.rateBIT));
5737
5738 env(trust(trader, usdGH(10'000'000)));
5739 env(trust(trader, usdBIT(10'000'000)));
5740 env(trust(trader, btcGH(10'000'000)));
5741 env.close();
5742
5743 env(pay(gatehub, trader, usdGH(100'000)));
5744 env(pay(gatehub, trader, btcGH(100'000)));
5745 env(pay(bitstamp, trader, usdBIT(100'000)));
5746 env.close();
5747
5748 AMM const amm{env, trader, usdGH(input.poolUsdGH), usdBIT(input.poolUsdBIT)};
5749 env.close();
5750
5751 IOUAmount const preSwapLPTokenBalance = amm.getLPTokensBalance();
5752
5753 env(offer(trader, usdBIT(1), btcGH(input.offer1BtcGH)));
5754 env(offer(trader, btcGH(input.offer2BtcGH), usdGH(input.offer2UsdGH)));
5755 env.close();
5756
5757 env(pay(trader, trader, input.sendUsdGH),
5758 Path(~usdGH),
5759 Path(~btcGH, ~usdGH),
5760 Sendmax(input.sendMaxUsdBIT),
5761 Txflags(tfPartialPayment));
5762 env.close();
5763
5764 auto const& goodUsdGH = input.goodUsdGH;
5765 auto const& goodUsdBIT = input.goodUsdBIT;
5766 auto const lpTokenBalance = [&] {
5767 if (not env.enabled(fixAMMv1_3))
5768 return input.lpTokenBalance;
5769
5770 return input.lpTokenBalanceAlt.value_or(input.lpTokenBalance);
5771 }();
5772
5773 BEAST_EXPECT(amm.expectBalances(goodUsdGH, goodUsdBIT, lpTokenBalance));
5774
5775 // Invariant: LPToken balance must not change in a
5776 // payment or a swap transaction
5777 BEAST_EXPECT(amm.getLPTokensBalance() == preSwapLPTokenBalance);
5778
5779 // Invariant: The square root of (product of the pool
5780 // balances) must be at least the LPTokenBalance
5781 Number const sqrtPoolProduct = root2(goodUsdGH * goodUsdBIT);
5782
5783 // Include a tiny tolerance for the test cases using
5784 // .goodUsdGH{usdGH, uint64_t(35'44113971506987),
5785 // -14}, .goodUsdBIT{usdBIT,
5786 // uint64_t(2'821579689703915), -15},
5787 // These two values multiply
5788 // to 99.99999999999994227040383754105 which gets
5789 // internally rounded to 100, due to representation
5790 // error.
5791 BEAST_EXPECT((sqrtPoolProduct + Number{1, -14} >= lpTokenBalance));
5792 }
5793 }
5794 }
5795
5796 void
5798 {
5799 testcase("swapRounding");
5800 using namespace jtx;
5801
5802 STAmount const xrpPool{XRP, UINT64_C(51600'000981)};
5803 STAmount const iouPool{USD, UINT64_C(803040'9987141784), -10};
5804
5805 STAmount const xrpBob{XRP, UINT64_C(1092'878933)};
5806 STAmount const iouBob{USD, UINT64_C(3'988035892323031), -28}; // 3.9...e-13
5807
5808 testAMM(
5809 [&](AMM& amm, Env& env) {
5810 // Check our AMM starting conditions.
5811 auto [xrpBegin, iouBegin, lptBegin] = amm.balances(XRP, USD);
5812
5813 // Set Bob's starting conditions.
5814 env.fund(xrpBob, bob_);
5815 env.trust(USD(1'000'000), bob_);
5816 env(pay(gw_, bob_, iouBob));
5817 env.close();
5818
5819 env(offer(bob_, XRP(6300), USD(100'000)));
5820 env.close();
5821
5822 // Assert that AMM is unchanged.
5823 BEAST_EXPECT(amm.expectBalances(xrpBegin, iouBegin, amm.tokens()));
5824 },
5825 {{xrpPool, iouPool}},
5826 889,
5827 std::nullopt,
5828 {testableAmendments()});
5829 }
5830
5831 void
5833 {
5834 testcase("AMM Offer Blocked By LOB");
5835 using namespace jtx;
5836
5837 // Low quality LOB offer blocks AMM liquidity
5838
5839 // USD/XRP crosses AMM
5840 {
5841 Env env(*this, features);
5842
5843 fund(env, gw_, {alice_, carol_}, XRP(1'000'000), {USD(1'000'000)});
5844 // Low quality LOB offer
5845 env(offer(alice_, XRP(1), USD(0.01)));
5846 env.close();
5847
5848 AMM const amm(env, gw_, XRP(200'000), USD(100'000));
5849
5850 // The offer crosses AMM
5851 env(offer(carol_, USD(0.49), XRP(1)));
5852 env.close();
5853
5854 BEAST_EXPECT(
5855 amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens()));
5856 BEAST_EXPECT(expectOffers(env, alice_, 1, {{Amounts{XRP(1), USD(0.01)}}}));
5857 // Carol's offer crosses AMM
5858 BEAST_EXPECT(expectOffers(env, carol_, 0));
5859 }
5860
5861 // There is no LOB offer, the same AMM liquidity is consumed.
5862 {
5863 Env env(*this, features);
5864
5865 fund(env, gw_, {alice_, carol_}, XRP(1'000'000), {USD(1'000'000)});
5866 // There is no LOB offer
5867 // env(offer(alice_, XRP(1), USD(0.01)));
5868
5869 AMM const amm(env, gw_, XRP(200'000), USD(100'000));
5870
5871 // The offer crosses AMM
5872 env(offer(carol_, USD(0.49), XRP(1)));
5873 env.close();
5874
5875 // The same result as with the LOB offer
5876 BEAST_EXPECT(
5877 amm.expectBalances(XRPAmount(200'000'980'005), USD(99'999.51), amm.tokens()));
5878 // Carol's offer crosses AMM
5879 BEAST_EXPECT(expectOffers(env, carol_, 0));
5880 }
5881
5882 // XRP/USD crosses AMM
5883 {
5884 Env env(*this, features);
5885 fund(env, gw_, {alice_, carol_, bob_}, XRP(10'000), {USD(1'000)});
5886
5887 // Low quality LOB offer
5888 env(offer(bob_, USD(1), XRPAmount(500)));
5889 env.close();
5890 AMM const amm(env, alice_, XRP(1'000), USD(500));
5891 env(offer(carol_, XRP(100), USD(55)));
5892 env.close();
5893 BEAST_EXPECT(amm.expectBalances(
5894 XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens()));
5895 BEAST_EXPECT(expectOffers(
5896 env, carol_, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}}));
5897 BEAST_EXPECT(expectOffers(env, bob_, 1, {{Amounts{USD(1), XRPAmount(500)}}}));
5898 }
5899
5900 // There is no LOB offer, the same AMM liquidity is consumed.
5901 {
5902 Env env(*this, features);
5903 fund(env, gw_, {alice_, carol_, bob_}, XRP(10'000), {USD(1'000)});
5904
5905 AMM const amm(env, alice_, XRP(1'000), USD(500));
5906 env(offer(carol_, XRP(100), USD(55)));
5907 env.close();
5908 BEAST_EXPECT(amm.expectBalances(
5909 XRPAmount(909'090'909), STAmount{USD, UINT64_C(550'000000055), -9}, amm.tokens()));
5910 BEAST_EXPECT(expectOffers(
5911 env, carol_, 1, {{Amounts{XRPAmount{9'090'909}, STAmount{USD, 4'99999995, -8}}}}));
5912 }
5913 }
5914
5915 void
5917 {
5918 testcase("LPToken Balance");
5919 using namespace jtx;
5920
5921 // Last Liquidity Provider is the issuer of one token
5922 {
5923 std::string logs;
5924 Env env(*this, features, std::make_unique<CaptureLogs>(&logs));
5925 fund(env, gw_, {alice_, carol_}, XRP(1'000'000'000), {USD(1'000'000'000)});
5926 AMM amm(env, gw_, XRP(2), USD(1));
5927 amm.deposit(alice_, IOUAmount{1'876123487565916, -15});
5928 amm.deposit(carol_, IOUAmount{1'000'000});
5929 amm.withdrawAll(alice_);
5930 BEAST_EXPECT(amm.expectLPTokens(alice_, IOUAmount{0}));
5931 amm.withdrawAll(carol_);
5932 BEAST_EXPECT(amm.expectLPTokens(carol_, IOUAmount{0}));
5933 auto const lpToken =
5934 getAccountLines(env, gw_, amm.lptIssue())[jss::lines][0u][jss::balance];
5935 auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value];
5936 BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373");
5937 amm.withdrawAll(gw_);
5938 BEAST_EXPECT(!amm.ammExists());
5939 }
5940
5941 // Last Liquidity Provider is the issuer of two tokens, or not
5942 // the issuer
5943 for (auto const& lp : {gw_, bob_})
5944 {
5945 Env env(*this, features);
5946 auto const abc = gw_["ABC"];
5947 fund(
5948 env,
5949 gw_,
5950 {alice_, carol_, bob_},
5951 XRP(1'000),
5952 {USD(1'000'000'000), abc(1'000'000'000'000)});
5953 AMM amm(env, lp, abc(2'000'000), USD(1));
5954 amm.deposit(alice_, IOUAmount{1'876123487565916, -15});
5955 amm.deposit(carol_, IOUAmount{1'000'000});
5956 amm.withdrawAll(alice_);
5957 amm.withdrawAll(carol_);
5958 auto const lpToken =
5959 getAccountLines(env, lp, amm.lptIssue())[jss::lines][0u][jss::balance];
5960 auto const lpTokenBalance = amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value];
5961 BEAST_EXPECT(lpToken == "1414.213562373095" && lpTokenBalance == "1414.213562373");
5962 amm.withdrawAll(lp);
5963 BEAST_EXPECT(!amm.ammExists());
5964 }
5965
5966 // More than one Liquidity Provider
5967 // XRP/IOU
5968 {
5969 Env env(*this, features);
5970 fund(env, gw_, {alice_}, XRP(1'000), {USD(1'000)});
5971 AMM amm(env, gw_, XRP(10), USD(10));
5972 amm.deposit(alice_, 1'000);
5973 auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw_);
5974 BEAST_EXPECT(res && !res.value());
5975 res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice_);
5976 BEAST_EXPECT(res && !res.value());
5977 }
5978 // IOU/IOU, issuer of both IOU
5979 {
5980 Env env(*this, features);
5981 fund(env, gw_, {alice_}, XRP(1'000), {USD(1'000), EUR(1'000)});
5982 AMM amm(env, gw_, EUR(10), USD(10));
5983 amm.deposit(alice_, 1'000);
5984 auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw_);
5985 BEAST_EXPECT(res && !res.value());
5986 res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice_);
5987 BEAST_EXPECT(res && !res.value());
5988 }
5989 // IOU/IOU, issuer of one IOU
5990 {
5991 Env env(*this, features);
5992 Account const gw1("gw1");
5993 auto const yan = gw1["YAN"];
5994 fund(env, gw_, {gw1}, XRP(1'000), {USD(1'000)});
5995 fund(env, gw1, {gw_}, XRP(1'000), {yan(1'000)}, Fund::TokenOnly);
5996 AMM amm(env, gw1, yan(10), USD(10));
5997 amm.deposit(gw_, 1'000);
5998 auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw_);
5999 BEAST_EXPECT(res && !res.value());
6000 res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw1);
6001 BEAST_EXPECT(res && !res.value());
6002 }
6003 }
6004
6005 void
6007 {
6008 testcase("test clawback from AMM account");
6009 using namespace jtx;
6010
6011 // Issuer has clawback enabled
6012 Env env(*this, features);
6013 env.fund(XRP(1'000), gw_);
6014 env(fset(gw_, asfAllowTrustLineClawback));
6015 fund(env, gw_, {alice_}, XRP(1'000), {USD(1'000)}, Fund::Acct);
6016 env.close();
6017
6018 // If featureAMMClawback is not enabled, AMMCreate is not allowed for
6019 // clawback-enabled issuer
6020 if (!features[featureAMMClawback])
6021 {
6022 AMM const amm(env, gw_, XRP(100), USD(100), Ter(tecNO_PERMISSION));
6023 AMM const amm1(env, alice_, USD(100), XRP(100), Ter(tecNO_PERMISSION));
6024 env(fclear(gw_, asfAllowTrustLineClawback));
6025 env.close();
6026 // Can't be cleared
6027 AMM const amm2(env, gw_, XRP(100), USD(100), Ter(tecNO_PERMISSION));
6028 }
6029 // If featureAMMClawback is enabled, AMMCreate is allowed for
6030 // clawback-enabled issuer. Clawback from the AMM Account is not
6031 // allowed, which will return tecAMM_ACCOUNT or tecPSEUDO_ACCOUNT,
6032 // depending on whether SingleAssetVault is enabled. We can only use
6033 // AMMClawback transaction to claw back from AMM Account.
6034 else
6035 {
6036 AMM const amm(env, gw_, XRP(100), USD(100), Ter(tesSUCCESS));
6037 AMM const amm1(env, alice_, USD(100), XRP(200), Ter(tecDUPLICATE));
6038
6039 // Construct the amount being clawed back using AMM account.
6040 // By doing this, we make the clawback transaction's Amount field's
6041 // subfield `issuer` to be the AMM account, which means
6042 // we are clawing back from an AMM account. This should return an
6043 // error because regular Clawback transaction is not
6044 // allowed for clawing back from an AMM account. Please notice the
6045 // `issuer` subfield represents the account being clawed back, which
6046 // is confusing.
6047 auto const error =
6048 features[featureSingleAssetVault] ? Ter{tecPSEUDO_ACCOUNT} : Ter{tecAMM_ACCOUNT};
6049 Issue const usd(USD.issue().currency, amm.ammAccount());
6050 auto const amount = amountFromString(usd, "10");
6051 env(claw(gw_, amount), error);
6052 }
6053 }
6054
6055 void
6057 {
6058 testcase("test AMMDeposit with frozen assets");
6059 using namespace jtx;
6060
6061 // This lambda function is used to create trustlines
6062 // between gw_ and alice_, and create an AMM account.
6063 // And also test the callback function.
6064 auto const testAMMDeposit = [&](Env& env, std::function<void(AMM & amm)> cb) {
6065 env.fund(XRP(1'000), gw_);
6066 fund(env, gw_, {alice_}, XRP(1'000), {USD(1'000)}, Fund::Acct);
6067 env.close();
6068 AMM amm(env, alice_, XRP(100), USD(100), Ter(tesSUCCESS));
6069 env(trust(gw_, alice_["USD"](0), tfSetFreeze));
6070 cb(amm);
6071 };
6072
6073 // Deposit two assets, one of which is frozen,
6074 // then we should get tecFROZEN error.
6075 {
6076 Env env(*this, features);
6077 testAMMDeposit(env, [&](AMM& amm) {
6078 amm.deposit(alice_, USD(100), XRP(100), std::nullopt, tfTwoAsset, Ter(tecFROZEN));
6079 });
6080 }
6081
6082 // Deposit one asset, which is the frozen token,
6083 // then we should get tecFROZEN error.
6084 {
6085 Env env(*this, features);
6086 testAMMDeposit(env, [&](AMM& amm) {
6087 amm.deposit(
6088 alice_, USD(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecFROZEN));
6089 });
6090 }
6091
6092 if (features[featureAMMClawback] || features[fixCleanup3_3_0])
6093 {
6094 // Deposit one asset which is not the frozen token,
6095 // but the other asset is frozen. tecFROZEN when either
6096 // AMMClawback or fixCleanup3_3_0 is enabled.
6097 Env env(*this, features);
6098 testAMMDeposit(env, [&](AMM& amm) {
6099 amm.deposit(
6100 alice_, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tecFROZEN));
6101 });
6102 }
6103 else
6104 {
6105 // Deposit one asset which is not the frozen token,
6106 // but the other asset is frozen. tesSUCCESS only when
6107 // neither AMMClawback nor fixCleanup3_3_0 is enabled.
6108 Env env(*this, features);
6109 testAMMDeposit(env, [&](AMM& amm) {
6110 amm.deposit(
6111 alice_, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, Ter(tesSUCCESS));
6112 });
6113 }
6114 }
6115
6116 void
6118 {
6119 testcase("Fix Reserve Check On Withdrawal");
6120 using namespace jtx;
6121
6122 auto const err = features[fixAMMv1_2] ? Ter(tecINSUFFICIENT_RESERVE) : Ter(tesSUCCESS);
6123
6124 auto const test = [&](auto&& cb) {
6125 Env env(*this, features);
6126 auto const startingXrp = reserve(env, 2) + env.current()->fees().base * 5;
6127 env.fund(startingXrp, gw_);
6128 env.fund(startingXrp, alice_);
6129 env.trust(USD(2'000), alice_);
6130 env.close();
6131 env(pay(gw_, alice_, USD(2'000)));
6132 env.close();
6133 AMM amm(env, gw_, EUR(1'000), USD(1'000));
6134 amm.deposit(alice_, USD(1));
6135 cb(amm);
6136 };
6137
6138 // Equal withdraw
6139 test([&](AMM& amm) { amm.withdrawAll(alice_, std::nullopt, err); });
6140
6141 // Equal withdraw with a limit
6142 test([&](AMM& amm) {
6143 amm.withdraw(
6145 .account = alice_,
6146 .asset1Out = EUR(0.1),
6147 .asset2Out = USD(0.1),
6148 .err = err,
6149 });
6150 amm.withdraw(
6152 .account = alice_,
6153 .asset1Out = USD(0.1),
6154 .asset2Out = EUR(0.1),
6155 .err = err,
6156 });
6157 });
6158
6159 // Single withdraw
6160 test([&](AMM& amm) {
6161 amm.withdraw(WithdrawArg{.account = alice_, .asset1Out = EUR(0.1), .err = err});
6162 amm.withdraw(WithdrawArg{.account = alice_, .asset1Out = USD(0.1)});
6163 });
6164 }
6165
6166 void
6168 {
6169 using namespace test::jtx;
6170
6171 auto const testCase = [&](std::string suffix, FeatureBitset features) {
6172 testcase("Fail pseudo-account allocation " + suffix);
6173 std::string logs;
6174 Env env{*this, features, std::make_unique<CaptureLogs>(&logs)};
6175 env.fund(XRP(30'000), gw_, alice_);
6176 env.close();
6177 env(trust(alice_, gw_["USD"](30'000), 0));
6178 env(pay(gw_, alice_, USD(10'000)));
6179 env.close();
6180
6181 STAmount const amount = XRP(10'000);
6182 STAmount const amount2 = USD(10'000);
6183 auto const keylet = keylet::amm(amount.asset(), amount2.asset());
6184 for (int i = 0; i < 256; ++i)
6185 {
6186 AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key);
6187
6188 env(pay(env.master.id(), accountId, XRP(1000)),
6189 Seq(kAutofill),
6190 Fee(kAutofill),
6191 Sig(kAutofill));
6192 }
6193
6194 AMM const ammAlice(
6195 env,
6196 alice_,
6197 amount,
6198 amount2,
6199 features[featureSingleAssetVault] ? Ter{terADDRESS_COLLISION} : Ter{tecDUPLICATE});
6200 };
6201
6202 testCase("tecDUPLICATE", testableAmendments() - featureSingleAssetVault);
6203 testCase("terADDRESS_COLLISION", testableAmendments());
6204 }
6205
6206 void
6208 {
6209 testcase("Deposit and Withdraw Rounding V2");
6210 using namespace jtx;
6211
6212 auto const xpm = gw_["XPM"];
6213 STAmount xrpBalance{XRPAmount(692'614'492'126)};
6214 STAmount xpmBalance{xpm, UINT64_C(18'610'359'80246901), -8};
6215 STAmount amount{xpm, UINT64_C(6'566'496939465400), -12};
6216 std::uint16_t const tfee = 941;
6217
6218 auto const test = [&](auto&& cb, std::uint16_t tfee) {
6219 Env env(*this, features);
6220 env.fund(XRP(1'000'000), gw_);
6221 env.fund(XRP(1'000), alice_);
6222 env(trust(alice_, xpm(7'000)));
6223 env(pay(gw_, alice_, amount));
6224
6225 AMM amm(env, gw_, xrpBalance, xpmBalance, CreateArg{.tfee = tfee});
6226 // AMM LPToken balance required to replicate single deposit failure
6227 STAmount const lptAMMBalance{amm.lptIssue(), UINT64_C(3'234'987'266'485968), -6};
6228 auto const burn = IOUAmount{amm.getLPTokensBalance() - lptAMMBalance};
6229 // burn tokens to get to the required AMM state
6230 env(amm.bid(BidArg{.account = gw_, .bidMin = burn, .bidMax = burn}));
6231 cb(amm, env);
6232 };
6233 test(
6234 [&](AMM& amm, Env& env) {
6235 auto const err = env.enabled(fixAMMv1_3) ? Ter(tesSUCCESS) : Ter(tecUNFUNDED_AMM);
6236 amm.deposit(DepositArg{.account = alice_, .asset1In = amount, .err = err});
6237 },
6238 tfee);
6239 test(
6240 [&](AMM& amm, Env& env) {
6241 auto const [amount, amount2, lptAMM] = amm.balances(XRP, xpm);
6242 auto const withdraw = STAmount{xpm, 1, -5};
6243 amm.withdraw(WithdrawArg{.asset1Out = STAmount{xpm, 1, -5}});
6244 auto const [amountAfter, amount2After, lptAMMAfter] = amm.balances(XRP, xpm);
6245 if (!env.enabled(fixAMMv1_3))
6246 {
6247 BEAST_EXPECT((amount2 - amount2After) > withdraw);
6248 }
6249 else
6250 {
6251 BEAST_EXPECT((amount2 - amount2After) <= withdraw);
6252 }
6253 },
6254 0);
6255 }
6256
6257 void
6258 invariant(jtx::AMM& amm, jtx::Env& env, std::string const& msg, bool shouldFail)
6259 {
6260 auto const [amount, amount2, lptBalance] = amm.balances(GBP, EUR);
6261
6263 NumberRoundModeGuard const g(
6265 auto const res = root2(amount * amount2);
6266
6267 if (shouldFail)
6268 {
6269 BEAST_EXPECT(res < lptBalance);
6270 }
6271 else
6272 {
6273 BEAST_EXPECT(res >= lptBalance);
6274 }
6275 }
6276
6277 void
6279 {
6280 testcase("Deposit Rounding");
6281 using namespace jtx;
6282
6283 // Single asset deposit
6284 for (auto const& deposit : {
6285 STAmount(EUR, 1, 1),
6286 STAmount(EUR, 1, 2),
6287 STAmount(EUR, 1, 5),
6288 STAmount(EUR, 1, -3), // fail
6289 STAmount(EUR, 1, -6),
6290 STAmount(EUR, 1, -9),
6291 })
6292 {
6293 testAMM(
6294 [&](AMM& ammAlice, Env& env) {
6295 fund(
6296 env,
6297 gw_,
6298 {bob_},
6299 XRP(10'000'000),
6300 {GBP(100'000), EUR(100'000)},
6301 Fund::Acct);
6302 env.close();
6303
6304 ammAlice.deposit(DepositArg{.account = bob_, .asset1In = deposit});
6305 invariant(
6306 ammAlice,
6307 env,
6308 "dep1",
6309 deposit == STAmount{EUR, 1, -3} && !env.enabled(fixAMMv1_3));
6310 },
6311 {{GBP(30'000), EUR(30'000)}},
6312 0,
6313 std::nullopt,
6314 {all});
6315 }
6316
6317 // Two-asset proportional deposit (1:1 pool ratio)
6318 testAMM(
6319 [&](AMM& ammAlice, Env& env) {
6320 fund(env, gw_, {bob_}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct);
6321 env.close();
6322
6323 STAmount const depositEuro{EUR, UINT64_C(10'1234567890123456), -16};
6324 STAmount const depositGBP{GBP, UINT64_C(10'1234567890123456), -16};
6325
6326 ammAlice.deposit(
6327 DepositArg{.account = bob_, .asset1In = depositEuro, .asset2In = depositGBP});
6328 invariant(ammAlice, env, "dep2", false);
6329 },
6330 {{GBP(30'000), EUR(30'000)}},
6331 0,
6332 std::nullopt,
6333 {all});
6334
6335 // Two-asset proportional deposit (1:3 pool ratio)
6336 for (auto const& exponent : {1, 2, 3, 4, -3 /*fail*/, -6, -9})
6337 {
6338 testAMM(
6339 [&](AMM& ammAlice, Env& env) {
6340 fund(
6341 env,
6342 gw_,
6343 {bob_},
6344 XRP(10'000'000),
6345 {GBP(100'000), EUR(100'000)},
6346 Fund::Acct);
6347 env.close();
6348
6349 STAmount const depositEuro{EUR, 1, exponent};
6350 STAmount const depositGBP{GBP, 1, exponent};
6351
6352 ammAlice.deposit(
6353 DepositArg{
6354 .account = bob_,
6355 .asset1In = depositEuro,
6356 .asset2In = depositGBP,
6357 });
6358 invariant(ammAlice, env, "dep3", exponent != -3 && !env.enabled(fixAMMv1_3));
6359 },
6360 {{GBP(10'000), EUR(30'000)}},
6361 0,
6362 std::nullopt,
6363 {all});
6364 }
6365
6366 // tfLPToken deposit
6367 testAMM(
6368 [&](AMM& ammAlice, Env& env) {
6369 fund(env, gw_, {bob_}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct);
6370 env.close();
6371
6372 ammAlice.deposit(
6373 DepositArg{.account = bob_, .tokens = IOUAmount{10'1234567890123456, -16}});
6374 invariant(ammAlice, env, "dep4", false);
6375 },
6376 {{GBP(7'000), EUR(30'000)}},
6377 0,
6378 std::nullopt,
6379 {all});
6380
6381 // tfOneAssetLPToken deposit
6382 for (auto const& tokens : {
6383 IOUAmount{1, -3},
6384 IOUAmount{1, -2},
6385 IOUAmount{1, -1},
6386 IOUAmount{1},
6387 IOUAmount{10},
6388 IOUAmount{100},
6389 IOUAmount{1'000},
6390 IOUAmount{10'000},
6391 })
6392 {
6393 testAMM(
6394 [&](AMM& ammAlice, Env& env) {
6395 fund(
6396 env,
6397 gw_,
6398 {bob_},
6399 XRP(10'000'000),
6400 {GBP(100'000), EUR(1'000'000)},
6401 Fund::Acct);
6402 env.close();
6403
6404 ammAlice.deposit(
6405 DepositArg{
6406 .account = bob_,
6407 .tokens = tokens,
6408 .asset1In = STAmount{EUR, 1, 6},
6409 });
6410 invariant(ammAlice, env, "dep5", false);
6411 },
6412 {{GBP(7'000), EUR(30'000)}},
6413 0,
6414 std::nullopt,
6415 {all});
6416 }
6417
6418 // Single deposit with EP not exceeding specified:
6419 // 1'000 GBP with EP not to exceed 5 (GBP/TokensOut)
6420 testAMM(
6421 [&](AMM& ammAlice, Env& env) {
6422 fund(env, gw_, {bob_}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct);
6423 env.close();
6424
6425 ammAlice.deposit(bob_, GBP(1'000), std::nullopt, STAmount{GBP, 5});
6426 invariant(ammAlice, env, "dep6", false);
6427 },
6428 {{GBP(30'000), EUR(30'000)}},
6429 0,
6430 std::nullopt,
6431 {all});
6432 }
6433
6434 void
6436 {
6437 testcase("Withdraw Rounding");
6438
6439 using namespace jtx;
6440
6441 // tfLPToken mode
6442 testAMM(
6443 [&](AMM& ammAlice, Env& env) {
6444 ammAlice.withdraw(alice_, 1'000);
6445 invariant(ammAlice, env, "with1", false);
6446 },
6447 {{GBP(7'000), EUR(30'000)}},
6448 0,
6449 std::nullopt,
6450 {all});
6451
6452 // tfWithdrawAll mode
6453 testAMM(
6454 [&](AMM& ammAlice, Env& env) {
6455 ammAlice.withdraw(WithdrawArg{.account = alice_, .flags = tfWithdrawAll});
6456 invariant(ammAlice, env, "with2", false);
6457 },
6458 {{GBP(7'000), EUR(30'000)}},
6459 0,
6460 std::nullopt,
6461 {all});
6462
6463 // tfTwoAsset withdraw mode
6464 testAMM(
6465 [&](AMM& ammAlice, Env& env) {
6466 ammAlice.withdraw(
6468 .account = alice_,
6469 .asset1Out = STAmount{GBP, 3'500},
6470 .asset2Out = STAmount{EUR, 15'000},
6471 .flags = tfTwoAsset,
6472 });
6473 invariant(ammAlice, env, "with3", false);
6474 },
6475 {{GBP(7'000), EUR(30'000)}},
6476 0,
6477 std::nullopt,
6478 {all});
6479
6480 // tfSingleAsset withdraw mode
6481 // Note: This test fails with 0 trading fees, but doesn't fail if
6482 // trading fees is set to 1'000 -- I suspect the compound operations
6483 // in AMMHelpers.cpp:ammAssetOut compensate for the rounding
6484 // errors
6485 testAMM(
6486 [&](AMM& ammAlice, Env& env) {
6487 ammAlice.withdraw(
6489 .account = alice_,
6490 .asset1Out = STAmount{GBP, 1'234},
6491 .flags = tfSingleAsset,
6492 });
6493 invariant(ammAlice, env, "with4", false);
6494 },
6495 {{GBP(7'000), EUR(30'000)}},
6496 0,
6497 std::nullopt,
6498 {all});
6499
6500 // tfOneAssetWithdrawAll mode
6501 testAMM(
6502 [&](AMM& ammAlice, Env& env) {
6503 fund(env, gw_, {bob_}, XRP(10'000'000), {GBP(100'000), EUR(100'000)}, Fund::Acct);
6504 env.close();
6505
6506 ammAlice.deposit(DepositArg{.account = bob_, .asset1In = STAmount{GBP, 3'456}});
6507
6508 ammAlice.withdraw(
6510 .account = bob_,
6511 .asset1Out = STAmount{GBP, 1'000},
6512 .flags = tfOneAssetWithdrawAll,
6513 });
6514 invariant(ammAlice, env, "with5", false);
6515 },
6516 {{GBP(7'000), EUR(30'000)}},
6517 0,
6518 std::nullopt,
6519 {all});
6520
6521 // tfOneAssetLPToken mode
6522 testAMM(
6523 [&](AMM& ammAlice, Env& env) {
6524 ammAlice.withdraw(
6526 .account = alice_,
6527 .tokens = 1'000,
6528 .asset1Out = STAmount{GBP, 100},
6529 .flags = tfOneAssetLPToken,
6530 });
6531 invariant(ammAlice, env, "with6", false);
6532 },
6533 {{GBP(7'000), EUR(30'000)}},
6534 0,
6535 std::nullopt,
6536 {all});
6537
6538 // tfLimitLPToken mode
6539 testAMM(
6540 [&](AMM& ammAlice, Env& env) {
6541 ammAlice.withdraw(
6543 .account = alice_,
6544 .asset1Out = STAmount{GBP, 100},
6545 .maxEP = IOUAmount{2},
6546 .flags = tfLimitLPToken,
6547 });
6548 invariant(ammAlice, env, "with7", true);
6549 },
6550 {{GBP(7'000), EUR(30'000)}},
6551 0,
6552 std::nullopt,
6553 {all});
6554 }
6555
6556 void
6558 {
6559 testcase("Test AuthAccounts reset after empty pool reinitialization");
6560 using namespace jtx;
6561
6562 Env env(
6563 *this,
6565 cfg->fees.referenceFee = XRPAmount(1);
6566 return cfg;
6567 }),
6568 features);
6569 Account const dan("dan");
6570 Account const ed("ed");
6571 fund(env, gw_, {alice_, carol_, bob_, dan, ed}, XRP(50'000), {USD(50'000)});
6572 AMM amm(env, alice_, XRP(10'000), USD(10'000));
6573 // Create excess trustlines to prevent AMM auto-deletion on withdrawal.
6574 for (auto i = 0; i < kMaxDeletableAmmTrustLines + 10; ++i)
6575 {
6576 Account const a{std::to_string(i)};
6577 env.fund(XRP(1'000), a);
6578 env(trust(a, STAmount{amm.lptIssue(), 10'000}));
6579 env.close();
6580 }
6581 // Carol deposits so she has LP tokens to bid.
6582 amm.deposit(carol_, 1'000'000);
6583 // Carol wins the auction slot, authorizing bob and dan.
6584 env(amm.bid({
6585 .account = carol_,
6586 .bidMin = 100,
6587 .authAccounts = {bob_, dan},
6588 }));
6589 env.close();
6590 BEAST_EXPECT(amm.expectAuctionSlot({bob_.id(), dan.id()}));
6591 // Withdraw all — AMM enters empty state but is not deleted because
6592 // excess trustlines prevent auto-deletion.
6593 amm.withdrawAll(alice_);
6594 amm.withdrawAll(carol_);
6595 BEAST_EXPECT(amm.ammExists());
6596 // Pre-conditions before re-init: AMM is empty and stale sfAuthAccounts
6597 // from carol's bid are still present.
6598 BEAST_EXPECT(amm.getLPTokensBalance() == IOUAmount{0});
6599 BEAST_EXPECT(amm.expectAuctionSlot({bob_.id(), dan.id()}));
6600 // Ed re-initializes the AMM via tfTwoAssetIfEmpty with fee=500.
6601 amm.deposit(
6602 ed,
6603 std::nullopt,
6604 XRP(10'000),
6605 USD(10'000),
6606 std::nullopt,
6607 tfTwoAssetIfEmpty,
6608 std::nullopt,
6609 std::nullopt,
6610 500);
6611
6612 auto const ammSle = env.current()->read(keylet::amm(amm[0], amm[1]));
6613 BEAST_EXPECT(ammSle && ammSle->isFieldPresent(sfAuctionSlot));
6614 auto const& slot = safeDowncast<STObject const&>(ammSle->peekAtField(sfAuctionSlot));
6615
6616 // sfDiscountedFee = 500 / AUCTION_SLOT_DISCOUNTED_FEE_FRACTION = 50,
6617 // sfPrice = 0 (reset on init), time interval = 0 (freshly issued slot).
6618 BEAST_EXPECT(amm.expectAuctionSlot(50, 0, IOUAmount{0}));
6619 // sfAccount must be the re-initializing depositor, not the previous
6620 // slot holder (carol).
6621 BEAST_EXPECT(slot[sfAccount] == ed.id());
6622 // sfTradingFee on the AMM SLE must reflect ed's deposit fee.
6623 BEAST_EXPECT(ammSle->getFieldU16(sfTradingFee) == 500);
6624 // sfVoteSlots must be reset to a single entry for ed.
6625 auto const& votes = ammSle->getFieldArray(sfVoteSlots);
6626 BEAST_EXPECT(votes.size() == 1);
6627 if (!votes.empty())
6628 {
6629 BEAST_EXPECT(votes[0].getAccountID(sfAccount) == ed.id());
6630 BEAST_EXPECT(votes[0].getFieldU16(sfTradingFee) == 500);
6631 BEAST_EXPECT(votes[0].getFieldU32(sfVoteWeight) == kVoteWeightScaleFactor);
6632 }
6633 // sfAuthAccounts behaviour depends on the fix.
6634 if (features[fixCleanup3_2_0])
6635 {
6636 BEAST_EXPECT(!slot.isFieldPresent(sfAuthAccounts));
6637 }
6638 else
6639 {
6640 BEAST_EXPECT(
6641 slot.isFieldPresent(sfAuthAccounts) && !slot.getFieldArray(sfAuthAccounts).empty());
6642 }
6643 }
6644
6645 void
6647 {
6648 testcase("Deposit integral overflow");
6649
6650 using namespace jtx;
6651 auto const all = testableAmendments();
6652
6653 // Found by Antithesis: two-asset deposit with a huge Amount against a
6654 // tiny pool leg makes frac = Amount/amountBalance enormous, so the
6655 // computed XRP-side deposit exceeds the integral asset's range and the
6656 // conversion to an STAmount throws out of doApply.
6657 //
6658 // applyGuts catches std::runtime_error around the deposit math, which
6659 // covers both ways the conversion can throw:
6660 // - value beyond int64 range: Number::operator rep() throws
6661 // std::overflow_error (a std::runtime_error); and
6662 // - value within int64 but above the asset maximum (kMaxNativeN):
6663 // STAmount::canonicalize throws std::runtime_error.
6664 // XRP(10) is 1e7 drops, so the computed XRP leg is 1e7 * frac:
6665 // asset1In 1e15 => frac ~1e15 => ~1e22 drops, past int64max; and
6666 // asset1In 1e11 => frac ~1e11 => ~1e18 drops, in [kMaxNativeN=1e17,
6667 // int64max) - the canonicalize band, which would otherwise escape.
6668 //
6669 // Without fixCleanup3_4_0 the exception escapes and is converted to
6670 // tefEXCEPTION by applySteps. With the amendment, applyGuts guards it
6671 // and fails cleanly with tecAMM_FAILED.
6672 auto const test = [this](FeatureBitset features, STAmount const& asset1In, TER expected) {
6673 // These deposits intentionally trigger the overflow, which logs
6674 // at error (guarded) or fatal (legacy tefEXCEPTION). Disable the
6675 // log threshold to keep the test output clean.
6676 Env env(*this, envconfig(), features, nullptr, beast::Severity::Disabled);
6677 env.fund(XRP(30'000), gw_, alice_);
6678 env(trust(alice_, STAmount{USD, 1, 20}));
6679 env(pay(gw_, alice_, STAmount{USD, 1, 18}));
6680 env.close();
6681
6682 AMM amm(env, gw_, XRP(10), USD(1));
6683 amm.deposit(
6684 DepositArg{
6685 .account = alice_,
6686 .asset1In = asset1In,
6687 .asset2In = XRP(1),
6688 .err = Ter(expected),
6689 });
6690 };
6691
6692 // int64-range band (overflow_error): legacy escapes as tefEXCEPTION,
6693 // fixed returns a tec.
6694 test(all - fixCleanup3_4_0, STAmount{USD, 1, 15}, tefEXCEPTION);
6695 test(all, STAmount{USD, 1, 15}, tecAMM_FAILED);
6696 // canonicalize band (runtime_error): same behavior. Regression guard
6697 // for the band a plain overflow_error catch would miss.
6698 test(all - fixCleanup3_4_0, STAmount{USD, 1, 11}, tefEXCEPTION);
6699 test(all, STAmount{USD, 1, 11}, tecAMM_FAILED);
6700 }
6701
6702 void
6704 {
6705 testcase("Deposit EPrice integral overflow");
6706
6707 using namespace jtx;
6708 auto const all = testableAmendments();
6709
6710 // Found by Antithesis: a one-sided tfLimitLPToken deposit (Amount and
6711 // EPrice) with Amount = 0 and a large EPrice makes the solved pool-side
6712 // deposit enormous, so it exceeds the integral asset's range and the
6713 // conversion to an STAmount throws out of doApply. This is the
6714 // singleDepositEPrice sibling of testDepositIntegralOverflow.
6715 //
6716 // applyGuts catches std::runtime_error around the deposit math, which
6717 // covers both ways the conversion can throw:
6718 // - value beyond int64 range: Number::operator rep() throws
6719 // std::overflow_error (a std::runtime_error); and
6720 // - value within int64 but above the asset maximum (kMaxNativeN):
6721 // STAmount::canonicalize throws std::runtime_error.
6722 //
6723 // Without fixCleanup3_4_0 the exception escapes and is converted to
6724 // tefEXCEPTION by applySteps. With the amendment, applyGuts guards it
6725 // and fails cleanly with tecAMM_FAILED.
6726 auto const test = [this](FeatureBitset features, STAmount const& ePrice, TER expected) {
6727 // These deposits intentionally trigger the overflow, which logs
6728 // at error (guarded) or fatal (legacy tefEXCEPTION). Disable the
6729 // log threshold to keep the test output clean.
6730 Env env(*this, envconfig(), features, nullptr, beast::Severity::Disabled);
6731 env.fund(XRP(30'000), gw_, alice_);
6732 env(trust(alice_, STAmount{USD, 1, 20}));
6733 env(pay(gw_, alice_, STAmount{USD, 1, 18}));
6734 env.close();
6735
6736 AMM amm(env, gw_, XRP(10), USD(1));
6737 // Amount = 0 (XRP), EPrice large => tfLimitLPToken. The solved XRP
6738 // leg blows past the integral range.
6739 amm.deposit(
6740 DepositArg{
6741 .account = alice_,
6742 .asset1In = XRP(0),
6743 .maxEP = ePrice,
6744 .err = Ter(expected),
6745 });
6746 };
6747
6748 // For this XRP(10)/USD(1) pool the LPToken balance is
6749 // sqrt(1e7 drops * 1) = 3162, so T^2/B = 1e7/1e7 = 1 and the solved
6750 // XRP-side deposit is ~EPrice^2 drops.
6751 //
6752 // int64-range band (overflow_error): legacy escapes as tefEXCEPTION,
6753 // fixed returns a tec. EPrice ~1e17 drops => solved deposit ~1e34 drops,
6754 // past int64max, so Number::operator rep() throws.
6755 auto const bigEP = STAmount{XRPAmount{99'999'999'999'999'999}};
6756 test(all - fixCleanup3_4_0, bigEP, tefEXCEPTION);
6757 test(all, bigEP, tecAMM_FAILED);
6758 // canonicalize band (runtime_error): same behavior. Regression guard
6759 // for the band a plain overflow_error catch would miss. EPrice 1e9 drops
6760 // => solved deposit ~1e18 drops, in [kMaxNativeN=1e17, int64max), so
6761 // STAmount::canonicalize throws.
6762 auto const midEP = STAmount{XRPAmount{1'000'000'000}};
6763 test(all - fixCleanup3_4_0, midEP, tefEXCEPTION);
6764 test(all, midEP, tecAMM_FAILED);
6765 }
6766
6767 void
6769 {
6770 testcase("Withdraw integral no overflow");
6771
6772 using namespace jtx;
6773 auto const all = testableAmendments();
6774
6775 // Regression guard for the sibling of testDepositIntegralOverflow.
6776 // AMMWithdraw::equalWithdrawLimit has the same
6777 // getRoundedAsset(integralBalance, frac) structure as the deposit
6778 // path and is likewise not wrapped in a try/catch. It is safe only
6779 // because withdraw preclaim (checkAmount) rejects a requested Amount
6780 // greater than the pool balance with tecAMM_BALANCE *before* the math
6781 // runs, so frac = Amount / balance stays <= 1 and the Number ->
6782 // integral STAmount conversion cannot overflow. Deposit has no such
6783 // bound (depositing more than the pool holds is legal), which is why
6784 // only the deposit path was exposed.
6785 //
6786 // This asserts the withdrawal analog of the deposit repro fails cleanly
6787 // with a tec. If the preclaim bound is ever weakened, equalWithdrawLimit
6788 // would be reached with a huge frac and Number::operator rep() would
6789 // escape as tefEXCEPTION, failing this test.
6790 auto const test = [this](FeatureBitset features) {
6791 Env env(*this, features);
6792 env.fund(XRP(30'000), gw_, alice_);
6793 env(trust(alice_, STAmount{USD, 1, 20}));
6794 env(pay(gw_, alice_, STAmount{USD, 1, 18}));
6795 env.close();
6796
6797 // gw holds all LPTokens of a tiny XRP/USD pool.
6798 AMM amm(env, gw_, XRP(10), USD(1));
6799
6800 // Two-asset limit withdraw (tfTwoAsset) requesting far more of the
6801 // tiny USD leg than the pool holds - the mirror of the deposit
6802 // repro. Rejected upstream, so no overflow is possible.
6803 amm.withdraw(
6805 .account = gw_,
6806 .asset1Out = STAmount{USD, 1, 15},
6807 .asset2Out = XRP(1),
6808 .err = Ter(tecAMM_BALANCE),
6809 });
6810 };
6811
6812 test(all);
6813 }
6814
6815 void
6816 run() override
6817 {
6818 FeatureBitset const all{testableAmendments()};
6821 for (auto const& f : amendmentCombinations({fixCleanup3_3_0, featureAMMClawback}))
6823 testDeposit();
6825 testWithdraw();
6827 testFeeVote();
6829 testBid(all);
6830 testBid(all - fixCleanup3_4_0);
6831 testBid(all - fixAMMv1_3);
6834 testBasicPaymentEngine(all - fixAMMv1_3);
6835 testBasicPaymentEngine(all - fixReducedOffersV2);
6836 testBasicPaymentEngine(all - fixAMMv1_3 - fixReducedOffersV2);
6837 testAMMTokens();
6838 testFlags();
6839 testRippling();
6840 testAMMAndCLOB(all);
6841 testAMMAndCLOB(all - fixAMMv1_3);
6842 testTradingFee(all);
6843 testTradingFee(all - fixAMMv1_3);
6844 testAdjustedTokens(all);
6845 testAdjustedTokens(all - fixAMMv1_3);
6847 testClawback();
6848 testAMMID();
6849 testSelection(all);
6850 testSelection(all - fixAMMv1_3);
6852 testMalformed();
6853 testOverflowOffer(all);
6854 testOverflowOffer(all - fixAMMv1_3);
6857 testFixChangeSpotPriceQuality(all - fixAMMv1_3);
6859 testFixAMMOfferBlockedByLOB(all - fixAMMv1_3);
6860 testLPTokenBalance(all);
6861 testLPTokenBalance(all - fixAMMv1_3);
6862 testAMMClawback(all);
6863 testAMMClawback(all - featureSingleAssetVault);
6864 testAMMClawback(all - featureAMMClawback - featureSingleAssetVault);
6865 testAMMClawback(all - featureAMMClawback);
6866 testAMMClawback(all - fixAMMv1_3 - featureAMMClawback);
6867 for (auto const& f : amendmentCombinations({fixCleanup3_3_0, featureAMMClawback}))
6869 testAMMDepositWithFrozenAssets(all - featureAMMClawback);
6870 testAMMDepositWithFrozenAssets(all - fixAMMv1_3 - featureAMMClawback);
6872 testFixReserveCheckOnWithdrawal(all - fixAMMv1_2);
6874 testDepositAndWithdrawRounding(all - fixAMMv1_3);
6876 testDepositRounding(all - fixAMMv1_3);
6878 testWithdrawRounding(all - fixAMMv1_3);
6881 testStaleAuthAccountsAfterReinit(all - fixCleanup3_2_0);
6885 }
6886};
6887
6889
6890} // namespace xrpl::test
void pass()
Record a successful test condition.
Definition suite.h:532
void fail(String const &reason, char const *file, int line)
Record a failure.
Definition suite.h:554
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
Represents a JSON value.
Definition json_value.h:121
UInt asUInt() const
RAII class to set and restore the current transaction rules.
Definition Rules.h:113
Floating point representation of amounts with high dynamic range.
Definition IOUAmount.h:26
A currency issued by an account.
Definition Issue.h:18
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
Sets the new scale and restores the old scale when it leaves scope.
Definition Number.h:967
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static RoundingMode getround()
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
Asset const & asset() const
Definition STAmount.h:496
json::Value getJson(JsonOptions) const override
Definition STIssue.cpp:88
jtx::Account const alice_
Definition AMMTest.h:87
void testAMM(std::function< void(jtx::AMM &, jtx::Env &)> const &cb, std::optional< std::pair< STAmount, STAmount > > const &pool=std::nullopt, std::uint16_t tfee=0, std::optional< jtx::Ter > const &ter=std::nullopt, std::vector< FeatureBitset > const &features={testableAmendments()})
testAMM() funds 30,000XRP and 30,000IOU for each non-XRP asset to Alice and Carol
Definition AMMTest.cpp:120
jtx::Account const gw_
Definition AMMTest.h:85
jtx::Account const carol_
Definition AMMTest.h:86
jtx::Account const bob_
Definition AMMTest.h:88
static XRPAmount reserve(jtx::Env &env, std::uint32_t count)
Definition AMMTest.cpp:199
static XRPAmount ammCrtFee(jtx::Env &env)
Definition AMMTest.cpp:205
Convenience class to test AMM functionality.
bool expectTradingFee(std::uint16_t fee) const
Definition AMM.cpp:337
json::Value bid(BidArg const &arg)
Definition AMM.cpp:735
IOUAmount getLPTokensBalance(std::optional< AccountID > const &account=std::nullopt) const
Definition AMM.cpp:282
bool ammExists() const
Definition AMM.cpp:344
IOUAmount withdrawAll(std::optional< Account > const &account, std::optional< STAmount > const &asset1OutDetails=std::nullopt, std::optional< Ter > const &ter=std::nullopt)
bool expectAuctionSlot(std::uint32_t fee, std::optional< std::uint8_t > timeSlot, IOUAmount expectedPrice) const
Definition AMM.cpp:307
IOUAmount tokens() const
IOUAmount deposit(std::optional< Account > const &account, LPToken tokens, std::optional< STAmount > const &asset1InDetails=std::nullopt, std::optional< std::uint32_t > const &flags=std::nullopt, std::optional< Ter > const &ter=std::nullopt)
Definition AMM.cpp:463
IOUAmount withdraw(std::optional< Account > const &account, std::optional< LPToken > const &tokens, std::optional< STAmount > const &asset1OutDetails=std::nullopt, std::optional< std::uint32_t > const &flags=std::nullopt, std::optional< Ter > const &ter=std::nullopt)
Definition AMM.cpp:605
json::Value ammRpcInfo(std::optional< AccountID > const &account=std::nullopt, std::optional< std::string > const &ledgerIndex=std::nullopt, std::optional< Asset > const &asset1=std::nullopt, std::optional< Asset > const &asset2=std::nullopt, std::optional< AccountID > const &ammAccount=std::nullopt, bool ignoreParams=false, unsigned apiVersion=rpc::kApiInvalidVersion) const
Send amm_info RPC command.
Definition AMM.cpp:183
AccountID const & ammAccount() const
void setTokens(json::Value &jv, std::optional< std::pair< Asset, Asset > > const &assets=std::nullopt)
Definition AMM.cpp:392
void vote(std::optional< Account > const &account, std::uint32_t feeVal, std::optional< std::uint32_t > const &flags=std::nullopt, std::optional< jtx::Seq > const &seq=std::nullopt, std::optional< std::pair< Asset, Asset > > const &assets=std::nullopt, std::optional< Ter > const &ter=std::nullopt)
Definition AMM.cpp:709
bool expectLPTokens(AccountID const &account, IOUAmount const &tokens) const
Definition AMM.cpp:296
bool expectBalances(STAmount const &asset1, STAmount const &asset2, IOUAmount const &lpt, std::optional< AccountID > const &account=std::nullopt) const
Verify the AMM balances.
Definition AMM.cpp:269
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
AccountID id() const
Returns the Account ID.
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
bool enabled(UInt256 feature) const
Definition Env.h:886
std::shared_ptr< ReadView const > closed()
Returns the last closed ledger.
Definition Env.cpp:127
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
Account const & master
Definition Env.h:165
json::Value rpc(unsigned apiVersion, std::unordered_map< std::string, std::string > const &headers, std::string const &cmd, Args &&... args)
Execute an RPC command.
Definition Env.h:1058
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
std::shared_ptr< STObject const > meta()
Return metadata for the last JTx.
Definition Env.cpp:538
void memoize(Account const &account)
Associate AccountID with account.
Definition Env.cpp:174
beast::Journal const journal
Definition Env.h:204
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
NetClock::time_point now()
Returns the current network time.
Definition Env.h:326
Set the fee on a JTx.
Definition fee.h:20
Add a path.
Definition paths.h:47
Sets the SendMax on a JTx.
Definition sendmax.h:16
Set the regular signature on a JTx.
Definition sig.h:19
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 make_pair(T... args)
T make_unique(T... args)
@ Object
object value (collection of name/value pairs).
Definition json_value.h:33
Keylet computation functions.
Definition Indexes.h:39
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Definition Indexes.cpp:415
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
json::Value create(A const &account, A const &dest, STAmount const &sendMax)
Create a check.
Deposit preauthorize operations.
Definition deposit.h:16
json::Value create(AccountID const &account, AccountID const &to, STAmount const &amount)
Definition escrow.cpp:24
auto const kCondition
Definition escrow.h:100
auto const kCancelTime
Set the "CancelAfter" time tag on a JTx.
Definition escrow.h:98
auto const kFinishTime
Set the "FinishAfter" time tag on a JTx.
Definition escrow.h:93
std::array< std::uint8_t, 39 > const kCb1
Definition escrow.h:60
json::Value create(AccountID const &account, AccountID const &to, STAmount const &amount, NetClock::duration const &settleDelay, PublicKey const &pk, std::optional< NetClock::time_point > const &cancelAfter, std::optional< std::uint32_t > const &dstTag)
Definition paychan.cpp:31
json::Value claw(Account const &account, STAmount const &amount, std::optional< Account > const &mptHolder)
Definition trust.cpp:51
json::Value pay(AccountID const &account, AccountID const &to, AnyAmount amount)
Create a payment.
Definition pay.cpp:14
std::vector< STAmount > fund(jtx::Env &env, jtx::Account const &gw, std::vector< jtx::Account > const &accounts, std::vector< STAmount > const &amts, Fund how)
Definition AMMTest.cpp:34
bool expectLedgerEntryRoot(Env &env, Account const &acct, STAmount const &expectedValue)
bool expectHolding(Env const &env, AccountID const &account, STAmount const &value, bool defaultLimits)
std::vector< FeatureBitset > amendmentCombinations(std::initializer_list< UInt256 > features, FeatureBitset seed)
Returns all 2^N permutations of a seed FeatureBitset with each subset of the given features excluded.
Definition Env.h:123
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)
json::Value fclear(Account const &account, std::uint32_t off)
Remove account flag.
Definition flags.h:110
FeatureBitset testableAmendments()
Definition Env.h:92
json::Value offer(Account const &account, STAmount const &takerPays, STAmount const &takerGets, std::uint32_t flags)
Create an offer.
Definition offer.cpp:14
std::unique_ptr< Config > envconfig()
creates and initializes a default configuration for jtx::Env
Definition envconfig.h:38
json::Value trust(Account const &account, STAmount const &amount, std::uint32_t flags)
Modify a trust line.
Definition trust.cpp:18
static AutofillT const kAutofill
Definition tags.h:15
PrettyAmount drops(Integer i)
Returns an XRP PrettyAmount, which is trivially convertible to STAmount.
json::Value accountBalance(Env &env, Account const &acct)
json::Value rate(Account const &account, double multiplier)
Set a transfer rate.
Definition rate.cpp:15
json::Value getAccountLines(Env &env, AccountID const &acctId)
json::Value getAccountOffers(Env &env, AccountID const &acct, bool current)
json::Value fset(Account const &account, std::uint32_t on, std::uint32_t off=0)
Add and/or remove flag.
Definition flags.cpp:15
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
@ telINSUF_FEE_P
Definition TER.h:43
@ terNO_AMM
Definition TER.h:229
@ terNO_RIPPLE
Definition TER.h:226
@ terADDRESS_COLLISION
Definition TER.h:230
@ terNO_ACCOUNT
Definition TER.h:219
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
constexpr std::uint32_t kTotalTimeSlotSecs
Definition AMMCore.h:19
bool isXRP(AccountID const &c)
Definition AccountID.h:84
Number ammAuctionMinSlotPrice(Number const &lptAMMBalance, std::uint16_t tradingFee)
Minimum auction slot price: LPTokens * TradingFee / kAuctionSlotMinFeeFraction.
Definition AMMCore.h:94
std::expected< bool, TER > isOnlyLiquidityProvider(ReadView const &view, Issue const &ammIssue, AccountID const &lpAccount)
Return true if the Liquidity Provider is the only AMM provider, false otherwise.
TAmounts< STAmount, STAmount > Amounts
Definition Quality.h:69
@ tefEXCEPTION
Definition TER.h:166
@ Fail
Should not be retried in this ledger.
Definition apply.h:132
BaseUInt< 160, detail::CurrencyTag > Currency
Currency is a hash representing a specific currency.
Definition UintTypes.h:42
STAmount amountFromString(Asset const &asset, std::string const &amount)
TOut swapAssetIn(TAmounts< TIn, TOut > const &pool, TIn const &assetIn, std::uint16_t tfee)
AMM pool invariant - the product (A * B) after swap in/out has to remain at least the same: (A + in) ...
Definition AMMHelpers.h:397
STAmount ammAssetOut(STAmount const &assetBalance, STAmount const &lptAMMBalance, STAmount const &lpTokens, std::uint16_t tfee)
Calculate asset withdrawal by tokens.
constexpr std::uint16_t kMaxDeletableAmmTrustLines
The maximum number of trustlines to delete as part of AMM account deletion cleanup.
Definition Protocol.h:436
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
T toAmount(STAmount const &amt)=delete
Asset getAsset(T const &amt)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
std::optional< TAmounts< TIn, TOut > > changeSpotPriceQuality(TAmounts< TIn, TOut > const &pool, Quality const &quality, std::uint16_t tfee, beast::Journal j)
Generate AMM offer so that either updated Spot Price Quality (SPQ) is equal to LOB quality (in this c...
Definition AMMHelpers.h:328
std::optional< Number > solveQuadraticEqSmallest(Number const &a, Number const &b, Number const &c)
Solve quadratic equation to find takerGets or takerPays.
AccountID pseudoAccountAddress(ReadView const &view, UInt256 const &pseudoOwnerKey)
Generate a pseudo-account address from a pseudo owner key.
Number root2(Number f)
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
constexpr std::uint16_t kAuctionSlotTimeIntervals
Definition AMMCore.h:20
@ temBAD_CURRENCY
Definition TER.h:78
@ temBAD_FEE
Definition TER.h:80
@ temBAD_AMM_TOKENS
Definition TER.h:117
@ temINVALID_FLAG
Definition TER.h:99
@ temMALFORMED
Definition TER.h:75
@ temBAD_AMOUNT
Definition TER.h:77
Dest safeDowncast(Src *s) noexcept
Definition safe_cast.h:84
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TIn swapAssetOut(TAmounts< TIn, TOut > const &pool, TOut const &assetOut, std::uint16_t tfee)
Swap assetOut out of the pool and swap in a proportional amount of the other asset.
Definition AMMHelpers.h:456
TERSubset< CanCvtToTER > TER
Definition TER.h:657
Issue const & noIssue()
Returns an asset specifier that represents no account and currency.
Definition Issue.h:118
@ tecPSEUDO_ACCOUNT
Definition TER.h:373
@ tecAMM_EMPTY
Definition TER.h:343
@ tecPATH_PARTIAL
Definition TER.h:293
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecINSUF_RESERVE_LINE
Definition TER.h:299
@ tecAMM_FAILED
Definition TER.h:341
@ tecAMM_NOT_EMPTY
Definition TER.h:344
@ tecPATH_DRY
Definition TER.h:305
@ tecINCOMPLETE
Definition TER.h:346
@ tecUNFUNDED_AMM
Definition TER.h:339
@ tecNO_AUTH
Definition TER.h:311
@ tecAMM_BALANCE
Definition TER.h:340
@ tecINVARIANT_FAILED
Definition TER.h:324
@ tecFROZEN
Definition TER.h:314
@ tecAMM_ACCOUNT
Definition TER.h:345
@ tecOWNERS
Definition TER.h:309
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecINSUFFICIENT_RESERVE
Definition TER.h:318
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDUPLICATE
Definition TER.h:326
constexpr std::uint32_t kVoteWeightScaleFactor
Definition AMMCore.h:30
@ tesSUCCESS
Definition TER.h:253
constexpr std::uint32_t kAuctionSlotIntervalDuration
Definition AMMCore.h:25
T push_back(T... args)
Zero allows classes to offer efficient comparisons to zero.
Definition Zero.h:26
Represents a pair of input and output currencies.
Definition Quality.h:29
Basic tests of AMM that do not use offers.
Definition AMM_test.cpp:78
void testAMMAndCLOB(FeatureBitset features)
static FeatureBitset testableAmendments()
Definition AMM_test.cpp:84
static std::vector< FeatureBitset > amendmentCombinations(std::initializer_list< UInt256 > features)
Definition AMM_test.cpp:94
void run() override
Runs the suite.
void testTradingFee(FeatureBitset features)
void testWithdrawRounding(FeatureBitset all)
void testWithdrawIntegralNoOverflow()
void testOverflowOffer(FeatureBitset featuresInitial)
void testFixAMMOfferBlockedByLOB(FeatureBitset features)
void testSelection(FeatureBitset features)
void testInvalidDeposit(FeatureBitset features)
Definition AMM_test.cpp:474
void invariant(jtx::AMM &amm, jtx::Env &env, std::string const &msg, bool shouldFail)
void testBid(FeatureBitset features)
void testDepositEPriceIntegralOverflow()
NumberMantissaScaleGuard const sg
Definition AMM_test.cpp:80
void testFixChangeSpotPriceQuality(FeatureBitset features)
void testDepositRounding(FeatureBitset all)
void testStaleAuthAccountsAfterReinit(FeatureBitset features)
void testAMMClawback(FeatureBitset features)
void testDepositIntegralOverflow()
void testLPTokenBalance(FeatureBitset features)
void testAMMDepositWithFrozenAssets(FeatureBitset features)
void testAdjustedTokens(FeatureBitset features)
void testBasicPaymentEngine(FeatureBitset features)
void testFixReserveCheckOnWithdrawal(FeatureBitset features)
void testDepositAndWithdrawRounding(FeatureBitset features)
Set the sequence number on a JTx.
Definition seq.h:16
T to_string(T... args)