From dfcad69155c91927229124eaec7ed9362dc4f873 Mon Sep 17 00:00:00 2001 From: Gregory Tsipenyuk Date: Wed, 8 Apr 2026 12:17:37 -0400 Subject: [PATCH] feat: Add MPT support to DEX (#5285) --- cspell.config.yaml | 8 + include/xrpl/ledger/ApplyView.h | 51 +- include/xrpl/ledger/OrderBookDB.h | 14 +- include/xrpl/ledger/PaymentSandbox.h | 112 +- include/xrpl/ledger/ReadView.h | 24 +- include/xrpl/ledger/View.h | 4 +- include/xrpl/ledger/helpers/AMMHelpers.h | 33 +- include/xrpl/ledger/helpers/AMMUtils.h | 20 +- include/xrpl/ledger/helpers/EscrowHelpers.h | 12 +- include/xrpl/ledger/helpers/MPTokenHelpers.h | 76 + .../xrpl/ledger/helpers/RippleStateHelpers.h | 10 + include/xrpl/ledger/helpers/TokenHelpers.h | 16 +- include/xrpl/protocol/AMMCore.h | 18 +- include/xrpl/protocol/AmountConversions.h | 89 +- include/xrpl/protocol/Asset.h | 151 +- include/xrpl/protocol/Book.h | 83 +- include/xrpl/protocol/Concepts.h | 86 + include/xrpl/protocol/LedgerFormats.h | 3 +- include/xrpl/protocol/MPTAmount.h | 16 +- include/xrpl/protocol/MPTIssue.h | 63 +- include/xrpl/protocol/PathAsset.h | 130 + include/xrpl/protocol/STAmount.h | 43 +- include/xrpl/protocol/STObject.h | 2 + include/xrpl/protocol/STPathSet.h | 98 +- include/xrpl/protocol/TER.h | 2 + include/xrpl/protocol/detail/features.macro | 1 + .../xrpl/protocol/detail/ledger_entries.macro | 2 + include/xrpl/protocol/detail/sfields.macro | 2 + .../xrpl/protocol/detail/transactions.macro | 62 +- include/xrpl/protocol/jss.h | 2 + .../ledger_entries/DirectoryNode.h | 70 + .../protocol_autogen/transactions/AMMBid.h | 4 + .../transactions/AMMClawback.h | 8 +- .../protocol_autogen/transactions/AMMCreate.h | 6 +- .../protocol_autogen/transactions/AMMDelete.h | 6 +- .../transactions/AMMDeposit.h | 8 + .../protocol_autogen/transactions/AMMVote.h | 4 + .../transactions/AMMWithdraw.h | 10 +- .../protocol_autogen/transactions/CheckCash.h | 6 +- .../transactions/CheckCreate.h | 2 + .../transactions/OfferCreate.h | 6 +- .../protocol_autogen/transactions/Payment.h | 2 +- include/xrpl/tx/invariants/InvariantCheck.h | 3 +- .../tx/invariants/InvariantCheckPrivilege.h | 1 + include/xrpl/tx/invariants/MPTInvariant.h | 28 + include/xrpl/tx/paths/AMMLiquidity.h | 23 +- include/xrpl/tx/paths/AMMOffer.h | 13 +- include/xrpl/tx/paths/Offer.h | 142 +- include/xrpl/tx/paths/OfferStream.h | 33 +- include/xrpl/tx/paths/detail/AmountSpec.h | 198 - include/xrpl/tx/paths/detail/EitherAmount.h | 54 + include/xrpl/tx/paths/detail/FlowDebugInfo.h | 4 +- include/xrpl/tx/paths/detail/StepChecks.h | 3 +- include/xrpl/tx/paths/detail/Steps.h | 86 +- include/xrpl/tx/paths/detail/StrandFlow.h | 8 +- include/xrpl/tx/transactors/check/CheckCash.h | 3 + .../xrpl/tx/transactors/check/CheckCreate.h | 3 + include/xrpl/tx/transactors/dex/AMMClawback.h | 3 + include/xrpl/tx/transactors/dex/AMMDeposit.h | 2 +- include/xrpl/tx/transactors/dex/AMMWithdraw.h | 8 +- include/xrpl/tx/transactors/dex/OfferCreate.h | 2 +- src/libxrpl/ledger/AcceptedLedgerTx.cpp | 3 +- src/libxrpl/ledger/PaymentSandbox.cpp | 260 +- src/libxrpl/ledger/View.cpp | 28 +- src/libxrpl/ledger/helpers/AMMHelpers.cpp | 26 +- src/libxrpl/ledger/helpers/AMMUtils.cpp | 270 +- .../ledger/helpers/AccountRootHelpers.cpp | 2 +- src/libxrpl/ledger/helpers/MPTokenHelpers.cpp | 177 +- src/libxrpl/ledger/helpers/NFTokenHelpers.cpp | 8 +- .../ledger/helpers/RippleStateHelpers.cpp | 44 +- src/libxrpl/ledger/helpers/TokenHelpers.cpp | 249 +- src/libxrpl/protocol/AMMCore.cpp | 60 +- src/libxrpl/protocol/Asset.cpp | 7 + src/libxrpl/protocol/Indexes.cpp | 77 +- src/libxrpl/protocol/MPTIssue.cpp | 15 +- src/libxrpl/protocol/PathAsset.cpp | 19 + src/libxrpl/protocol/STAmount.cpp | 238 +- src/libxrpl/protocol/STIssue.cpp | 33 +- src/libxrpl/protocol/STObject.cpp | 6 + src/libxrpl/protocol/STParsedJSON.cpp | 76 +- src/libxrpl/protocol/STPathSet.cpp | 55 +- src/libxrpl/protocol/TER.cpp | 1 + src/libxrpl/tx/Transactor.cpp | 40 +- src/libxrpl/tx/invariants/AMMInvariant.cpp | 14 +- src/libxrpl/tx/invariants/FreezeInvariant.cpp | 2 +- src/libxrpl/tx/invariants/InvariantCheck.cpp | 54 +- src/libxrpl/tx/invariants/MPTInvariant.cpp | 193 +- src/libxrpl/tx/paths/AMMLiquidity.cpp | 40 +- src/libxrpl/tx/paths/AMMOffer.cpp | 37 +- src/libxrpl/tx/paths/BookStep.cpp | 310 +- src/libxrpl/tx/paths/DirectStep.cpp | 10 +- src/libxrpl/tx/paths/Flow.cpp | 139 +- src/libxrpl/tx/paths/MPTEndpointStep.cpp | 919 +++ src/libxrpl/tx/paths/OfferStream.cpp | 167 +- src/libxrpl/tx/paths/PaySteps.cpp | 338 +- src/libxrpl/tx/paths/RippleCalc.cpp | 2 +- src/libxrpl/tx/paths/XRPEndpointStep.cpp | 24 +- .../tx/transactors/bridge/XChainBridge.cpp | 26 +- .../tx/transactors/check/CheckCash.cpp | 352 +- .../tx/transactors/check/CheckCreate.cpp | 90 +- src/libxrpl/tx/transactors/dex/AMMBid.cpp | 24 +- .../tx/transactors/dex/AMMClawback.cpp | 97 +- src/libxrpl/tx/transactors/dex/AMMCreate.cpp | 188 +- src/libxrpl/tx/transactors/dex/AMMDelete.cpp | 9 +- src/libxrpl/tx/transactors/dex/AMMDeposit.cpp | 109 +- src/libxrpl/tx/transactors/dex/AMMVote.cpp | 9 +- .../tx/transactors/dex/AMMWithdraw.cpp | 179 +- .../tx/transactors/dex/OfferCreate.cpp | 229 +- src/libxrpl/tx/transactors/escrow/Escrow.cpp | 0 .../tx/transactors/escrow/EscrowCancel.cpp | 4 +- .../tx/transactors/escrow/EscrowCreate.cpp | 17 +- .../tx/transactors/escrow/EscrowFinish.cpp | 8 +- .../lending/LoanBrokerCoverClawback.cpp | 2 +- .../tx/transactors/nft/NFTokenAcceptOffer.cpp | 6 +- .../tx/transactors/payment/Payment.cpp | 64 +- src/libxrpl/tx/transactors/token/Clawback.cpp | 9 +- src/libxrpl/tx/transactors/token/TrustSet.cpp | 15 +- .../tx/transactors/vault/VaultClawback.cpp | 65 +- .../tx/transactors/vault/VaultWithdraw.cpp | 2 +- src/test/app/AMMCalc_test.cpp | 21 +- src/test/app/AMMClawbackMPT_test.cpp | 1821 +++++ src/test/app/AMMClawback_test.cpp | 69 +- src/test/app/AMMExtendedMPT_test.cpp | 3619 +++++++++ src/test/app/AMMExtended_test.cpp | 11 +- src/test/app/AMMMPT_test.cpp | 7043 +++++++++++++++++ src/test/app/AMM_test.cpp | 86 +- src/test/app/CheckMPT_test.cpp | 2156 +++++ src/test/app/Check_test.cpp | 116 +- src/test/app/CrossingLimitsMPT_test.cpp | 431 + src/test/app/CrossingLimits_test.cpp | 100 +- src/test/app/Delegate_test.cpp | 10 +- src/test/app/FlowMPT_test.cpp | 2111 +++++ src/test/app/Flow_test.cpp | 26 +- src/test/app/Invariants_test.cpp | 155 +- src/test/app/LPTokenTransfer_test.cpp | 2 +- src/test/app/LedgerLoad_test.cpp | 4 +- src/test/app/LendingHelpers_test.cpp | 2 +- src/test/app/LoanBroker_test.cpp | 18 +- src/test/app/Loan_test.cpp | 61 +- src/test/app/MPToken_test.cpp | 3520 +++++++- src/test/app/NFTokenAuth_test.cpp | 16 +- src/test/app/NFToken_test.cpp | 7 +- src/test/app/OfferMPT_test.cpp | 4731 +++++++++++ src/test/app/Offer_test.cpp | 49 +- src/test/app/PathMPT_test.cpp | 443 ++ src/test/app/Path_test.cpp | 16 +- src/test/app/PayStrandMPT_test.cpp | 627 ++ src/test/app/PayStrand_test.cpp | 116 +- src/test/app/PermissionedDEX_test.cpp | 4 +- src/test/app/ReducedOffer_test.cpp | 24 +- src/test/app/TheoreticalQuality_test.cpp | 6 +- src/test/app/TrustAndBalance_test.cpp | 3 +- src/test/app/Vault_test.cpp | 61 +- src/test/app/XChain_test.cpp | 22 +- src/test/jtx/AMM.h | 176 +- src/test/jtx/AMMTest.h | 43 +- src/test/jtx/Env.h | 7 - src/test/jtx/PathSet.h | 25 +- src/test/jtx/TestHelpers.h | 275 +- src/test/jtx/amount.h | 47 +- src/test/jtx/flags.h | 4 +- src/test/jtx/impl/AMM.cpp | 438 +- src/test/jtx/impl/AMMTest.cpp | 170 +- src/test/jtx/impl/Env.cpp | 87 +- src/test/jtx/impl/TestHelpers.cpp | 388 +- src/test/jtx/impl/amount.cpp | 92 +- src/test/jtx/impl/balance.cpp | 4 +- src/test/jtx/impl/mpt.cpp | 2 + src/test/jtx/impl/paths.cpp | 25 +- src/test/jtx/impl/xchain_bridge.cpp | 11 +- src/test/jtx/mpt.h | 8 + src/test/jtx/owners.h | 5 +- src/test/jtx/paths.h | 7 +- src/test/ledger/BookDirs_test.cpp | 13 +- src/test/ledger/Directory_test.cpp | 6 +- src/test/ledger/PaymentSandbox_test.cpp | 40 +- src/test/protocol/Memo_test.cpp | 2 +- src/test/protocol/STAmount_test.cpp | 10 +- src/test/protocol/STNumber_test.cpp | 2 +- src/test/rpc/AMMInfo_test.cpp | 41 +- src/test/rpc/Book_test.cpp | 4 +- src/test/rpc/DeliveredAmount_test.cpp | 2 +- src/test/rpc/Feature_test.cpp | 2 +- src/test/rpc/GatewayBalances_test.cpp | 2 +- src/test/rpc/LedgerEntry_test.cpp | 118 +- src/test/rpc/Subscribe_test.cpp | 4 +- .../ledger_entries/DirectoryNodeTests.cpp | 54 + src/xrpld/app/ledger/OrderBookDB.h | 0 src/xrpld/app/ledger/OrderBookDBImpl.cpp | 66 +- src/xrpld/app/ledger/OrderBookDBImpl.h | 16 +- src/xrpld/app/misc/NetworkOPs.cpp | 27 +- src/xrpld/rpc/BookChanges.h | 31 +- src/xrpld/rpc/MPTokenIssuanceID.h | 2 +- src/xrpld/rpc/detail/AccountAssets.cpp | 86 + src/xrpld/rpc/detail/AccountAssets.h | 21 + src/xrpld/rpc/detail/AccountCurrencies.cpp | 66 - src/xrpld/rpc/detail/AccountCurrencies.h | 21 - src/xrpld/rpc/detail/AssetCache.cpp | 147 + src/xrpld/rpc/detail/AssetCache.h | 106 + src/xrpld/rpc/detail/MPT.h | 45 + src/xrpld/rpc/detail/MPTokenIssuanceID.cpp | 4 +- src/xrpld/rpc/detail/PathRequest.cpp | 211 +- src/xrpld/rpc/detail/PathRequest.h | 23 +- src/xrpld/rpc/detail/PathRequestManager.cpp | 34 +- src/xrpld/rpc/detail/PathRequestManager.h | 9 +- src/xrpld/rpc/detail/Pathfinder.cpp | 405 +- src/xrpld/rpc/detail/Pathfinder.h | 19 +- src/xrpld/rpc/detail/PathfinderUtils.h | 11 +- src/xrpld/rpc/detail/RPCHelpers.cpp | 60 + src/xrpld/rpc/detail/RPCHelpers.h | 9 + src/xrpld/rpc/detail/RippleLineCache.cpp | 101 - src/xrpld/rpc/detail/RippleLineCache.h | 101 - src/xrpld/rpc/detail/TransactionSign.cpp | 19 +- .../handlers/account/AccountCurrencies.cpp | 4 +- .../rpc/handlers/account/AccountLines.cpp | 2 +- .../rpc/handlers/account/GatewayBalances.cpp | 10 +- .../rpc/handlers/account/NoRippleCheck.cpp | 4 +- src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp | 4 +- .../rpc/handlers/ledger/LedgerEntryHelpers.h | 10 +- src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp | 56 +- .../rpc/handlers/orderbook/BookOffers.cpp | 253 +- .../rpc/handlers/subscribe/Subscribe.cpp | 46 +- .../rpc/handlers/subscribe/Unsubscribe.cpp | 46 +- 223 files changed, 34897 insertions(+), 4228 deletions(-) create mode 100644 include/xrpl/protocol/Concepts.h create mode 100644 include/xrpl/protocol/PathAsset.h create mode 100644 include/xrpl/tx/paths/detail/EitherAmount.h create mode 100644 src/libxrpl/protocol/PathAsset.cpp create mode 100644 src/libxrpl/tx/paths/MPTEndpointStep.cpp create mode 100644 src/libxrpl/tx/transactors/escrow/Escrow.cpp create mode 100644 src/test/app/AMMClawbackMPT_test.cpp create mode 100644 src/test/app/AMMExtendedMPT_test.cpp create mode 100644 src/test/app/AMMMPT_test.cpp create mode 100644 src/test/app/CheckMPT_test.cpp create mode 100644 src/test/app/CrossingLimitsMPT_test.cpp create mode 100644 src/test/app/FlowMPT_test.cpp create mode 100644 src/test/app/OfferMPT_test.cpp create mode 100644 src/test/app/PathMPT_test.cpp create mode 100644 src/test/app/PayStrandMPT_test.cpp create mode 100644 src/xrpld/app/ledger/OrderBookDB.h create mode 100644 src/xrpld/rpc/detail/AccountAssets.cpp create mode 100644 src/xrpld/rpc/detail/AccountAssets.h delete mode 100644 src/xrpld/rpc/detail/AccountCurrencies.cpp delete mode 100644 src/xrpld/rpc/detail/AccountCurrencies.h create mode 100644 src/xrpld/rpc/detail/AssetCache.cpp create mode 100644 src/xrpld/rpc/detail/AssetCache.h create mode 100644 src/xrpld/rpc/detail/MPT.h diff --git a/cspell.config.yaml b/cspell.config.yaml index 63edba587d..028f02191e 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -44,6 +44,10 @@ suggestWords: words: - abempty - AMMID + - AMMMPT + - AMMMPToken + - AMMMPTokens + - AMMXRP - amt - amts - asnode @@ -96,6 +100,7 @@ words: - distro - doxyfile - dxrpl + - enabled - endmacro - exceptioned - Falco @@ -148,6 +153,8 @@ words: - ltype - mcmodel - MEMORYSTATUSEX + - MPTAMM + - MPTDEX - Merkle - Metafuncton - misprediction @@ -157,6 +164,7 @@ words: - mptid - mptissuance - mptissuanceid + - mptissue - mptoken - mptokenid - mptokenissuance diff --git a/include/xrpl/ledger/ApplyView.h b/include/xrpl/ledger/ApplyView.h index d5be5c9a1e..73161453db 100644 --- a/include/xrpl/ledger/ApplyView.h +++ b/include/xrpl/ledger/ApplyView.h @@ -213,11 +213,60 @@ public: // Called when a credit is made to an account // This is required to support PaymentSandbox virtual void - creditHook( + creditHookIOU( AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) + { + XRPL_ASSERT(amount.holds(), "creditHookIOU: amount is for Issue"); + } + + virtual void + creditHookMPT( + AccountID const& from, + AccountID const& to, + STAmount const& amount, + std::uint64_t preCreditBalanceHolder, + std::int64_t preCreditBalanceIssuer) + { + XRPL_ASSERT(amount.holds(), "creditHookMPT: amount is for MPTIssue"); + } + + /** Facilitate tracking of MPT sold by an issuer owning MPT sell offer. + * Unlike IOU, MPT doesn't have bi-directional relationship with an issuer, + * where a trustline limits an amount that can be issued to a holder. + * Consequently, the credit step (last MPTEndpointStep or + * BookStep buying MPT) might temporarily overflow OutstandingAmount. + * Limiting of a step's output amount in this case is delegated to + * the next step (in rev order). The next step always redeems when a holder + * account sells MPT (first MPTEndpointStep or BookStep selling MPT). + * In this case the holder account is only limited by the step's output + * and it's available funds since it's transferring the funds from one + * account to another account and doesn't change OutstandingAmount. + * This doesn't apply to an offer owned by an issuer. + * In this case the issuer sells or self debits and is increasing + * OutstandingAmount. Ability to issue is limited by the issuer + * originally available funds less already self sold MPT amounts (MPT sell + * offer). + * Consider an example: + * - GW creates MPT(USD) with 1,000USD MaximumAmount. + * - GW pays 950USD to A1. + * - A1 creates an offer 100XRP(buy)/100USD(sell). + * - GW creates an offer 100XRP(buy)/100USD(sell). + * - A2 pays 200USD to A3 with sendMax of 200XRP. + * Since the payment engine executes payments in reverse, + * OutstandingAmount overflows in MPTEndpointStep: 950 + 200 = 1,150USD. + * BookStep first consumes A1 offer. This reduces OutstandingAmount + * by 100USD: 1,150 - 100 = 1,050USD. GW offer can only be partially + * consumed because the initial available amount is 50USD = 1,000 - 950. + * BookStep limits it's output to 150USD. This in turn limits A3's send + * amount to 150XRP: A1 buys 100XRP and sells 100USD to A3. This doesn't + * change OutstandingAmount. GW buys 50XRP and sells 50USD to A3. This + * changes OutstandingAmount to 1,000USD. + */ + virtual void + issuerSelfDebitHookMPT(MPTIssue const& issue, std::uint64_t amount, std::int64_t origBalance) { } diff --git a/include/xrpl/ledger/OrderBookDB.h b/include/xrpl/ledger/OrderBookDB.h index 5bf66eb4ab..a0aee58e2a 100644 --- a/include/xrpl/ledger/OrderBookDB.h +++ b/include/xrpl/ledger/OrderBookDB.h @@ -3,8 +3,8 @@ #include #include #include +#include #include -#include #include #include @@ -53,30 +53,30 @@ public: issue. This is useful for pathfinding to find all possible next hops from a given currency. - @param issue The issue to search for + @param asset The asset to search for @param domain Optional domain restriction for the order book @return Vector of books that want this issue */ virtual std::vector - getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + getBooksByTakerPays(Asset const& asset, std::optional const& domain = std::nullopt) = 0; /** Get the count of order books that want a specific issue. - @param issue The issue to search for + @param asset The asset to search for @param domain Optional domain restriction for the order book @return Number of books that want this issue */ virtual int - getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + getBookSize(Asset const& asset, std::optional const& domain = std::nullopt) = 0; /** Check if an order book to XRP exists for the given issue. - @param issue The issue to check + @param asset The asset to check @param domain Optional domain restriction for the order book @return true if a book from this issue to XRP exists */ virtual bool - isBookToXRP(Issue const& issue, std::optional const& domain = std::nullopt) = 0; + isBookToXRP(Asset const& asset, std::optional const& domain = std::nullopt) = 0; /** * Process a transaction for order book tracking. diff --git a/include/xrpl/ledger/PaymentSandbox.h b/include/xrpl/ledger/PaymentSandbox.h index 891e3ef27b..d6f7820e8a 100644 --- a/include/xrpl/ledger/PaymentSandbox.h +++ b/include/xrpl/ledger/PaymentSandbox.h @@ -15,10 +15,55 @@ namespace detail { // into the PaymentSandbox class itself class DeferredCredits { -public: - struct Adjustment +private: + using KeyIOU = std::tuple; + struct ValueIOU { - Adjustment(STAmount const& d, STAmount const& c, STAmount const& b) + explicit ValueIOU() = default; + + STAmount lowAcctCredits; + STAmount highAcctCredits; + STAmount lowAcctOrigBalance; + }; + + struct HolderValueMPT + { + HolderValueMPT() = default; + // Debit to issuer + std::uint64_t debit = 0; + std::uint64_t origBalance = 0; + }; + + struct IssuerValueMPT + { + IssuerValueMPT() = default; + std::map holders; + // Credit to holder + std::uint64_t credit = 0; + // OutstandingAmount might overflow when MPTs are credited to a holder. + // Consider A1 paying 100MPT to A2 and A1 already having maximum MPTs. + // Since the payment engine executes a payment in revers, A2 is + // credited first and OutstandingAmount is going to be equal + // to MaximumAmount + 100MPT. In the next step A1 redeems 100MPT + // to the issuer and OutstandingAmount balances out. + std::int64_t origBalance = 0; + // Self debit on offer selling MPT. Since the payment engine executes + // a payment in reverse, a crediting/buying step may overflow + // OutstandingAmount. A sell MPT offer owned by a holder can redeem any + // amount up to the offer's amount and holder's available funds, + // balancing out OutstandingAmount. But if the offer's owner is issuer + // then it issues more MPT. In this case the available amount to issue + // is the initial issuer's available amount less all offer sell amounts + // by the issuer. This is self-debit, where the offer's owner, + // issuer in this case, debits to self. + std::uint64_t selfDebit = 0; + }; + using AdjustmentMPT = IssuerValueMPT; + +public: + struct AdjustmentIOU + { + AdjustmentIOU(STAmount const& d, STAmount const& c, STAmount const& b) : debits(d), credits(c), origBalance(b) { } @@ -29,16 +74,30 @@ public: // Get the adjustments for the balance between main and other. // Returns the debits, credits and the original balance - std::optional - adjustments(AccountID const& main, AccountID const& other, Currency const& currency) const; + std::optional + adjustmentsIOU(AccountID const& main, AccountID const& other, Currency const& currency) const; + + std::optional + adjustmentsMPT(MPTID const& mptID) const; void - credit( + creditIOU( AccountID const& sender, AccountID const& receiver, STAmount const& amount, STAmount const& preCreditSenderBalance); + void + creditMPT( + AccountID const& sender, + AccountID const& receiver, + STAmount const& amount, + std::uint64_t preCreditBalanceHolder, + std::int64_t preCreditBalanceIssuer); + + void + issuerSelfDebitMPT(MPTIssue const& issue, std::uint64_t amount, std::int64_t origBalance); + void ownerCount(AccountID const& id, std::uint32_t cur, std::uint32_t next); @@ -52,21 +111,11 @@ public: apply(DeferredCredits& to); private: - // lowAccount, highAccount - using Key = std::tuple; - struct Value - { - explicit Value() = default; + static KeyIOU + makeKeyIOU(AccountID const& a1, AccountID const& a2, Currency const& currency); - STAmount lowAcctCredits; - STAmount highAcctCredits; - STAmount lowAcctOrigBalance; - }; - - static Key - makeKey(AccountID const& a1, AccountID const& a2, Currency const& c); - - std::map credits_; + std::map creditsIOU_; + std::map creditsMPT_; std::map ownerCounts_; }; @@ -131,16 +180,35 @@ public: /** @} */ STAmount - balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) + balanceHookIOU(AccountID const& account, AccountID const& issuer, STAmount const& amount) const override; + STAmount + balanceHookMPT(AccountID const& account, MPTIssue const& issue, std::int64_t amount) + const override; + + STAmount + balanceHookSelfIssueMPT(MPTIssue const& issue, std::int64_t amount) const override; + void - creditHook( + creditHookIOU( AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) override; + void + creditHookMPT( + AccountID const& from, + AccountID const& to, + STAmount const& amount, + std::uint64_t preCreditBalanceHolder, + std::int64_t preCreditBalanceIssuer) override; + + void + issuerSelfDebitHookMPT(MPTIssue const& issue, std::uint64_t amount, std::int64_t origBalance) + override; + void adjustOwnerCountHook(AccountID const& account, std::uint32_t cur, std::uint32_t next) override; diff --git a/include/xrpl/ledger/ReadView.h b/include/xrpl/ledger/ReadView.h index e3a5163418..debf01e85f 100644 --- a/include/xrpl/ledger/ReadView.h +++ b/include/xrpl/ledger/ReadView.h @@ -148,15 +148,35 @@ public: // Accounts in a payment are not allowed to use assets acquired during that // payment. The PaymentSandbox tracks the debits, credits, and owner count - // changes that accounts make during a payment. `balanceHook` adjusts + // changes that accounts make during a payment. `balanceHookIOU` adjusts // balances so newly acquired assets are not counted toward the balance. // This is required to support PaymentSandbox. virtual STAmount - balanceHook(AccountID const& account, AccountID const& issuer, STAmount const& amount) const + balanceHookIOU(AccountID const& account, AccountID const& issuer, STAmount const& amount) const { + XRPL_ASSERT(amount.holds(), "balanceHookIOU: amount is for Issue"); + return amount; } + // balanceHookMPT adjusts balances so newly acquired assets are not counted + // toward the balance. + virtual STAmount + balanceHookMPT(AccountID const& account, MPTIssue const& issue, std::int64_t amount) const + { + return STAmount{issue, amount}; + } + + // An offer owned by an issuer and selling MPT is limited by the issuer's + // funds available to issue, which are originally available funds less + // already self sold MPT amounts (MPT sell offer). This hook is used + // by issuerFundsToSelfIssue() function. + virtual STAmount + balanceHookSelfIssueMPT(MPTIssue const& issue, std::int64_t amount) const + { + return STAmount{issue, amount}; + } + // Accounts in a payment are not allowed to use assets acquired during that // payment. The PaymentSandbox tracks the debits, credits, and owner count // changes that accounts make during a payment. `ownerCountHook` adjusts the diff --git a/include/xrpl/ledger/View.h b/include/xrpl/ledger/View.h index 615f644987..4958a89d8c 100644 --- a/include/xrpl/ledger/View.h +++ b/include/xrpl/ledger/View.h @@ -63,8 +63,8 @@ isVaultPseudoAccountFrozen( isLPTokenFrozen( ReadView const& view, AccountID const& account, - Issue const& asset, - Issue const& asset2); + Asset const& asset, + Asset const& asset2); // Return the list of enabled amendments [[nodiscard]] std::set diff --git a/include/xrpl/ledger/helpers/AMMHelpers.h b/include/xrpl/ledger/helpers/AMMHelpers.h index 55f27a3f06..173b4924ae 100644 --- a/include/xrpl/ledger/helpers/AMMHelpers.h +++ b/include/xrpl/ledger/helpers/AMMHelpers.h @@ -36,7 +36,7 @@ enum class IsDeposit : bool { No = false, Yes = true }; * @return LP Tokens as IOU */ STAmount -ammLPTokens(STAmount const& asset1, STAmount const& asset2, Issue const& lptIssue); +ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue); /** Calculate LP Tokens given asset's deposit amount. * @param asset1Balance current AMM asset1 balance @@ -124,7 +124,8 @@ withinRelativeDistance(Quality const& calcQuality, Quality const& reqQuality, Nu template requires( std::is_same_v || std::is_same_v || - std::is_same_v || std::is_same_v) + std::is_same_v || std::is_same_v || + std::is_same_v) bool withinRelativeDistance(Amt const& calc, Amt const& req, Number const& dist) { @@ -195,7 +196,7 @@ getAMMOfferStartWithTakerGets( // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerGets is XRP. auto const takerGets = - toAmount(getIssue(pool.out), nTakerGetsProposed, Number::downward); + toAmount(getAsset(pool.out), nTakerGetsProposed, Number::downward); return TAmounts{swapAssetOut(pool, takerGets, tfee), takerGets}; }; @@ -262,7 +263,7 @@ getAMMOfferStartWithTakerPays( // Round downward to minimize the offer and to maximize the quality. // This has the most impact when takerPays is XRP. auto const takerPays = - toAmount(getIssue(pool.in), nTakerPaysProposed, Number::downward); + toAmount(getAsset(pool.in), nTakerPaysProposed, Number::downward); return TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; }; @@ -331,7 +332,7 @@ changeSpotPriceQuality( << " " << to_string(pool.out) << " " << quality << " " << tfee; return std::nullopt; } - auto const takerPays = toAmount(getIssue(pool.in), nTakerPays, Number::upward); + auto const takerPays = toAmount(getAsset(pool.in), nTakerPays, Number::upward); // should not fail if (auto amounts = TAmounts{takerPays, swapAssetIn(pool, takerPays, tfee)}; Quality{amounts} < quality && @@ -360,7 +361,7 @@ changeSpotPriceQuality( // Generate the offer starting with XRP side. Return seated offer amounts // if the offer can be generated, otherwise nullopt. auto amounts = [&]() { - if (isXRP(getIssue(pool.out))) + if (isXRP(getAsset(pool.out))) return getAMMOfferStartWithTakerGets(pool, quality, tfee); return getAMMOfferStartWithTakerPays(pool, quality, tfee); }(); @@ -445,7 +446,7 @@ swapAssetIn(TAmounts const& pool, TIn const& assetIn, std::uint16_t t auto const denom = pool.in + assetIn * (1 - fee); if (denom.signum() <= 0) - return toAmount(getIssue(pool.out), 0); + return toAmount(getAsset(pool.out), 0); Number::setround(Number::upward); auto const ratio = numerator / denom; @@ -454,14 +455,14 @@ swapAssetIn(TAmounts const& pool, TIn const& assetIn, std::uint16_t t auto const swapOut = pool.out - ratio; if (swapOut.signum() < 0) - return toAmount(getIssue(pool.out), 0); + return toAmount(getAsset(pool.out), 0); - return toAmount(getIssue(pool.out), swapOut, Number::downward); + return toAmount(getAsset(pool.out), swapOut, Number::downward); } else { return toAmount( - getIssue(pool.out), + getAsset(pool.out), pool.out - (pool.in * pool.out) / (pool.in + assetIn * feeMult(tfee)), Number::downward); } @@ -508,7 +509,7 @@ swapAssetOut(TAmounts const& pool, TOut const& assetOut, std::uint16_ auto const denom = pool.out - assetOut; if (denom.signum() <= 0) { - return toMaxAmount(getIssue(pool.in)); + return toMaxAmount(getAsset(pool.in)); } Number::setround(Number::upward); @@ -522,14 +523,14 @@ swapAssetOut(TAmounts const& pool, TOut const& assetOut, std::uint16_ Number::setround(Number::upward); auto const swapIn = numerator2 / feeMult; if (swapIn.signum() < 0) - return toAmount(getIssue(pool.in), 0); + return toAmount(getAsset(pool.in), 0); - return toAmount(getIssue(pool.in), swapIn, Number::upward); + return toAmount(getAsset(pool.in), swapIn, Number::upward); } else { return toAmount( - getIssue(pool.in), + getAsset(pool.in), ((pool.in * pool.out) / (pool.out - assetOut) - pool.in) / feeMult(tfee), Number::upward); } @@ -616,9 +617,9 @@ getRoundedAsset(Rules const& rules, STAmount const& balance, A const& frac, IsDe if (!rules.enabled(fixAMMv1_3)) { if constexpr (std::is_same_v) - return multiply(balance, frac, balance.issue()); + return multiply(balance, frac, balance.asset()); else - return toSTAmount(balance.issue(), balance * frac); + return toSTAmount(balance.asset(), balance * frac); } auto const rm = detail::getAssetRounding(isDeposit); return multiply(balance, frac, rm); diff --git a/include/xrpl/ledger/helpers/AMMUtils.h b/include/xrpl/ledger/helpers/AMMUtils.h index 77ad18106e..a9e9c9344a 100644 --- a/include/xrpl/ledger/helpers/AMMUtils.h +++ b/include/xrpl/ledger/helpers/AMMUtils.h @@ -21,9 +21,10 @@ std::pair ammPoolHolds( ReadView const& view, AccountID const& ammAccountID, - Issue const& issue1, - Issue const& issue2, + Asset const& asset1, + Asset const& asset2, FreezeHandling freezeHandling, + AuthHandling authHandling, beast::Journal const j); /** Get AMM pool and LP token balances. If both optIssue are @@ -34,9 +35,10 @@ Expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, - std::optional const& optIssue1, - std::optional const& optIssue2, + std::optional const& optAsset1, + std::optional const& optAsset2, FreezeHandling freezeHandling, + AuthHandling authHandling, beast::Journal const j); /** Get the balance of LP tokens. @@ -44,8 +46,8 @@ ammHolds( STAmount ammLPHolds( ReadView const& view, - Currency const& cur1, - Currency const& cur2, + Asset const& asset1, + Asset const& asset2, AccountID const& ammAccount, AccountID const& lpAccount, beast::Journal const j); @@ -67,13 +69,13 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) /** Returns total amount held by AMM for the given token. */ STAmount -ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Issue const& issue); +ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Asset const& asset); /** Delete trustlines to AMM. If all trustlines are deleted then * AMM object and account are deleted. Otherwise tecIMPCOMPLETE is returned. */ TER -deleteAMMAccount(Sandbox& view, Issue const& asset, Issue const& asset2, beast::Journal j); +deleteAMMAccount(Sandbox& view, Asset const& asset, Asset const& asset2, beast::Journal j); /** Initialize Auction and Voting slots and set the trading/discounted fee. */ @@ -82,7 +84,7 @@ initializeFeeAuctionVote( ApplyView& view, std::shared_ptr& ammSle, AccountID const& account, - Issue const& lptIssue, + Asset const& lptAsset, std::uint16_t tfee); /** Return true if the Liquidity Provider is the only AMM provider, false diff --git a/include/xrpl/ledger/helpers/EscrowHelpers.h b/include/xrpl/ledger/helpers/EscrowHelpers.h index 1680dbcad4..b44601594d 100644 --- a/include/xrpl/ledger/helpers/EscrowHelpers.h +++ b/include/xrpl/ledger/helpers/EscrowHelpers.h @@ -41,7 +41,8 @@ escrowUnlockApplyHelper( bool createAsset, beast::Journal journal) { - Keylet const trustLineKey = keylet::line(receiver, amount.issue()); + Issue const& issue = amount.get(); + Keylet const trustLineKey = keylet::line(receiver, issue); bool const recvLow = issuer > receiver; bool const senderIssuer = issuer == sender; bool const receiverIssuer = issuer == receiver; @@ -64,9 +65,9 @@ escrowUnlockApplyHelper( return tecNO_LINE_INSUF_RESERVE; } - Currency const currency = amount.getCurrency(); - STAmount initialBalance(amount.issue()); - initialBalance.setIssuer(noAccount()); + Currency const currency = issue.currency; + STAmount initialBalance(issue); + initialBalance.get().account = noAccount(); if (TER const ter = trustCreate( view, // payment sandbox @@ -113,7 +114,8 @@ escrowUnlockApplyHelper( if ((!senderIssuer && !receiverIssuer) && lockedRate != parityRate) { // compute transfer fee, if any - auto const xferFee = amount.value() - divideRound(amount, lockedRate, amount.issue(), true); + auto const xferFee = + amount.value() - divideRound(amount, lockedRate, amount.get(), true); // compute balance to transfer finalAmt = amount.value() - xferFee; } diff --git a/include/xrpl/ledger/helpers/MPTokenHelpers.h b/include/xrpl/ledger/helpers/MPTokenHelpers.h index 466486306c..6544b18dd1 100644 --- a/include/xrpl/ledger/helpers/MPTokenHelpers.h +++ b/include/xrpl/ledger/helpers/MPTokenHelpers.h @@ -80,6 +80,7 @@ authorizeMPToken( * requireAuth check is recursive for MPT shares in a vault, descending to * assets in the vault, up to maxAssetCheckDepth recursion depth. This is * purely defensive, as we currently do not allow such vaults to be created. + * WeakAuth intentionally allows missing MPTokens under MPToken V2. */ [[nodiscard]] TER requireAuth( @@ -114,6 +115,12 @@ canTransfer( AccountID const& from, AccountID const& to); +/** Check if Asset can be traded on DEX. return tecNO_PERMISSION + * if it doesn't and tesSUCCESS otherwise. + */ +[[nodiscard]] TER +canTrade(ReadView const& view, Asset const& asset); + //------------------------------------------------------------------------------ // // Empty holding operations (MPT-specific) @@ -164,4 +171,73 @@ createMPToken( AccountID const& account, std::uint32_t const flags); +TER +checkCreateMPT( + xrpl::ApplyView& view, + xrpl::MPTIssue const& mptIssue, + xrpl::AccountID const& holder, + beast::Journal j); + +//------------------------------------------------------------------------------ +// +// MPT Overflow related +// +//------------------------------------------------------------------------------ + +// MaximumAmount doesn't exceed 2**63-1 +std::int64_t +maxMPTAmount(SLE const& sleIssuance); + +// OutstandingAmount may overflow and available amount might be negative. +// But available amount is always <= |MaximumAmount - OutstandingAmount|. +std::int64_t +availableMPTAmount(SLE const& sleIssuance); + +std::int64_t +availableMPTAmount(ReadView const& view, MPTID const& mptID); + +/** Checks for two types of OutstandingAmount overflow during a send operation. + * 1. **Direct directSendNoFee (Overflow: No):** A true overflow check when + * `OutstandingAmount > MaximumAmount`. This threshold is used for direct + * directSendNoFee transactions that bypass the payment engine. + * 2. **accountSend & Payment Engine (Overflow: Yes):** A temporary overflow + * check when `OutstandingAmount > UINT64_MAX`. This higher threshold is used + * for `accountSend` and payments processed via the payment engine. + */ +bool +isMPTOverflow( + std::int64_t sendAmount, + std::uint64_t outstandingAmount, + std::int64_t maximumAmount, + AllowMPTOverflow allowOverflow); + +/** + * Determine funds available for an issuer to sell in an issuer owned offer. + * Issuing step, which could be either MPTEndPointStep last step or BookStep's + * TakerPays may overflow OutstandingAmount. Redeeming step, in BookStep's + * TakerGets redeems the offer's owner funds, essentially balancing out + * the overflow, unless the offer's owner is the issuer. + */ +[[nodiscard]] STAmount +issuerFundsToSelfIssue(ReadView const& view, MPTIssue const& issue); + +/** Facilitate tracking of MPT sold by an issuer owning MPT sell offer. + * See ApplyView::issuerSelfDebitHookMPT(). + */ +void +issuerSelfDebitHookMPT(ApplyView& view, MPTIssue const& issue, std::uint64_t amount); + +//------------------------------------------------------------------------------ +// +// MPT DEX +// +//------------------------------------------------------------------------------ + +/* Return true if a transaction is allowed for the specified MPT/account. The + * function checks MPTokenIssuance and MPToken objects flags to determine if the + * transaction is allowed. + */ +TER +checkMPTTxAllowed(ReadView const& v, TxType tx, Asset const& asset, AccountID const& accountID); + } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/RippleStateHelpers.h b/include/xrpl/ledger/helpers/RippleStateHelpers.h index 3feba59d1f..17b0f7673e 100644 --- a/include/xrpl/ledger/helpers/RippleStateHelpers.h +++ b/include/xrpl/ledger/helpers/RippleStateHelpers.h @@ -252,4 +252,14 @@ deleteAMMTrustLine( std::optional const& ammAccountID, beast::Journal j); +/** Delete AMMs MPToken. The passed `sle` must be obtained from a prior + * call to view.peek(). + */ +[[nodiscard]] TER +deleteAMMMPToken( + ApplyView& view, + std::shared_ptr sleMPT, + AccountID const& ammAccountID, + beast::Journal j); + } // namespace xrpl diff --git a/include/xrpl/ledger/helpers/TokenHelpers.h b/include/xrpl/ledger/helpers/TokenHelpers.h index 908950a1e1..c05308295a 100644 --- a/include/xrpl/ledger/helpers/TokenHelpers.h +++ b/include/xrpl/ledger/helpers/TokenHelpers.h @@ -31,6 +31,9 @@ enum SpendableHandling { shSIMPLE_BALANCE, shFULL_BALANCE }; enum class WaiveTransferFee : bool { No = false, Yes }; +/** Controls whether accountSend is allowed to overflow OutstandingAmount **/ +enum class AllowMPTOverflow : bool { No = false, Yes }; + /* Check if MPToken (for MPT) or trust line (for IOU) exists: * - StrongAuth - before checking if authorization is required * - WeakAuth @@ -176,6 +179,16 @@ accountFunds( FreezeHandling freezeHandling, beast::Journal j); +// Overload with AuthHandling to support IOU and MPT. +[[nodiscard]] STAmount +accountFunds( + ReadView const& view, + AccountID const& id, + STAmount const& saDefault, + FreezeHandling freezeHandling, + AuthHandling authHandling, + beast::Journal j); + /** Returns the transfer fee as Rate based on the type of token * @param view The ledger view * @param amount The amount to transfer @@ -257,7 +270,8 @@ accountSend( AccountID const& to, STAmount const& saAmount, beast::Journal j, - WaiveTransferFee waiveFee = WaiveTransferFee::No); + WaiveTransferFee waiveFee = WaiveTransferFee::No, + AllowMPTOverflow allowOverflow = AllowMPTOverflow::No); using MultiplePaymentDestinations = std::vector>; /** Like accountSend, except one account is sending multiple payments (with the diff --git a/include/xrpl/protocol/AMMCore.h b/include/xrpl/protocol/AMMCore.h index 1a0252d67a..7a835b44cd 100644 --- a/include/xrpl/protocol/AMMCore.h +++ b/include/xrpl/protocol/AMMCore.h @@ -2,7 +2,7 @@ #include #include -#include +#include #include #include @@ -31,12 +31,12 @@ class Rules; /** Calculate Liquidity Provider Token (LPT) Currency. */ Currency -ammLPTCurrency(Currency const& cur1, Currency const& cur2); +ammLPTCurrency(Asset const& asset1, Asset const& asset2); /** Calculate LPT Issue from AMM asset pair. */ Issue -ammLPTIssue(Currency const& cur1, Currency const& cur2, AccountID const& ammAccountID); +ammLPTIssue(Asset const& asset1, Asset const& asset2, AccountID const& ammAccountID); /** Validate the amount. * If validZero is false and amount is beast::zero then invalid amount. @@ -46,19 +46,19 @@ ammLPTIssue(Currency const& cur1, Currency const& cur2, AccountID const& ammAcco NotTEC invalidAMMAmount( STAmount const& amount, - std::optional> const& pair = std::nullopt, + std::optional> const& pair = std::nullopt, bool validZero = false); NotTEC invalidAMMAsset( - Issue const& issue, - std::optional> const& pair = std::nullopt); + Asset const& asset, + std::optional> const& pair = std::nullopt); NotTEC invalidAMMAssetPair( - Issue const& issue1, - Issue const& issue2, - std::optional> const& pair = std::nullopt); + Asset const& asset1, + Asset const& asset2, + std::optional> const& pair = std::nullopt); /** Get time slot of the auction slot. */ diff --git a/include/xrpl/protocol/AmountConversions.h b/include/xrpl/protocol/AmountConversions.h index 7e41eff41a..e1965c1d5c 100644 --- a/include/xrpl/protocol/AmountConversions.h +++ b/include/xrpl/protocol/AmountConversions.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -9,11 +10,12 @@ namespace xrpl { inline STAmount -toSTAmount(IOUAmount const& iou, Issue const& iss) +toSTAmount(IOUAmount const& iou, Asset const& asset) { + XRPL_ASSERT(asset.holds(), "xrpl::toSTAmount : is Issue"); bool const isNeg = iou.signum() < 0; std::uint64_t const umant = isNeg ? -iou.mantissa() : iou.mantissa(); - return STAmount(iss, umant, iou.exponent(), isNeg, STAmount::unchecked()); + return STAmount(asset, umant, iou.exponent(), isNeg, STAmount::unchecked()); } inline STAmount @@ -31,12 +33,25 @@ toSTAmount(XRPAmount const& xrp) } inline STAmount -toSTAmount(XRPAmount const& xrp, Issue const& iss) +toSTAmount(XRPAmount const& xrp, Asset const& asset) { - XRPL_ASSERT(isXRP(iss.account) && isXRP(iss.currency), "xrpl::toSTAmount : is XRP"); + XRPL_ASSERT(isXRP(asset), "xrpl::toSTAmount : is XRP"); return toSTAmount(xrp); } +inline STAmount +toSTAmount(MPTAmount const& mpt) +{ + return STAmount(mpt, noMPT()); +} + +inline STAmount +toSTAmount(MPTAmount const& mpt, Asset const& asset) +{ + XRPL_ASSERT(asset.holds(), "xrpl::toSTAmount : is MPT"); + return STAmount(mpt, asset.get()); +} + template T toAmount(STAmount const& amt) = delete; @@ -76,6 +91,21 @@ toAmount(STAmount const& amt) return XRPAmount(sMant); } +template <> +inline MPTAmount +toAmount(STAmount const& amt) +{ + XRPL_ASSERT( + amt.holds() && amt.mantissa() <= maxMPTokenAmount && amt.exponent() == 0, + "xrpl::toAmount : maximum mantissa"); + if (amt.mantissa() > maxMPTokenAmount || amt.exponent() != 0) + Throw("toAmount: invalid mantissa or exponent"); + bool const isNeg = amt.negative(); + std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); + + return MPTAmount(sMant); +} + template T toAmount(IOUAmount const& amt) = delete; @@ -98,23 +128,36 @@ toAmount(XRPAmount const& amt) return amt; } +template +T +toAmount(MPTAmount const& amt) = delete; + +template <> +inline MPTAmount +toAmount(MPTAmount const& amt) +{ + return amt; +} + template T -toAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Number::getround()) +toAmount(Asset const& asset, Number const& n, Number::rounding_mode mode = Number::getround()) { saveNumberRoundMode const rm(Number::getround()); - if (isXRP(issue)) + if (isXRP(asset)) Number::setround(mode); if constexpr (std::is_same_v) return IOUAmount(n); else if constexpr (std::is_same_v) return XRPAmount(static_cast(n)); + else if constexpr (std::is_same_v) + return MPTAmount(static_cast(n)); else if constexpr (std::is_same_v) { - if (isXRP(issue)) - return STAmount(issue, static_cast(n)); - return STAmount(issue, n); + if (isXRP(asset)) + return STAmount(asset, static_cast(n)); + return STAmount(asset, n); } else { @@ -125,17 +168,23 @@ toAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Numbe template T -toMaxAmount(Issue const& issue) +toMaxAmount(Asset const& asset) { if constexpr (std::is_same_v) return IOUAmount(STAmount::cMaxValue, STAmount::cMaxOffset); else if constexpr (std::is_same_v) return XRPAmount(static_cast(STAmount::cMaxNativeN)); + else if constexpr (std::is_same_v) + return MPTAmount(maxMPTokenAmount); else if constexpr (std::is_same_v) { - if (isXRP(issue)) - return STAmount(issue, static_cast(STAmount::cMaxNativeN)); - return STAmount(issue, STAmount::cMaxValue, STAmount::cMaxOffset); + return asset.visit( + [](Issue const& issue) { + if (isXRP(issue)) + return STAmount(issue, static_cast(STAmount::cMaxNativeN)); + return STAmount(issue, STAmount::cMaxValue, STAmount::cMaxOffset); + }, + [](MPTIssue const& issue) { return STAmount(issue, maxMPTokenAmount); }); } else { @@ -145,21 +194,23 @@ toMaxAmount(Issue const& issue) } inline STAmount -toSTAmount(Issue const& issue, Number const& n, Number::rounding_mode mode = Number::getround()) +toSTAmount(Asset const& asset, Number const& n, Number::rounding_mode mode = Number::getround()) { - return toAmount(issue, n, mode); + return toAmount(asset, n, mode); } template -Issue -getIssue(T const& amt) +Asset +getAsset(T const& amt) { if constexpr (std::is_same_v) return noIssue(); else if constexpr (std::is_same_v) return xrpIssue(); + else if constexpr (std::is_same_v) + return noMPT(); else if constexpr (std::is_same_v) - return amt.issue(); + return amt.asset(); else { constexpr bool alwaysFalse = !std::is_same_v; @@ -175,6 +226,8 @@ get(STAmount const& a) return a.iou(); else if constexpr (std::is_same_v) return a.xrp(); + else if constexpr (std::is_same_v) + return a.mpt(); else if constexpr (std::is_same_v) return a; else diff --git a/include/xrpl/protocol/Asset.h b/include/xrpl/protocol/Asset.h index d48bc94b50..c8c629ab48 100644 --- a/include/xrpl/protocol/Asset.h +++ b/include/xrpl/protocol/Asset.h @@ -2,20 +2,37 @@ #include #include +#include #include #include +#include namespace xrpl { -class Asset; class STAmount; -template -concept ValidIssueType = std::is_same_v || std::is_same_v; +template + requires( + std::is_same_v || std::is_same_v || + std::is_same_v) +struct AmountType +{ + using amount_type = T; +}; -template -concept AssetType = std::is_convertible_v || std::is_convertible_v || - std::is_convertible_v || std::is_convertible_v; +/* Used to check for an asset with either badCurrency() + * or MPT with 0 account. + */ +struct BadAsset +{ +}; + +inline BadAsset const& +badAsset() +{ + static BadAsset const a; + return a; +} /* Asset is an abstraction of three different issue types: XRP, IOU, MPT. * For historical reasons, two issue types XRP and IOU are wrapped in Issue @@ -26,6 +43,9 @@ class Asset { public: using value_type = std::variant; + using token_type = std::variant; + using AmtType = + std::variant, AmountType, AmountType>; private: value_type issue_; @@ -69,36 +89,42 @@ public: constexpr value_type const& value() const; + constexpr token_type + token() const; + void setJson(Json::Value& jv) const; STAmount operator()(Number const&) const; - bool + constexpr AmtType + getAmountType() const; + + // Custom, generic visit implementation + template + constexpr auto + visit(Visitors&&... visitors) const -> decltype(auto) + { + // Simple delegation to the reusable utility, passing the internal + // variant data. + return detail::visit(issue_, std::forward(visitors)...); + } + + constexpr bool native() const { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - return issue.native(); - if constexpr (std::is_same_v) - return false; - }, - issue_); + return visit( + [&](Issue const& issue) { return issue.native(); }, + [&](MPTIssue const&) { return false; }); } bool integral() const { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - return issue.native(); - if constexpr (std::is_same_v) - return true; - }, - issue_); + return visit( + [&](Issue const& issue) { return issue.native(); }, + [&](MPTIssue const&) { return true; }); } friend constexpr bool @@ -110,6 +136,10 @@ public: friend constexpr bool operator==(Currency const& lhs, Asset const& rhs); + // rhs is either badCurrency() or MPT issuer is 0 + friend constexpr bool + operator==(BadAsset const& lhs, Asset const& rhs); + /** Return true if both assets refer to the same currency (regardless of * issuer) or MPT issuance. Otherwise return false. */ @@ -117,6 +147,12 @@ public: equalTokens(Asset const& lhs, Asset const& rhs); }; +template +constexpr bool is_issue_v = std::is_same_v; + +template +constexpr bool is_mptissue_v = std::is_same_v; + inline Json::Value to_json(Asset const& asset) { @@ -156,6 +192,29 @@ Asset::value() const return issue_; } +constexpr Asset::token_type +Asset::token() const +{ + return visit( + [&](Issue const& issue) -> Asset::token_type { return issue.currency; }, + [&](MPTIssue const& issue) -> Asset::token_type { return issue.getMptID(); }); +} + +constexpr Asset::AmtType +Asset::getAmountType() const +{ + return visit( + [&](Issue const& issue) -> Asset::AmtType { + constexpr AmountType xrp; + constexpr AmountType iou; + return native() ? AmtType(xrp) : AmtType(iou); + }, + [&](MPTIssue const& issue) -> Asset::AmtType { + constexpr AmountType mpt; + return AmtType(mpt); + }); +} + constexpr bool operator==(Asset const& lhs, Asset const& rhs) { @@ -177,7 +236,7 @@ operator<=>(Asset const& lhs, Asset const& rhs) [](TLhs const& lhs_, TRhs const& rhs_) { if constexpr (std::is_same_v) return std::weak_ordering(lhs_ <=> rhs_); - else if constexpr (std::is_same_v && std::is_same_v) + else if constexpr (is_issue_v && is_mptissue_v) return std::weak_ordering::greater; else return std::weak_ordering::less; @@ -189,7 +248,17 @@ operator<=>(Asset const& lhs, Asset const& rhs) constexpr bool operator==(Currency const& lhs, Asset const& rhs) { - return rhs.holds() && rhs.get().currency == lhs; + return rhs.visit( + [&](Issue const& issue) { return issue.currency == lhs; }, + [](MPTIssue const& issue) { return false; }); +} + +constexpr bool +operator==(BadAsset const&, Asset const& rhs) +{ + return rhs.visit( + [](Issue const& issue) -> bool { return badCurrency() == issue.currency; }, + [](MPTIssue const& issue) -> bool { return issue.getIssuer() == xrpAccount(); }); } constexpr bool @@ -223,4 +292,36 @@ validJSONAsset(Json::Value const& jv); Asset assetFromJson(Json::Value const& jv); +Json::Value +to_json(Asset const& asset); + +inline bool +isConsistent(Asset const& asset) +{ + return asset.visit( + [](Issue const& issue) { return isConsistent(issue); }, + [](MPTIssue const&) { return true; }); +} + +inline bool +validAsset(Asset const& asset) +{ + return asset.visit( + [](Issue const& issue) { return isConsistent(issue) && issue.currency != badCurrency(); }, + [](MPTIssue const& issue) { return issue.getIssuer() != xrpAccount(); }); +} + +template +void +hash_append(Hasher& h, Asset const& r) +{ + using beast::hash_append; + r.visit( + [&](Issue const& issue) { hash_append(h, issue); }, + [&](MPTIssue const& issue) { hash_append(h, issue); }); +} + +std::ostream& +operator<<(std::ostream& os, Asset const& x); + } // namespace xrpl diff --git a/include/xrpl/protocol/Book.h b/include/xrpl/protocol/Book.h index 83965cf701..638d9b387d 100644 --- a/include/xrpl/protocol/Book.h +++ b/include/xrpl/protocol/Book.h @@ -2,7 +2,7 @@ #include #include -#include +#include #include @@ -15,15 +15,15 @@ namespace xrpl { class Book final : public CountedObject { public: - Issue in; - Issue out; + Asset in; + Asset out; std::optional domain; Book() { } - Book(Issue const& in_, Issue const& out_, std::optional const& domain_) + Book(Asset const& in_, Asset const& out_, std::optional const& domain_) : in(in_), out(out_), domain(domain_) { } @@ -112,16 +112,67 @@ public: } }; +template <> +struct hash : private boost::base_from_member, 0> +{ +private: + using id_hash_type = boost::base_from_member, 0>; + +public: + explicit hash() = default; + + using value_type = std::size_t; + using argument_type = xrpl::MPTIssue; + + value_type + operator()(argument_type const& value) const + { + value_type const result(id_hash_type::member(value.getMptID())); + return result; + } +}; + +template <> +struct hash +{ +private: + using value_type = std::size_t; + using argument_type = xrpl::Asset; + + using issue_hasher = std::hash; + using mptissue_hasher = std::hash; + + issue_hasher m_issue_hasher; + mptissue_hasher m_mptissue_hasher; + +public: + explicit hash() = default; + + value_type + operator()(argument_type const& asset) const + { + return asset.visit( + [&](xrpl::Issue const& issue) { + value_type const result(m_issue_hasher(issue)); + return result; + }, + [&](xrpl::MPTIssue const& issue) { + value_type const result(m_mptissue_hasher(issue)); + return result; + }); + } +}; + //------------------------------------------------------------------------------ template <> struct hash { private: - using issue_hasher = std::hash; + using asset_hasher = std::hash; using uint256_hasher = xrpl::uint256::hasher; - issue_hasher m_issue_hasher; + asset_hasher m_asset_hasher; uint256_hasher m_uint256_hasher; public: @@ -133,8 +184,8 @@ public: value_type operator()(argument_type const& value) const { - value_type result(m_issue_hasher(value.in)); - boost::hash_combine(result, m_issue_hasher(value.out)); + value_type result(m_asset_hasher(value.in)); + boost::hash_combine(result, m_asset_hasher(value.out)); if (value.domain) boost::hash_combine(result, m_uint256_hasher(*value.domain)); @@ -159,6 +210,22 @@ struct hash : std::hash // using Base::Base; // inherit ctors }; +template <> +struct hash : std::hash +{ + explicit hash() = default; + + using Base = std::hash; +}; + +template <> +struct hash : std::hash +{ + explicit hash() = default; + + using Base = std::hash; +}; + template <> struct hash : std::hash { diff --git a/include/xrpl/protocol/Concepts.h b/include/xrpl/protocol/Concepts.h new file mode 100644 index 0000000000..5f2eb3c7c8 --- /dev/null +++ b/include/xrpl/protocol/Concepts.h @@ -0,0 +1,86 @@ +#pragma once + +#include + +#include + +namespace xrpl { + +class STAmount; +class Asset; +class Issue; +class MPTIssue; +class IOUAmount; +class XRPAmount; +class MPTAmount; + +template +concept StepAmount = + std::is_same_v || std::is_same_v || std::is_same_v; + +template +concept ValidIssueType = std::is_same_v || std::is_same_v; + +template +concept AssetType = std::is_convertible_v || std::is_convertible_v || + std::is_convertible_v || std::is_convertible_v; + +template +concept ValidPathAsset = (std::is_same_v || std::is_same_v); + +template +concept ValidTaker = + ((std::is_same_v || std::is_same_v || + std::is_same_v) && + (std::is_same_v || std::is_same_v || + std::is_same_v) && + (!std::is_same_v || !std::is_same_v)); + +namespace detail { + +// This template combines multiple callable objects (lambdas) into a single +// object that std::visit can use for overload resolution. +template +struct CombineVisitors : Ts... +{ + // Bring all operator() overloads from base classes into this scope. + // It's the mechanism that makes the CombineVisitors struct function + // as a single callable object with multiple overloads. + using Ts::operator()...; + + // Perfect forwarding constructor to correctly initialize the base class + // lambdas + constexpr CombineVisitors(Ts&&... ts) : Ts(std::forward(ts))... + { + } +}; + +// This function forces function template argument deduction, which is more +// robust than class template argument deduction (CTAD) via the deduction guide. +template +constexpr CombineVisitors...> +make_combine_visitors(Ts&&... ts) +{ + // std::decay_t is used to remove references/constness from the lambda + // types before they are passed as template arguments to the CombineVisitors + // struct. + return CombineVisitors...>{std::forward(ts)...}; +} + +// This function takes ANY variant and ANY number of visitors, and performs the +// visit. It is the reusable core logic. +template +constexpr auto +visit(Variant&& v, Visitors&&... visitors) -> decltype(auto) +{ + // Use the function template helper instead of raw CTAD. + auto visitor_set = make_combine_visitors(std::forward(visitors)...); + + // Delegate to std::visit, perfectly forwarding the variant and the visitor + // set. + return std::visit(visitor_set, std::forward(v)); +} + +} // namespace detail + +} // namespace xrpl diff --git a/include/xrpl/protocol/LedgerFormats.h b/include/xrpl/protocol/LedgerFormats.h index a43f6a7134..06fd1040e1 100644 --- a/include/xrpl/protocol/LedgerFormats.h +++ b/include/xrpl/protocol/LedgerFormats.h @@ -187,7 +187,8 @@ enum LedgerEntryType : std::uint16_t { \ LEDGER_OBJECT(MPToken, \ LSF_FLAG2(lsfMPTLocked, 0x00000001) \ - LSF_FLAG(lsfMPTAuthorized, 0x00000002)) \ + LSF_FLAG(lsfMPTAuthorized, 0x00000002) \ + LSF_FLAG(lsfMPTAMM, 0x00000004)) \ \ LEDGER_OBJECT(Credential, \ LSF_FLAG(lsfAccepted, 0x00010000)) \ diff --git a/include/xrpl/protocol/MPTAmount.h b/include/xrpl/protocol/MPTAmount.h index 5c1642ae5c..33b6e5abe4 100644 --- a/include/xrpl/protocol/MPTAmount.h +++ b/include/xrpl/protocol/MPTAmount.h @@ -22,11 +22,12 @@ public: using value_type = std::int64_t; protected: - value_type value_; + value_type value_{}; public: MPTAmount() = default; constexpr MPTAmount(MPTAmount const& other) = default; + constexpr MPTAmount(beast::Zero); constexpr MPTAmount& operator=(MPTAmount const& other) = default; @@ -85,6 +86,11 @@ constexpr MPTAmount::MPTAmount(value_type value) : value_(value) { } +constexpr MPTAmount::MPTAmount(beast::Zero) +{ + *this = beast::zero; +} + constexpr MPTAmount& MPTAmount::operator=(beast::Zero) { @@ -116,6 +122,14 @@ MPTAmount::value() const return value_; } +// Output MPTAmount as just the value. +template +std::basic_ostream& +operator<<(std::basic_ostream& os, MPTAmount const& q) +{ + return os << q.value(); +} + inline std::string to_string(MPTAmount const& amount) { diff --git a/include/xrpl/protocol/MPTIssue.h b/include/xrpl/protocol/MPTIssue.h index d84a610418..60b7072902 100644 --- a/include/xrpl/protocol/MPTIssue.h +++ b/include/xrpl/protocol/MPTIssue.h @@ -17,7 +17,14 @@ private: public: MPTIssue() = default; - explicit MPTIssue(MPTID const& issuanceID); + MPTIssue(MPTID const& issuanceID); + + MPTIssue(std::uint32_t sequence, AccountID const& account); + + operator MPTID const&() const + { + return mptID_; + } AccountID const& getIssuer() const; @@ -73,6 +80,47 @@ isXRP(MPTID const&) return false; } +inline AccountID +getMPTIssuer(MPTID const& mptid) +{ + static_assert(sizeof(MPTID) == (sizeof(std::uint32_t) + sizeof(AccountID))); + // Extract the 20 bytes for the AccountID + std::array bytes{}; + std::copy_n(mptid.data() + sizeof(std::uint32_t), sizeof(AccountID), bytes.begin()); + + // bit_cast is a "magic" compiler intrinsic that is + // usually optimized away to nothing in the final assembly. + return std::bit_cast(bytes); +} + +// Disallow temporary +inline AccountID const& +getMPTIssuer(MPTID const&&) = delete; +inline AccountID const& +getMPTIssuer(MPTID&&) = delete; + +inline MPTID +noMPT() +{ + static MPTIssue const mpt{0, noAccount()}; + return mpt.getMptID(); +} + +inline MPTID +badMPT() +{ + static MPTIssue const mpt{0, xrpAccount()}; + return mpt.getMptID(); +} + +template +void +hash_append(Hasher& h, MPTIssue const& r) +{ + using beast::hash_append; + hash_append(h, r.getMptID()); +} + Json::Value to_json(MPTIssue const& mptIssue); @@ -82,4 +130,17 @@ to_string(MPTIssue const& mptIssue); MPTIssue mptIssueFromJson(Json::Value const& jv); +std::ostream& +operator<<(std::ostream& os, MPTIssue const& x); + } // namespace xrpl + +namespace std { + +template <> +struct hash : xrpl::MPTID::hasher +{ + explicit hash() = default; +}; + +} // namespace std diff --git a/include/xrpl/protocol/PathAsset.h b/include/xrpl/protocol/PathAsset.h new file mode 100644 index 0000000000..31bd8f384f --- /dev/null +++ b/include/xrpl/protocol/PathAsset.h @@ -0,0 +1,130 @@ +#pragma once + +#include +#include + +namespace xrpl { + +/* Represent STPathElement's asset, which can be Currency or MPTID. + */ +class PathAsset +{ +private: + std::variant easset_; + +public: + PathAsset() = default; + // Enables comparing Asset and PathAsset + PathAsset(Asset const& asset); + PathAsset(Currency const& currency) : easset_(currency) + { + } + PathAsset(MPTID const& mpt) : easset_(mpt) + { + } + + template + constexpr bool + holds() const; + + constexpr bool + isXRP() const; + + template + T const& + get() const; + + constexpr std::variant const& + value() const; + + // Custom, generic visit implementation + template + constexpr auto + visit(Visitors&&... visitors) const -> decltype(auto) + { + // Simple delegation to the reusable utility, passing the internal + // variant data. + return detail::visit(easset_, std::forward(visitors)...); + } + + friend constexpr bool + operator==(PathAsset const& lhs, PathAsset const& rhs); +}; + +template +constexpr bool is_currency_v = std::is_same_v; + +template +constexpr bool is_mptid_v = std::is_same_v; + +inline PathAsset::PathAsset(Asset const& asset) +{ + asset.visit( + [&](Issue const& issue) { easset_ = issue.currency; }, + [&](MPTIssue const& issue) { easset_ = issue.getMptID(); }); +} + +template +constexpr bool +PathAsset::holds() const +{ + return std::holds_alternative(easset_); +} + +template +T const& +PathAsset::get() const +{ + if (!holds()) + Throw("PathAsset doesn't hold requested asset."); + return std::get(easset_); +} + +constexpr std::variant const& +PathAsset::value() const +{ + return easset_; +} + +constexpr bool +PathAsset::isXRP() const +{ + return visit( + [&](Currency const& currency) { return xrpl::isXRP(currency); }, + [](MPTID const&) { return false; }); +} + +constexpr bool +operator==(PathAsset const& lhs, PathAsset const& rhs) +{ + return std::visit( + [](TLhs const& lhs_, TRhs const& rhs_) { + if constexpr (std::is_same_v) + return lhs_ == rhs_; + else + return false; + }, + lhs.value(), + rhs.value()); +} + +template +void +hash_append(Hasher& h, PathAsset const& pathAsset) +{ + std::visit([&](T const& e) { hash_append(h, e); }, pathAsset.value()); +} + +inline bool +isXRP(PathAsset const& asset) +{ + return asset.isXRP(); +} + +std::string +to_string(PathAsset const& asset); + +std::ostream& +operator<<(std::ostream& os, PathAsset const& x); + +} // namespace xrpl diff --git a/include/xrpl/protocol/STAmount.h b/include/xrpl/protocol/STAmount.h index df26f99b75..3fa4a53e3f 100644 --- a/include/xrpl/protocol/STAmount.h +++ b/include/xrpl/protocol/STAmount.h @@ -164,12 +164,9 @@ public: constexpr TIss const& get() const; - Issue const& - issue() const; - - // These three are deprecated - Currency const& - getCurrency() const; + template + TIss& + get(); AccountID const& getIssuer() const; @@ -225,9 +222,6 @@ public: void clear(Asset const& asset); - void - setIssuer(AccountID const& uIssuer); - /** Set the Issue for this amount. */ void setIssue(Asset const& asset); @@ -466,16 +460,11 @@ STAmount::get() const return mAsset.get(); } -inline Issue const& -STAmount::issue() const +template +TIss& +STAmount::get() { - return get(); -} - -inline Currency const& -STAmount::getCurrency() const -{ - return mAsset.get().currency; + return mAsset.get(); } inline AccountID const& @@ -505,11 +494,13 @@ operator bool() const noexcept inline STAmount:: operator Number() const { - if (native()) - return xrp(); - if (mAsset.holds()) - return mpt(); - return iou(); + return asset().visit( + [&](Issue const& issue) -> Number { + if (issue.native()) + return xrp(); + return iou(); + }, + [&](MPTIssue const&) -> Number { return mpt(); }); } inline STAmount& @@ -568,12 +559,6 @@ STAmount::clear(Asset const& asset) clear(); } -inline void -STAmount::setIssuer(AccountID const& uIssuer) -{ - mAsset.get().account = uIssuer; -} - inline STAmount const& STAmount::value() const noexcept { diff --git a/include/xrpl/protocol/STObject.h b/include/xrpl/protocol/STObject.h index 61a1cce05e..7553521237 100644 --- a/include/xrpl/protocol/STObject.h +++ b/include/xrpl/protocol/STObject.h @@ -349,6 +349,8 @@ public: void setFieldH128(SField const& field, uint128 const&); void + setFieldH192(SField const& field, uint192 const&); + void setFieldH256(SField const& field, uint256 const&); void setFieldI32(SField const& field, std::int32_t); diff --git a/include/xrpl/protocol/STPathSet.h b/include/xrpl/protocol/STPathSet.h index 2ccbc3d657..1d6fce5c18 100644 --- a/include/xrpl/protocol/STPathSet.h +++ b/include/xrpl/protocol/STPathSet.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include @@ -16,7 +18,7 @@ class STPathElement final : public CountedObject { unsigned int mType; AccountID mAccountID; - Currency mCurrencyID; + PathAsset mAssetID; AccountID mIssuerID; bool is_offer_; @@ -28,8 +30,10 @@ public: typeAccount = 0x01, // Rippling through an account (vs taking an offer). typeCurrency = 0x10, // Currency follows. typeIssuer = 0x20, // Issuer follows. + typeMPT = 0x40, // MPT follows. typeBoundary = 0xFF, // Boundary between alternate paths. - typeAll = typeAccount | typeCurrency | typeIssuer, + typeAsset = typeCurrency | typeMPT, + typeAll = typeAccount | typeCurrency | typeIssuer | typeMPT, // Combination of all types. }; @@ -40,19 +44,19 @@ public: STPathElement( std::optional const& account, - std::optional const& currency, + std::optional const& asset, std::optional const& issuer); STPathElement( AccountID const& account, - Currency const& currency, + PathAsset const& asset, AccountID const& issuer, - bool forceCurrency = false); + bool forceAsset = false); STPathElement( unsigned int uType, AccountID const& account, - Currency const& currency, + PathAsset const& asset, AccountID const& issuer); auto @@ -70,6 +74,12 @@ public: bool hasCurrency() const; + bool + hasMPT() const; + + bool + hasAsset() const; + bool isNone() const; @@ -78,12 +88,21 @@ public: AccountID const& getAccountID() const; + PathAsset const& + getPathAsset() const; + Currency const& getCurrency() const; + MPTID const& + getMPTID() const; + AccountID const& getIssuerID() const; + bool + isType(Type const& pe) const; + bool operator==(STPathElement const& t) const; @@ -118,7 +137,7 @@ public: emplace_back(Args&&... args); bool - hasSeen(AccountID const& account, Currency const& currency, AccountID const& issuer) const; + hasSeen(AccountID const& account, PathAsset const& asset, AccountID const& issuer) const; Json::Value getJson(JsonOptions) const; @@ -221,7 +240,7 @@ inline STPathElement::STPathElement() : mType(typeNone), is_offer_(true) inline STPathElement::STPathElement( std::optional const& account, - std::optional const& currency, + std::optional const& asset, std::optional const& issuer) : mType(typeNone) { @@ -238,10 +257,10 @@ inline STPathElement::STPathElement( mAccountID != noAccount(), "xrpl::STPathElement::STPathElement : account is set"); } - if (currency) + if (asset) { - mCurrencyID = *currency; - mType |= typeCurrency; + mAssetID = *asset; + mType |= mAssetID.holds() ? typeCurrency : typeMPT; } if (issuer) @@ -256,20 +275,20 @@ inline STPathElement::STPathElement( inline STPathElement::STPathElement( AccountID const& account, - Currency const& currency, + PathAsset const& asset, AccountID const& issuer, - bool forceCurrency) + bool forceAsset) : mType(typeNone) , mAccountID(account) - , mCurrencyID(currency) + , mAssetID(asset) , mIssuerID(issuer) , is_offer_(isXRP(mAccountID)) { if (!is_offer_) mType |= typeAccount; - if (forceCurrency || !isXRP(currency)) - mType |= typeCurrency; + if (forceAsset || !isXRP(mAssetID)) + mType |= asset.holds() ? typeCurrency : typeMPT; if (!isXRP(issuer)) mType |= typeIssuer; @@ -280,14 +299,19 @@ inline STPathElement::STPathElement( inline STPathElement::STPathElement( unsigned int uType, AccountID const& account, - Currency const& currency, + PathAsset const& asset, AccountID const& issuer) : mType(uType) , mAccountID(account) - , mCurrencyID(currency) + , mAssetID(asset) , mIssuerID(issuer) , is_offer_(isXRP(mAccountID)) { + // uType could be assetType; i.e. either Currency or MPTID. + // Get the actual type. + mAssetID.visit( + [&](Currency const&) { mType = mType & (~Type::typeMPT); }, + [&](MPTID const&) { mType = mType & (~Type::typeCurrency); }); hash_value_ = get_hash(*this); } @@ -309,16 +333,34 @@ STPathElement::isAccount() const return !isOffer(); } +inline bool +STPathElement::isType(Type const& pe) const +{ + return (mType & pe) != 0u; +} + inline bool STPathElement::hasIssuer() const { - return getNodeType() & STPathElement::typeIssuer; + return isType(STPathElement::typeIssuer); } inline bool STPathElement::hasCurrency() const { - return getNodeType() & STPathElement::typeCurrency; + return isType(STPathElement::typeCurrency); +} + +inline bool +STPathElement::hasMPT() const +{ + return isType(STPathElement::typeMPT); +} + +inline bool +STPathElement::hasAsset() const +{ + return isType(STPathElement::typeAsset); } inline bool @@ -335,10 +377,22 @@ STPathElement::getAccountID() const return mAccountID; } +inline PathAsset const& +STPathElement::getPathAsset() const +{ + return mAssetID; +} + inline Currency const& STPathElement::getCurrency() const { - return mCurrencyID; + return mAssetID.get(); +} + +inline MPTID const& +STPathElement::getMPTID() const +{ + return mAssetID.get(); } inline AccountID const& @@ -351,7 +405,7 @@ inline bool STPathElement::operator==(STPathElement const& t) const { return (mType & typeAccount) == (t.mType & typeAccount) && hash_value_ == t.hash_value_ && - mAccountID == t.mAccountID && mCurrencyID == t.mCurrencyID && mIssuerID == t.mIssuerID; + mAccountID == t.mAccountID && mAssetID == t.mAssetID && mIssuerID == t.mIssuerID; } inline bool diff --git a/include/xrpl/protocol/TER.h b/include/xrpl/protocol/TER.h index 64201881b0..0d8bb94b06 100644 --- a/include/xrpl/protocol/TER.h +++ b/include/xrpl/protocol/TER.h @@ -121,6 +121,7 @@ enum TEMcodes : TERUnderlyingType { temARRAY_TOO_LARGE, temBAD_TRANSFER_FEE, temINVALID_INNER_BATCH, + temBAD_MPT, }; //------------------------------------------------------------------------------ @@ -208,6 +209,7 @@ enum TERcodes : TERUnderlyingType { terADDRESS_COLLISION, // Failed to allocate AccountID when trying to // create a pseudo-account terNO_DELEGATE_PERMISSION, // Delegate does not have permission + terLOCKED, // MPT is locked }; //------------------------------------------------------------------------------ diff --git a/include/xrpl/protocol/detail/features.macro b/include/xrpl/protocol/detail/features.macro index c697629e59..494b3fa6cd 100644 --- a/include/xrpl/protocol/detail/features.macro +++ b/include/xrpl/protocol/detail/features.macro @@ -15,6 +15,7 @@ // Add new amendments to the top of this list. // Keep it sorted in reverse chronological order. +XRPL_FEATURE(MPTokensV2, Supported::no, VoteBehavior::DefaultNo) XRPL_FIX (Security3_1_3, Supported::no, VoteBehavior::DefaultNo) XRPL_FIX (PermissionedDomainInvariant, Supported::yes, VoteBehavior::DefaultNo) XRPL_FIX (ExpiredNFTokenOfferRemoval, Supported::yes, VoteBehavior::DefaultNo) diff --git a/include/xrpl/protocol/detail/ledger_entries.macro b/include/xrpl/protocol/detail/ledger_entries.macro index 7955dcb66c..e4182f0cba 100644 --- a/include/xrpl/protocol/detail/ledger_entries.macro +++ b/include/xrpl/protocol/detail/ledger_entries.macro @@ -161,8 +161,10 @@ LEDGER_ENTRY(ltDIR_NODE, 0x0064, DirectoryNode, directory, ({ {sfOwner, soeOPTIONAL}, // for owner directories {sfTakerPaysCurrency, soeOPTIONAL}, // order book directories {sfTakerPaysIssuer, soeOPTIONAL}, // order book directories + {sfTakerPaysMPT, soeOPTIONAL}, // order book directories {sfTakerGetsCurrency, soeOPTIONAL}, // order book directories {sfTakerGetsIssuer, soeOPTIONAL}, // order book directories + {sfTakerGetsMPT, soeOPTIONAL}, // order book directories {sfExchangeRate, soeOPTIONAL}, // order book directories {sfIndexes, soeREQUIRED}, {sfRootIndex, soeREQUIRED}, diff --git a/include/xrpl/protocol/detail/sfields.macro b/include/xrpl/protocol/detail/sfields.macro index a203f2fe8c..4f21207831 100644 --- a/include/xrpl/protocol/detail/sfields.macro +++ b/include/xrpl/protocol/detail/sfields.macro @@ -159,6 +159,8 @@ TYPED_SFIELD(sfTakerGetsIssuer, UINT160, 4) // 192-bit (common) TYPED_SFIELD(sfMPTokenIssuanceID, UINT192, 1) TYPED_SFIELD(sfShareMPTID, UINT192, 2) +TYPED_SFIELD(sfTakerPaysMPT, UINT192, 3) +TYPED_SFIELD(sfTakerGetsMPT, UINT192, 4) // 256-bit (common) TYPED_SFIELD(sfLedgerHash, UINT256, 1) diff --git a/include/xrpl/protocol/detail/transactions.macro b/include/xrpl/protocol/detail/transactions.macro index a2f3c1be43..e52d28ce2a 100644 --- a/include/xrpl/protocol/detail/transactions.macro +++ b/include/xrpl/protocol/detail/transactions.macro @@ -27,7 +27,7 @@ TRANSACTION(ttPAYMENT, 0, Payment, Delegation::delegable, uint256{}, - createAcct, + createAcct | mayCreateMPT, ({ {sfDestination, soeREQUIRED}, {sfAmount, soeREQUIRED, soeMPTSupported}, @@ -129,10 +129,10 @@ TRANSACTION(ttREGULAR_KEY_SET, 5, SetRegularKey, TRANSACTION(ttOFFER_CREATE, 7, OfferCreate, Delegation::delegable, uint256{}, - noPriv, + mayCreateMPT, ({ - {sfTakerPays, soeREQUIRED}, - {sfTakerGets, soeREQUIRED}, + {sfTakerPays, soeREQUIRED, soeMPTSupported}, + {sfTakerGets, soeREQUIRED, soeMPTSupported}, {sfExpiration, soeOPTIONAL}, {sfOfferSequence, soeOPTIONAL}, {sfDomainID, soeOPTIONAL}, @@ -239,7 +239,7 @@ TRANSACTION(ttCHECK_CREATE, 16, CheckCreate, noPriv, ({ {sfDestination, soeREQUIRED}, - {sfSendMax, soeREQUIRED}, + {sfSendMax, soeREQUIRED, soeMPTSupported}, {sfExpiration, soeOPTIONAL}, {sfDestinationTag, soeOPTIONAL}, {sfInvoiceID, soeOPTIONAL}, @@ -252,11 +252,11 @@ TRANSACTION(ttCHECK_CREATE, 16, CheckCreate, TRANSACTION(ttCHECK_CASH, 17, CheckCash, Delegation::delegable, uint256{}, - noPriv, + mayCreateMPT, ({ {sfCheckID, soeREQUIRED}, - {sfAmount, soeOPTIONAL}, - {sfDeliverMin, soeOPTIONAL}, + {sfAmount, soeOPTIONAL, soeMPTSupported}, + {sfDeliverMin, soeOPTIONAL, soeMPTSupported}, })) /** This transaction type cancels an existing check. */ @@ -409,12 +409,12 @@ TRANSACTION(ttCLAWBACK, 30, Clawback, TRANSACTION(ttAMM_CLAWBACK, 31, AMMClawback, Delegation::delegable, featureAMMClawback, - mayDeleteAcct | overrideFreeze, + mayDeleteAcct | overrideFreeze | mayAuthorizeMPT, ({ {sfHolder, soeREQUIRED}, - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, - {sfAmount, soeOPTIONAL}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, + {sfAmount, soeOPTIONAL, soeMPTSupported}, })) /** This transaction type creates an AMM instance */ @@ -424,10 +424,10 @@ TRANSACTION(ttAMM_CLAWBACK, 31, AMMClawback, TRANSACTION(ttAMM_CREATE, 35, AMMCreate, Delegation::delegable, featureAMM, - createPseudoAcct, + createPseudoAcct | mayCreateMPT, ({ - {sfAmount, soeREQUIRED}, - {sfAmount2, soeREQUIRED}, + {sfAmount, soeREQUIRED, soeMPTSupported}, + {sfAmount2, soeREQUIRED, soeMPTSupported}, {sfTradingFee, soeREQUIRED}, })) @@ -440,10 +440,10 @@ TRANSACTION(ttAMM_DEPOSIT, 36, AMMDeposit, featureAMM, noPriv, ({ - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, - {sfAmount, soeOPTIONAL}, - {sfAmount2, soeOPTIONAL}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, + {sfAmount, soeOPTIONAL, soeMPTSupported}, + {sfAmount2, soeOPTIONAL, soeMPTSupported}, {sfEPrice, soeOPTIONAL}, {sfLPTokenOut, soeOPTIONAL}, {sfTradingFee, soeOPTIONAL}, @@ -456,12 +456,12 @@ TRANSACTION(ttAMM_DEPOSIT, 36, AMMDeposit, TRANSACTION(ttAMM_WITHDRAW, 37, AMMWithdraw, Delegation::delegable, featureAMM, - mayDeleteAcct, + mayDeleteAcct | mayAuthorizeMPT, ({ - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, - {sfAmount, soeOPTIONAL}, - {sfAmount2, soeOPTIONAL}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, + {sfAmount, soeOPTIONAL, soeMPTSupported}, + {sfAmount2, soeOPTIONAL, soeMPTSupported}, {sfEPrice, soeOPTIONAL}, {sfLPTokenIn, soeOPTIONAL}, })) @@ -475,8 +475,8 @@ TRANSACTION(ttAMM_VOTE, 38, AMMVote, featureAMM, noPriv, ({ - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, {sfTradingFee, soeREQUIRED}, })) @@ -489,8 +489,8 @@ TRANSACTION(ttAMM_BID, 39, AMMBid, featureAMM, noPriv, ({ - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, {sfBidMin, soeOPTIONAL}, {sfBidMax, soeOPTIONAL}, {sfAuthAccounts, soeOPTIONAL}, @@ -503,10 +503,10 @@ TRANSACTION(ttAMM_BID, 39, AMMBid, TRANSACTION(ttAMM_DELETE, 40, AMMDelete, Delegation::delegable, featureAMM, - mustDeleteAcct, + mustDeleteAcct | mayDeleteMPT, ({ - {sfAsset, soeREQUIRED}, - {sfAsset2, soeREQUIRED}, + {sfAsset, soeREQUIRED, soeMPTSupported}, + {sfAsset2, soeREQUIRED, soeMPTSupported}, })) /** This transactions creates a crosschain sequence number */ diff --git a/include/xrpl/protocol/jss.h b/include/xrpl/protocol/jss.h index ecd9d65b4e..a22810ac8a 100644 --- a/include/xrpl/protocol/jss.h +++ b/include/xrpl/protocol/jss.h @@ -401,6 +401,8 @@ JSS(min_ledger); // in: LedgerCleaner JSS(minimum_fee); // out: TxQ JSS(minimum_level); // out: TxQ JSS(missingCommand); // error +JSS(mpt_issuance_id_a); // out: BookChanges +JSS(mpt_issuance_id_b); // out: BookChanges JSS(name); // out: AmendmentTableImpl, PeerImp JSS(needed_state_hashes); // out: InboundLedger JSS(needed_transaction_hashes); // out: InboundLedger diff --git a/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h b/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h index 545542ec6c..4c06ac5bbb 100644 --- a/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h +++ b/include/xrpl/protocol_autogen/ledger_entries/DirectoryNode.h @@ -117,6 +117,30 @@ public: return this->sle_->isFieldPresent(sfTakerPaysIssuer); } + /** + * @brief Get sfTakerPaysMPT (soeOPTIONAL) + * @return The field value, or std::nullopt if not present. + */ + [[nodiscard]] + protocol_autogen::Optional + getTakerPaysMPT() const + { + if (hasTakerPaysMPT()) + return this->sle_->at(sfTakerPaysMPT); + return std::nullopt; + } + + /** + * @brief Check if sfTakerPaysMPT is present. + * @return True if the field is present, false otherwise. + */ + [[nodiscard]] + bool + hasTakerPaysMPT() const + { + return this->sle_->isFieldPresent(sfTakerPaysMPT); + } + /** * @brief Get sfTakerGetsCurrency (soeOPTIONAL) * @return The field value, or std::nullopt if not present. @@ -165,6 +189,30 @@ public: return this->sle_->isFieldPresent(sfTakerGetsIssuer); } + /** + * @brief Get sfTakerGetsMPT (soeOPTIONAL) + * @return The field value, or std::nullopt if not present. + */ + [[nodiscard]] + protocol_autogen::Optional + getTakerGetsMPT() const + { + if (hasTakerGetsMPT()) + return this->sle_->at(sfTakerGetsMPT); + return std::nullopt; + } + + /** + * @brief Check if sfTakerGetsMPT is present. + * @return True if the field is present, false otherwise. + */ + [[nodiscard]] + bool + hasTakerGetsMPT() const + { + return this->sle_->isFieldPresent(sfTakerGetsMPT); + } + /** * @brief Get sfExchangeRate (soeOPTIONAL) * @return The field value, or std::nullopt if not present. @@ -427,6 +475,17 @@ public: return *this; } + /** + * @brief Set sfTakerPaysMPT (soeOPTIONAL) + * @return Reference to this builder for method chaining. + */ + DirectoryNodeBuilder& + setTakerPaysMPT(std::decay_t const& value) + { + object_[sfTakerPaysMPT] = value; + return *this; + } + /** * @brief Set sfTakerGetsCurrency (soeOPTIONAL) * @return Reference to this builder for method chaining. @@ -449,6 +508,17 @@ public: return *this; } + /** + * @brief Set sfTakerGetsMPT (soeOPTIONAL) + * @return Reference to this builder for method chaining. + */ + DirectoryNodeBuilder& + setTakerGetsMPT(std::decay_t const& value) + { + object_[sfTakerGetsMPT] = value; + return *this; + } + /** * @brief Set sfExchangeRate (soeOPTIONAL) * @return Reference to this builder for method chaining. diff --git a/include/xrpl/protocol_autogen/transactions/AMMBid.h b/include/xrpl/protocol_autogen/transactions/AMMBid.h index d3f8cba8f7..4e5c5d1d15 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMBid.h +++ b/include/xrpl/protocol_autogen/transactions/AMMBid.h @@ -49,6 +49,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -192,6 +194,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMBidBuilder& @@ -203,6 +206,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMBidBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMClawback.h b/include/xrpl/protocol_autogen/transactions/AMMClawback.h index 9603cad6ef..3a968f34d2 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMClawback.h +++ b/include/xrpl/protocol_autogen/transactions/AMMClawback.h @@ -21,7 +21,7 @@ class AMMClawbackBuilder; * Type: ttAMM_CLAWBACK (31) * Delegable: Delegation::delegable * Amendment: featureAMMClawback - * Privileges: mayDeleteAcct | overrideFreeze + * Privileges: mayDeleteAcct | overrideFreeze | mayAuthorizeMPT * * Immutable wrapper around STTx providing type-safe field access. * Use AMMClawbackBuilder to construct new transactions. @@ -60,6 +60,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -71,6 +72,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -82,6 +84,7 @@ public: /** * @brief Get sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -166,6 +169,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMClawbackBuilder& @@ -177,6 +181,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMClawbackBuilder& @@ -188,6 +193,7 @@ public: /** * @brief Set sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMClawbackBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMCreate.h b/include/xrpl/protocol_autogen/transactions/AMMCreate.h index 311d19a3c4..ad6a253ffc 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMCreate.h +++ b/include/xrpl/protocol_autogen/transactions/AMMCreate.h @@ -21,7 +21,7 @@ class AMMCreateBuilder; * Type: ttAMM_CREATE (35) * Delegable: Delegation::delegable * Amendment: featureAMM - * Privileges: createPseudoAcct + * Privileges: createPseudoAcct | mayCreateMPT * * Immutable wrapper around STTx providing type-safe field access. * Use AMMCreateBuilder to construct new transactions. @@ -49,6 +49,7 @@ public: /** * @brief Get sfAmount (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAmount2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -129,6 +131,7 @@ public: /** * @brief Set sfAmount (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMCreateBuilder& @@ -140,6 +143,7 @@ public: /** * @brief Set sfAmount2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMCreateBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMDelete.h b/include/xrpl/protocol_autogen/transactions/AMMDelete.h index bc61434d0b..3325ee63b3 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMDelete.h +++ b/include/xrpl/protocol_autogen/transactions/AMMDelete.h @@ -21,7 +21,7 @@ class AMMDeleteBuilder; * Type: ttAMM_DELETE (40) * Delegable: Delegation::delegable * Amendment: featureAMM - * Privileges: mustDeleteAcct + * Privileges: mustDeleteAcct | mayDeleteMPT * * Immutable wrapper around STTx providing type-safe field access. * Use AMMDeleteBuilder to construct new transactions. @@ -49,6 +49,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -116,6 +118,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDeleteBuilder& @@ -127,6 +130,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDeleteBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMDeposit.h b/include/xrpl/protocol_autogen/transactions/AMMDeposit.h index 8e86339b0a..bb9a36d218 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMDeposit.h +++ b/include/xrpl/protocol_autogen/transactions/AMMDeposit.h @@ -49,6 +49,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -71,6 +73,7 @@ public: /** * @brief Get sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -97,6 +100,7 @@ public: /** * @brief Get sfAmount2 (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -246,6 +250,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDepositBuilder& @@ -257,6 +262,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDepositBuilder& @@ -268,6 +274,7 @@ public: /** * @brief Set sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDepositBuilder& @@ -279,6 +286,7 @@ public: /** * @brief Set sfAmount2 (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMDepositBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMVote.h b/include/xrpl/protocol_autogen/transactions/AMMVote.h index a4e58c9aa4..3baa3f6d41 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMVote.h +++ b/include/xrpl/protocol_autogen/transactions/AMMVote.h @@ -49,6 +49,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -129,6 +131,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMVoteBuilder& @@ -140,6 +143,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMVoteBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/AMMWithdraw.h b/include/xrpl/protocol_autogen/transactions/AMMWithdraw.h index da19c546ee..99f82b69c8 100644 --- a/include/xrpl/protocol_autogen/transactions/AMMWithdraw.h +++ b/include/xrpl/protocol_autogen/transactions/AMMWithdraw.h @@ -21,7 +21,7 @@ class AMMWithdrawBuilder; * Type: ttAMM_WITHDRAW (37) * Delegable: Delegation::delegable * Amendment: featureAMM - * Privileges: mayDeleteAcct + * Privileges: mayDeleteAcct | mayAuthorizeMPT * * Immutable wrapper around STTx providing type-safe field access. * Use AMMWithdrawBuilder to construct new transactions. @@ -49,6 +49,7 @@ public: /** * @brief Get sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -71,6 +73,7 @@ public: /** * @brief Get sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -97,6 +100,7 @@ public: /** * @brief Get sfAmount2 (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -220,6 +224,7 @@ public: /** * @brief Set sfAsset (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMWithdrawBuilder& @@ -231,6 +236,7 @@ public: /** * @brief Set sfAsset2 (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMWithdrawBuilder& @@ -242,6 +248,7 @@ public: /** * @brief Set sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMWithdrawBuilder& @@ -253,6 +260,7 @@ public: /** * @brief Set sfAmount2 (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ AMMWithdrawBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/CheckCash.h b/include/xrpl/protocol_autogen/transactions/CheckCash.h index 2a2bc9c7af..34dc91c61b 100644 --- a/include/xrpl/protocol_autogen/transactions/CheckCash.h +++ b/include/xrpl/protocol_autogen/transactions/CheckCash.h @@ -21,7 +21,7 @@ class CheckCashBuilder; * Type: ttCHECK_CASH (17) * Delegable: Delegation::delegable * Amendment: uint256{} - * Privileges: noPriv + * Privileges: mayCreateMPT * * Immutable wrapper around STTx providing type-safe field access. * Use CheckCashBuilder to construct new transactions. @@ -60,6 +60,7 @@ public: /** * @brief Get sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -86,6 +87,7 @@ public: /** * @brief Get sfDeliverMin (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value, or std::nullopt if not present. */ [[nodiscard]] @@ -166,6 +168,7 @@ public: /** * @brief Set sfAmount (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ CheckCashBuilder& @@ -177,6 +180,7 @@ public: /** * @brief Set sfDeliverMin (soeOPTIONAL) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ CheckCashBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/CheckCreate.h b/include/xrpl/protocol_autogen/transactions/CheckCreate.h index ba209a7fc4..f5e2ad23a9 100644 --- a/include/xrpl/protocol_autogen/transactions/CheckCreate.h +++ b/include/xrpl/protocol_autogen/transactions/CheckCreate.h @@ -60,6 +60,7 @@ public: /** * @brief Get sfSendMax (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -205,6 +206,7 @@ public: /** * @brief Set sfSendMax (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ CheckCreateBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/OfferCreate.h b/include/xrpl/protocol_autogen/transactions/OfferCreate.h index a0eff385f6..2735eb85f7 100644 --- a/include/xrpl/protocol_autogen/transactions/OfferCreate.h +++ b/include/xrpl/protocol_autogen/transactions/OfferCreate.h @@ -21,7 +21,7 @@ class OfferCreateBuilder; * Type: ttOFFER_CREATE (7) * Delegable: Delegation::delegable * Amendment: uint256{} - * Privileges: noPriv + * Privileges: mayCreateMPT * * Immutable wrapper around STTx providing type-safe field access. * Use OfferCreateBuilder to construct new transactions. @@ -49,6 +49,7 @@ public: /** * @brief Get sfTakerPays (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -60,6 +61,7 @@ public: /** * @brief Get sfTakerGets (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return The field value. */ [[nodiscard]] @@ -194,6 +196,7 @@ public: /** * @brief Set sfTakerPays (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ OfferCreateBuilder& @@ -205,6 +208,7 @@ public: /** * @brief Set sfTakerGets (soeREQUIRED) + * @note This field supports MPT (Multi-Purpose Token) amounts. * @return Reference to this builder for method chaining. */ OfferCreateBuilder& diff --git a/include/xrpl/protocol_autogen/transactions/Payment.h b/include/xrpl/protocol_autogen/transactions/Payment.h index 877286f90e..edf496dc6d 100644 --- a/include/xrpl/protocol_autogen/transactions/Payment.h +++ b/include/xrpl/protocol_autogen/transactions/Payment.h @@ -21,7 +21,7 @@ class PaymentBuilder; * Type: ttPAYMENT (0) * Delegable: Delegation::delegable * Amendment: uint256{} - * Privileges: createAcct + * Privileges: createAcct | mayCreateMPT * * Immutable wrapper around STTx providing type-safe field access. * Use PaymentBuilder to construct new transactions. diff --git a/include/xrpl/tx/invariants/InvariantCheck.h b/include/xrpl/tx/invariants/InvariantCheck.h index e7ced63785..ad4c5e16c4 100644 --- a/include/xrpl/tx/invariants/InvariantCheck.h +++ b/include/xrpl/tx/invariants/InvariantCheck.h @@ -398,7 +398,8 @@ using InvariantChecks = std::tuple< ValidPseudoAccounts, ValidLoanBroker, ValidLoan, - ValidVault>; + ValidVault, + ValidMPTPayment>; /** * @brief get a tuple of all invariant checks diff --git a/include/xrpl/tx/invariants/InvariantCheckPrivilege.h b/include/xrpl/tx/invariants/InvariantCheckPrivilege.h index 161b3572db..684e40c8cf 100644 --- a/include/xrpl/tx/invariants/InvariantCheckPrivilege.h +++ b/include/xrpl/tx/invariants/InvariantCheckPrivilege.h @@ -44,6 +44,7 @@ enum Privilege { mayDeleteMPT = 0x0400, // The transaction MAY delete an MPT object. May not create. mustModifyVault = 0x0800, // The transaction must modify, delete or create, a vault mayModifyVault = 0x1000, // The transaction MAY modify, delete or create, a vault + mayCreateMPT = 0x2000, // The transaction MAY create an MPT object, except for issuer. }; constexpr Privilege diff --git a/include/xrpl/tx/invariants/MPTInvariant.h b/include/xrpl/tx/invariants/MPTInvariant.h index 68f866d362..dd064af396 100644 --- a/include/xrpl/tx/invariants/MPTInvariant.h +++ b/include/xrpl/tx/invariants/MPTInvariant.h @@ -28,4 +28,32 @@ public: finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&) const; }; +/** Verify: + * - OutstandingAmount <= MaximumAmount for any MPT + * - OutstandingAmount after = OutstandingAmount before + + * sum (MPT after - MPT before) - this is total MPT credit/debit + */ +class ValidMPTPayment +{ + enum Order { Before = 0, After = 1 }; + struct MPTData + { + std::array outstanding{}; + // sum (MPT after - MPT before) + std::int64_t mptAmount{0}; + }; + + // true if OutstandingAmount > MaximumAmount in after for any MPT + bool overflow_{false}; + // mptid:MPTData + hash_map data_; + +public: + void + visitEntry(bool, std::shared_ptr const&, std::shared_ptr const&); + + bool + finalize(STTx const&, TER const, XRPAmount const, ReadView const&, beast::Journal const&); +}; + } // namespace xrpl diff --git a/include/xrpl/tx/paths/AMMLiquidity.h b/include/xrpl/tx/paths/AMMLiquidity.h index 87d6ffe32f..5716ea531d 100644 --- a/include/xrpl/tx/paths/AMMLiquidity.h +++ b/include/xrpl/tx/paths/AMMLiquidity.h @@ -5,12 +5,13 @@ #include #include #include +#include #include #include namespace xrpl { -template +template class AMMOffer; /** AMMLiquidity class provides AMM offers to BookStep class. @@ -35,8 +36,8 @@ private: AMMContext& ammContext_; AccountID const ammAccountID_; std::uint32_t const tradingFee_; - Issue const issueIn_; - Issue const issueOut_; + Asset const assetIn_; + Asset const assetOut_; // Initial AMM pool balances TAmounts const initialBalances_; beast::Journal const j_; @@ -46,8 +47,8 @@ public: ReadView const& view, AccountID const& ammAccountID, std::uint32_t tradingFee, - Issue const& in, - Issue const& out, + Asset const& in, + Asset const& out, AMMContext& ammContext, beast::Journal j); ~AMMLiquidity() = default; @@ -87,16 +88,16 @@ public: return ammContext_; } - Issue const& - issueIn() const + Asset const& + assetIn() const { - return issueIn_; + return assetIn_; } - Issue const& - issueOut() const + Asset const& + assetOut() const { - return issueOut_; + return assetOut_; } private: diff --git a/include/xrpl/tx/paths/AMMOffer.h b/include/xrpl/tx/paths/AMMOffer.h index 4ef1b2048b..de583a60d6 100644 --- a/include/xrpl/tx/paths/AMMOffer.h +++ b/include/xrpl/tx/paths/AMMOffer.h @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -16,7 +17,7 @@ class QualityFunction; * methods for use in generic BookStep methods. AMMOffer amounts * are changed indirectly in BookStep limiting steps. */ -template +template class AMMOffer { private: @@ -52,8 +53,11 @@ public: return quality_; } - Issue const& - issueIn() const; + Asset const& + assetIn() const; + + Asset const& + assetOut() const; AccountID const& owner() const; @@ -99,7 +103,8 @@ public: static TER send(Args&&... args) { - return accountSend(std::forward(args)..., WaiveTransferFee::Yes); + return accountSend( + std::forward(args)..., WaiveTransferFee::Yes, AllowMPTOverflow::Yes); } bool diff --git a/include/xrpl/tx/paths/Offer.h b/include/xrpl/tx/paths/Offer.h index de3eed933a..ae7a47061a 100644 --- a/include/xrpl/tx/paths/Offer.h +++ b/include/xrpl/tx/paths/Offer.h @@ -3,6 +3,8 @@ #include #include #include +#include +#include #include #include #include @@ -12,28 +14,15 @@ namespace xrpl { -template -class TOfferBase -{ -protected: - Issue issIn_; - Issue issOut_; -}; - -template <> -class TOfferBase -{ -public: - explicit TOfferBase() = default; -}; - -template -class TOffer : private TOfferBase +template +class TOffer { private: SLE::pointer m_entry; Quality m_quality{}; AccountID m_account; + Asset assetIn_; + Asset assetOut_; TAmounts m_amounts{}; void @@ -113,10 +102,10 @@ public: return m_entry->key(); } - Issue const& - issueIn() const; - Issue const& - issueOut() const; + Asset const& + assetIn() const; + Asset const& + assetOut() const; TAmounts limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const; @@ -131,8 +120,8 @@ public: bool isFunded() const { - // Offer owner is issuer; they have unlimited funds - return m_account == issueOut().account; + // Offer owner is issuer; they have unlimited funds if IOU + return m_account == assetOut_.getIssuer() && assetOut_.holds(); } static std::pair @@ -167,9 +156,7 @@ public: } }; -using Offer = TOffer<>; - -template +template TOffer::TOffer(SLE::pointer const& entry, Quality quality) : m_entry(entry), m_quality(quality), m_account(m_entry->getAccountID(sfAccount)) { @@ -177,33 +164,26 @@ TOffer::TOffer(SLE::pointer const& entry, Quality quality) auto const tg = m_entry->getFieldAmount(sfTakerGets); m_amounts.in = toAmount(tp); m_amounts.out = toAmount(tg); - this->issIn_ = tp.issue(); - this->issOut_ = tg.issue(); + assetIn_ = tp.asset(); + assetOut_ = tg.asset(); } -template <> -inline TOffer::TOffer(SLE::pointer const& entry, Quality quality) - : m_entry(entry) - , m_quality(quality) - , m_account(m_entry->getAccountID(sfAccount)) - , m_amounts(m_entry->getFieldAmount(sfTakerPays), m_entry->getFieldAmount(sfTakerGets)) -{ -} - -template +template void TOffer::setFieldAmounts() { - // LCOV_EXCL_START -#ifdef _MSC_VER - UNREACHABLE("xrpl::TOffer::setFieldAmounts : must be specialized"); -#else - static_assert(sizeof(TOut) == -1, "Must be specialized"); -#endif - // LCOV_EXCL_STOP + if constexpr (std::is_same_v) + m_entry->setFieldAmount(sfTakerPays, toSTAmount(m_amounts.in)); + else + m_entry->setFieldAmount(sfTakerPays, toSTAmount(m_amounts.in, assetIn_)); + + if constexpr (std::is_same_v) + m_entry->setFieldAmount(sfTakerGets, toSTAmount(m_amounts.out)); + else + m_entry->setFieldAmount(sfTakerGets, toSTAmount(m_amounts.out, assetOut_)); } -template +template TAmounts TOffer::limitOut(TAmounts const& offerAmount, TOut const& limit, bool roundUp) const @@ -213,7 +193,7 @@ TOffer::limitOut(TAmounts const& offerAmount, TOut const& return quality().ceil_out_strict(offerAmount, limit, roundUp); } -template +template TAmounts TOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const @@ -228,75 +208,29 @@ TOffer::limitIn(TAmounts const& offerAmount, TIn const& li return m_quality.ceil_in(offerAmount, limit); } -template +template template TER TOffer::send(Args&&... args) { - return accountSend(std::forward(args)...); + return accountSend(std::forward(args)..., WaiveTransferFee::No, AllowMPTOverflow::Yes); } -template <> -inline void -TOffer::setFieldAmounts() +template +Asset const& +TOffer::assetIn() const { - m_entry->setFieldAmount(sfTakerPays, m_amounts.in); - m_entry->setFieldAmount(sfTakerGets, m_amounts.out); + return assetIn_; } -template <> -inline void -TOffer::setFieldAmounts() +template +Asset const& +TOffer::assetOut() const { - m_entry->setFieldAmount(sfTakerPays, toSTAmount(m_amounts.in, issIn_)); - m_entry->setFieldAmount(sfTakerGets, toSTAmount(m_amounts.out, issOut_)); + return assetOut_; } -template <> -inline void -TOffer::setFieldAmounts() -{ - m_entry->setFieldAmount(sfTakerPays, toSTAmount(m_amounts.in, issIn_)); - m_entry->setFieldAmount(sfTakerGets, toSTAmount(m_amounts.out)); -} - -template <> -inline void -TOffer::setFieldAmounts() -{ - m_entry->setFieldAmount(sfTakerPays, toSTAmount(m_amounts.in)); - m_entry->setFieldAmount(sfTakerGets, toSTAmount(m_amounts.out, issOut_)); -} - -template -Issue const& -TOffer::issueIn() const -{ - return this->issIn_; -} - -template <> -inline Issue const& -TOffer::issueIn() const -{ - return m_amounts.in.issue(); -} - -template -Issue const& -TOffer::issueOut() const -{ - return this->issOut_; -} - -template <> -inline Issue const& -TOffer::issueOut() const -{ - return m_amounts.out.issue(); -} - -template +template inline std::ostream& operator<<(std::ostream& os, TOffer const& offer) { diff --git a/include/xrpl/tx/paths/OfferStream.h b/include/xrpl/tx/paths/OfferStream.h index ba553360ef..e40387e3d2 100644 --- a/include/xrpl/tx/paths/OfferStream.h +++ b/include/xrpl/tx/paths/OfferStream.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -11,7 +12,7 @@ namespace xrpl { -template +template class TOfferStreamBase { public: @@ -64,6 +65,7 @@ protected: permRmOffer(uint256 const& offerIndex) = 0; template + requires ValidTaker bool shouldRmSmallIncreasedQOffer() const; @@ -105,33 +107,6 @@ public: } }; -/** Presents and consumes the offers in an order book. - - Two `ApplyView` objects accumulate changes to the ledger. `view` - is applied when the calling transaction succeeds. If the calling - transaction fails, then `view_cancel` is applied. - - Certain invalid offers are automatically removed: - - Offers with missing ledger entries - - Offers that expired - - Offers found unfunded: - An offer is found unfunded when the corresponding balance is zero - and the caller has not modified the balance. This is accomplished - by also looking up the balance in the cancel view. - - When an offer is removed, it is removed from both views. This grooms the - order book regardless of whether or not the transaction is successful. -*/ -class OfferStream : public TOfferStreamBase -{ -protected: - void - permRmOffer(uint256 const& offerIndex) override; - -public: - using TOfferStreamBase::TOfferStreamBase; -}; - /** Presents and consumes the offers in an order book. The `view_' ` `ApplyView` accumulates changes to the ledger. @@ -149,7 +124,7 @@ public: and the caller has not modified the balance. This is accomplished by also looking up the balance in the cancel view. */ -template +template class FlowOfferStream : public TOfferStreamBase { private: diff --git a/include/xrpl/tx/paths/detail/AmountSpec.h b/include/xrpl/tx/paths/detail/AmountSpec.h index 1adee6a0a3..e69de29bb2 100644 --- a/include/xrpl/tx/paths/detail/AmountSpec.h +++ b/include/xrpl/tx/paths/detail/AmountSpec.h @@ -1,198 +0,0 @@ -#pragma once - -#include -#include -#include - -#include - -namespace xrpl { - -struct AmountSpec -{ - explicit AmountSpec() = default; - - bool native{}; - union - { - XRPAmount xrp; - IOUAmount iou = {}; - }; - std::optional issuer; - std::optional currency; - - friend std::ostream& - operator<<(std::ostream& stream, AmountSpec const& amt) - { - if (amt.native) - stream << to_string(amt.xrp); - else - stream << to_string(amt.iou); - if (amt.currency) - stream << "/(" << *amt.currency << ")"; - if (amt.issuer) - stream << "/" << *amt.issuer << ""; - return stream; - } -}; - -struct EitherAmount -{ -#ifndef NDEBUG - bool native = false; -#endif - - union - { - IOUAmount iou = {}; - XRPAmount xrp; - }; - - EitherAmount() = default; - - explicit EitherAmount(IOUAmount const& a) : iou(a) - { - } - -#if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic push - // ignore warning about half of iou amount being uninitialized -#pragma GCC diagnostic ignored "-Wmaybe-uninitialized" -#endif - explicit EitherAmount(XRPAmount const& a) : xrp(a) - { -#ifndef NDEBUG - native = true; -#endif - } -#if defined(__GNUC__) && !defined(__clang__) -#pragma GCC diagnostic pop -#endif - - explicit EitherAmount(AmountSpec const& a) - { -#ifndef NDEBUG - native = a.native; -#endif - if (a.native) - xrp = a.xrp; - else - iou = a.iou; - } - -#ifndef NDEBUG - friend std::ostream& - operator<<(std::ostream& stream, EitherAmount const& amt) - { - if (amt.native) - stream << to_string(amt.xrp); - else - stream << to_string(amt.iou); - return stream; - } -#endif -}; - -template -T& -get(EitherAmount& amt) -{ - static_assert(sizeof(T) == -1, "Must used specialized function"); - return T(0); -} - -template <> -inline IOUAmount& -get(EitherAmount& amt) -{ - XRPL_ASSERT(!amt.native, "xrpl::get(EitherAmount&) : is not XRP"); - return amt.iou; -} - -template <> -inline XRPAmount& -get(EitherAmount& amt) -{ - XRPL_ASSERT(amt.native, "xrpl::get(EitherAmount&) : is XRP"); - return amt.xrp; -} - -template -T const& -get(EitherAmount const& amt) -{ - static_assert(sizeof(T) == -1, "Must used specialized function"); - return T(0); -} - -template <> -inline IOUAmount const& -get(EitherAmount const& amt) -{ - XRPL_ASSERT(!amt.native, "xrpl::get(EitherAmount const&) : is not XRP"); - return amt.iou; -} - -template <> -inline XRPAmount const& -get(EitherAmount const& amt) -{ - XRPL_ASSERT(amt.native, "xrpl::get(EitherAmount const&) : is XRP"); - return amt.xrp; -} - -inline AmountSpec -toAmountSpec(STAmount const& amt) -{ - XRPL_ASSERT( - amt.mantissa() < std::numeric_limits::max(), - "xrpl::toAmountSpec(STAmount const&) : maximum mantissa"); - bool const isNeg = amt.negative(); - std::int64_t const sMant = isNeg ? -std::int64_t(amt.mantissa()) : amt.mantissa(); - AmountSpec result; - - result.native = isXRP(amt); - if (result.native) - { - result.xrp = XRPAmount(sMant); - } - else - { - result.iou = IOUAmount(sMant, amt.exponent()); - result.issuer = amt.issue().account; - result.currency = amt.issue().currency; - } - - return result; -} - -inline EitherAmount -toEitherAmount(STAmount const& amt) -{ - if (isXRP(amt)) - return EitherAmount{amt.xrp()}; - return EitherAmount{amt.iou()}; -} - -inline AmountSpec -toAmountSpec(EitherAmount const& ea, std::optional const& c) -{ - AmountSpec r; - r.native = (!c || isXRP(*c)); - r.currency = c; - XRPL_ASSERT( - ea.native == r.native, - "xrpl::toAmountSpec(EitherAmount const&&, std::optional) : " - "matching native"); - if (r.native) - { - r.xrp = ea.xrp; - } - else - { - r.iou = ea.iou; - } - return r; -} - -} // namespace xrpl diff --git a/include/xrpl/tx/paths/detail/EitherAmount.h b/include/xrpl/tx/paths/detail/EitherAmount.h new file mode 100644 index 0000000000..ffd90751b8 --- /dev/null +++ b/include/xrpl/tx/paths/detail/EitherAmount.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include + +namespace xrpl { + +struct EitherAmount +{ + std::variant amount; + + explicit EitherAmount() = default; + + template + explicit EitherAmount(T const& a) : amount(a) + { + } + + template + [[nodiscard]] bool + holds() const + { + return std::holds_alternative(amount); + } + + template + [[nodiscard]] T const& + get() const + { + if (!holds()) + Throw("EitherAmount doesn't hold requested amount"); + return std::get(amount); + } + +#ifndef NDEBUG + friend std::ostream& + operator<<(std::ostream& stream, EitherAmount const& amt) + { + std::visit([&](T const& a) { stream << to_string(a); }, amt.amount); + return stream; + } +#endif +}; + +template +T const& +get(EitherAmount const& amt) +{ + return amt.get(); +} + +} // namespace xrpl diff --git a/include/xrpl/tx/paths/detail/FlowDebugInfo.h b/include/xrpl/tx/paths/detail/FlowDebugInfo.h index d2d9dc8466..3a1f45fd02 100644 --- a/include/xrpl/tx/paths/detail/FlowDebugInfo.h +++ b/include/xrpl/tx/paths/detail/FlowDebugInfo.h @@ -208,14 +208,14 @@ struct FlowDebugInfo auto writeXrpAmtList = [&write_list]( std::vector const& amts, char delim = ';') { auto get_val = [](EitherAmount const& a) -> std::string { - return xrpl::to_string(a.xrp); + return xrpl::to_string(a.get()); }; write_list(amts, get_val, delim); }; auto writeIouAmtList = [&write_list]( std::vector const& amts, char delim = ';') { auto get_val = [](EitherAmount const& a) -> std::string { - return xrpl::to_string(a.iou); + return xrpl::to_string(a.get()); }; write_list(amts, get_val, delim); }; diff --git a/include/xrpl/tx/paths/detail/StepChecks.h b/include/xrpl/tx/paths/detail/StepChecks.h index c866705a4c..7ad9279c87 100644 --- a/include/xrpl/tx/paths/detail/StepChecks.h +++ b/include/xrpl/tx/paths/detail/StepChecks.h @@ -50,8 +50,7 @@ checkFreeze( if (!sleAmm) return tecINTERNAL; // LCOV_EXCL_LINE - if (isLPTokenFrozen( - view, src, (*sleAmm)[sfAsset].get(), (*sleAmm)[sfAsset2].get())) + if (isLPTokenFrozen(view, src, (*sleAmm)[sfAsset], (*sleAmm)[sfAsset2])) { return terNO_LINE; } diff --git a/include/xrpl/tx/paths/detail/Steps.h b/include/xrpl/tx/paths/detail/Steps.h index 0b75974acb..4fa3b09d07 100644 --- a/include/xrpl/tx/paths/detail/Steps.h +++ b/include/xrpl/tx/paths/detail/Steps.h @@ -2,11 +2,11 @@ #include #include +#include #include #include -#include #include -#include +#include #include @@ -44,6 +44,7 @@ issues(DebtDirection dir) BookStepIX is an IOU/XRP offer book BookStepXI is an XRP/IOU offer book XRPEndpointStep is the source or destination account for XRP + MPTEndpointStep is the source or destination account for MPT Amounts may be transformed through a step in either the forward or the reverse direction. In the forward direction, the function `fwd` is used to @@ -339,8 +340,8 @@ std::pair normalizePath( AccountID const& src, AccountID const& dst, - Issue const& deliver, - std::optional const& sendMaxIssue, + Asset const& deliver, + std::optional const& sendMaxAsset, STPath const& path); /** @@ -355,7 +356,7 @@ normalizePath( optimization. If, during direct offer crossing, the quality of the tip of the book drops below this value, then evaluating the strand can stop. - @param sendMaxIssue Optional asset to send. + @param sendMaxAsset Optional asset to send. @param path Liquidity sources to use for this strand of the payment. The path contains an ordered collection of the offer books to use and accounts to ripple through. @@ -372,9 +373,9 @@ toStrand( ReadView const& sb, AccountID const& src, AccountID const& dst, - Issue const& deliver, + Asset const& deliver, std::optional const& limitQuality, - std::optional const& sendMaxIssue, + std::optional const& sendMaxAsset, STPath const& path, bool ownerPaysTransferFee, OfferCrossing offerCrossing, @@ -413,9 +414,9 @@ toStrands( ReadView const& sb, AccountID const& src, AccountID const& dst, - Issue const& deliver, + Asset const& deliver, std::optional const& limitQuality, - std::optional const& sendMax, + std::optional const& sendMax, STPathSet const& paths, bool addDefaultPath, bool ownerPaysTransferFee, @@ -425,7 +426,7 @@ toStrands( beast::Journal j); /// @cond INTERNAL -template +template struct StepImp : public Step { explicit StepImp() = default; @@ -493,8 +494,16 @@ public: // Check equal with tolerance bool checkNear(IOUAmount const& expected, IOUAmount const& actual); -bool -checkNear(XRPAmount const& expected, XRPAmount const& actual); +inline bool +checkNear(MPTAmount const& expected, MPTAmount const& actual) +{ + return expected == actual; +} +inline bool +checkNear(XRPAmount const& expected, XRPAmount const& actual) +{ + return expected == actual; +} /// @endcond /** @@ -505,7 +514,7 @@ struct StrandContext ReadView const& view; ///< Current ReadView AccountID const strandSrc; ///< Strand source account AccountID const strandDst; ///< Strand destination account - Issue const strandDeliver; ///< Issue strand delivers + Asset const strandDeliver; ///< Asset strand delivers std::optional const limitQuality; ///< Worst accepted quality bool const isFirst; ///< true if Step is first in Strand bool const isLast = false; ///< true if Step is last in Strand @@ -522,11 +531,11 @@ struct StrandContext at most twice: once as a src and once as a dst (hence the two element array). The strandSrc and strandDst will only show up once each. */ - std::array, 2>& seenDirectIssues; + std::array, 2>& seenDirectAssets; /** A strand may not include an offer that output the same issue more than once */ - boost::container::flat_set& seenBookOuts; + boost::container::flat_set& seenBookOuts; AMMContext& ammContext; std::optional domainID; // the domain the order book will use beast::Journal const j; @@ -539,15 +548,15 @@ struct StrandContext // replicates the source or destination. AccountID const& strandSrc_, AccountID const& strandDst_, - Issue const& strandDeliver_, + Asset const& strandDeliver_, std::optional const& limitQuality_, bool isLast_, bool ownerPaysTransferFee_, OfferCrossing offerCrossing_, bool isDefaultPath_, - std::array, 2>& - seenDirectIssues_, ///< For detecting currency loops - boost::container::flat_set& seenBookOuts_, ///< For detecting book loops + std::array, 2>& + seenDirectAssets_, ///< For detecting currency loops + boost::container::flat_set& seenBookOuts_, ///< For detecting book loops AMMContext& ammContext_, std::optional const& domainID, beast::Journal j_); ///< Journal for logging @@ -563,6 +572,13 @@ directStepEqual( AccountID const& dst, Currency const& currency); +bool +mptEndpointStepEqual( + Step const& step, + AccountID const& src, + AccountID const& dst, + MPTID const& mptid); + bool xrpEndpointStepEqual(Step const& step, AccountID const& acc); @@ -577,6 +593,13 @@ make_DirectStepI( AccountID const& dst, Currency const& c); +std::pair> +make_MPTEndpointStep( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + MPTID const& a); + std::pair> make_BookStepII(StrandContext const& ctx, Issue const& in, Issue const& out); @@ -589,9 +612,30 @@ make_BookStepXI(StrandContext const& ctx, Issue const& out); std::pair> make_XRPEndpointStep(StrandContext const& ctx, AccountID const& acc); -template +std::pair> +make_BookStepMM(StrandContext const& ctx, MPTIssue const& in, MPTIssue const& out); + +std::pair> +make_BookStepMX(StrandContext const& ctx, MPTIssue const& in); + +std::pair> +make_BookStepXM(StrandContext const& ctx, MPTIssue const& out); + +std::pair> +make_BookStepMI(StrandContext const& ctx, MPTIssue const& in, Issue const& out); + +std::pair> +make_BookStepIM(StrandContext const& ctx, Issue const& in, MPTIssue const& out); + +template bool -isDirectXrpToXrp(Strand const& strand); +isDirectXrpToXrp(Strand const& strand) +{ + if constexpr (std::is_same_v && std::is_same_v) + return strand.size() == 2; + else + return false; +} /// @endcond } // namespace xrpl diff --git a/include/xrpl/tx/paths/detail/StrandFlow.h b/include/xrpl/tx/paths/detail/StrandFlow.h index 1f05ae1a5b..9892facee3 100644 --- a/include/xrpl/tx/paths/detail/StrandFlow.h +++ b/include/xrpl/tx/paths/detail/StrandFlow.h @@ -246,7 +246,7 @@ flow( EitherAmount stepIn(*strand[0]->cachedIn()); for (auto i = 0; i < s; ++i) { - bool valid; + bool valid = false; std::tie(valid, stepIn) = strand[i]->validFwd(checkSB, checkAfView, stepIn); if (!valid) { @@ -379,8 +379,10 @@ limitOut( return XRPAmount{*out}; else if constexpr (std::is_same_v) return IOUAmount{*out}; + else if constexpr (std::is_same_v) + return MPTAmount{*out}; else - return STAmount{remainingOut.issue(), out->mantissa(), out->exponent()}; + return STAmount{remainingOut.asset(), out->mantissa(), out->exponent()}; }(); // A tiny difference could be due to the round off if (withinRelativeDistance(out, remainingOut, Number(1, -9))) @@ -534,7 +536,7 @@ public: @return Actual amount in and out from the strands, errors, and payment sandbox */ -template +template FlowResult flow( PaymentSandbox const& baseView, diff --git a/include/xrpl/tx/transactors/check/CheckCash.h b/include/xrpl/tx/transactors/check/CheckCash.h index c64d45061d..3b914d2024 100644 --- a/include/xrpl/tx/transactors/check/CheckCash.h +++ b/include/xrpl/tx/transactors/check/CheckCash.h @@ -13,6 +13,9 @@ public: { } + static bool + checkExtraFeatures(PreflightContext const& ctx); + static NotTEC preflight(PreflightContext const& ctx); diff --git a/include/xrpl/tx/transactors/check/CheckCreate.h b/include/xrpl/tx/transactors/check/CheckCreate.h index 2b5aa9123d..bcb9d16ea2 100644 --- a/include/xrpl/tx/transactors/check/CheckCreate.h +++ b/include/xrpl/tx/transactors/check/CheckCreate.h @@ -13,6 +13,9 @@ public: { } + static bool + checkExtraFeatures(xrpl::PreflightContext const& ctx); + static NotTEC preflight(PreflightContext const& ctx); diff --git a/include/xrpl/tx/transactors/dex/AMMClawback.h b/include/xrpl/tx/transactors/dex/AMMClawback.h index 2bfccfa202..dd455903a2 100644 --- a/include/xrpl/tx/transactors/dex/AMMClawback.h +++ b/include/xrpl/tx/transactors/dex/AMMClawback.h @@ -13,6 +13,9 @@ public: { } + static bool + checkExtraFeatures(PreflightContext const& ctx); + static std::uint32_t getFlagsMask(PreflightContext const& ctx); diff --git a/include/xrpl/tx/transactors/dex/AMMDeposit.h b/include/xrpl/tx/transactors/dex/AMMDeposit.h index 287d46ff07..e2a19504ae 100644 --- a/include/xrpl/tx/transactors/dex/AMMDeposit.h +++ b/include/xrpl/tx/transactors/dex/AMMDeposit.h @@ -224,7 +224,7 @@ private: AccountID const& ammAccount, STAmount const& amount, STAmount const& amount2, - Issue const& lptIssue, + Asset const& lptIssue, std::uint16_t tfee); }; diff --git a/include/xrpl/tx/transactors/dex/AMMWithdraw.h b/include/xrpl/tx/transactors/dex/AMMWithdraw.h index 5328b03abb..087fd3a14c 100644 --- a/include/xrpl/tx/transactors/dex/AMMWithdraw.h +++ b/include/xrpl/tx/transactors/dex/AMMWithdraw.h @@ -98,7 +98,8 @@ public: STAmount const& lpTokens, STAmount const& lpTokensWithdraw, std::uint16_t tfee, - FreezeHandling freezeHanding, + FreezeHandling freezeHandling, + AuthHandling authHandling, WithdrawAll withdrawAll, XRPAmount const& priorBalance, beast::Journal const& journal); @@ -132,6 +133,7 @@ public: STAmount const& lpTokensWithdraw, std::uint16_t tfee, FreezeHandling freezeHandling, + AuthHandling authHandling, WithdrawAll withdrawAll, XRPAmount const& priorBalance, beast::Journal const& journal); @@ -141,8 +143,8 @@ public: Sandbox& sb, std::shared_ptr const ammSle, STAmount const& lpTokenBalance, - Issue const& issue1, - Issue const& issue2, + Asset const& asset1, + Asset const& asset2, beast::Journal const& journal); private: diff --git a/include/xrpl/tx/transactors/dex/OfferCreate.h b/include/xrpl/tx/transactors/dex/OfferCreate.h index 2179180054..ad36f1b6e6 100644 --- a/include/xrpl/tx/transactors/dex/OfferCreate.h +++ b/include/xrpl/tx/transactors/dex/OfferCreate.h @@ -51,7 +51,7 @@ private: ApplyFlags const flags, AccountID const id, beast::Journal const j, - Issue const& issue); + Asset const& asset); // Use the payment flow code to perform offer crossing. std::pair diff --git a/src/libxrpl/ledger/AcceptedLedgerTx.cpp b/src/libxrpl/ledger/AcceptedLedgerTx.cpp index 005d48e6f6..70deb0139a 100644 --- a/src/libxrpl/ledger/AcceptedLedgerTx.cpp +++ b/src/libxrpl/ledger/AcceptedLedgerTx.cpp @@ -43,13 +43,14 @@ AcceptedLedgerTx::AcceptedLedgerTx( auto const amount = mTxn->getFieldAmount(sfTakerGets); // If the offer create is not self funded then add the owner balance - if (account != amount.issue().account) + if (account != amount.getIssuer()) { auto const ownerFunds = accountFunds( *ledger, account, amount, fhIGNORE_FREEZE, + ahIGNORE_AUTH, beast::Journal{beast::Journal::getNullSink()}); mJson[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } diff --git a/src/libxrpl/ledger/PaymentSandbox.cpp b/src/libxrpl/ledger/PaymentSandbox.cpp index a56d730b5a..a46e22f404 100644 --- a/src/libxrpl/ledger/PaymentSandbox.cpp +++ b/src/libxrpl/ledger/PaymentSandbox.cpp @@ -3,12 +3,14 @@ #include #include +#include + namespace xrpl { namespace detail { auto -DeferredCredits::makeKey(AccountID const& a1, AccountID const& a2, Currency const& c) -> Key +DeferredCredits::makeKeyIOU(AccountID const& a1, AccountID const& a2, Currency const& c) -> KeyIOU { if (a1 < a2) { @@ -19,21 +21,23 @@ DeferredCredits::makeKey(AccountID const& a1, AccountID const& a2, Currency cons } void -DeferredCredits::credit( +DeferredCredits::creditIOU( AccountID const& sender, AccountID const& receiver, STAmount const& amount, STAmount const& preCreditSenderBalance) { XRPL_ASSERT( - sender != receiver, "xrpl::detail::DeferredCredits::credit : sender is not receiver"); - XRPL_ASSERT(!amount.negative(), "xrpl::detail::DeferredCredits::credit : positive amount"); + sender != receiver, "xrpl::detail::DeferredCredits::creditIOU : sender is not receiver"); + XRPL_ASSERT(!amount.negative(), "xrpl::detail::DeferredCredits::creditIOU : positive amount"); + XRPL_ASSERT( + amount.holds(), "xrpl::detail::DeferredCredits::creditIOU : amount is for Issue"); - auto const k = makeKey(sender, receiver, amount.getCurrency()); - auto i = credits_.find(k); - if (i == credits_.end()) + auto const k = makeKeyIOU(sender, receiver, amount.get().currency); + auto i = creditsIOU_.find(k); + if (i == creditsIOU_.end()) { - Value v; + ValueIOU v; if (sender < receiver) { @@ -48,7 +52,7 @@ DeferredCredits::credit( v.lowAcctOrigBalance = -preCreditSenderBalance; } - credits_[k] = v; + creditsIOU_[k] = v; } else { @@ -65,6 +69,93 @@ DeferredCredits::credit( } } +void +DeferredCredits::creditMPT( + AccountID const& sender, + AccountID const& receiver, + STAmount const& amount, + std::uint64_t preCreditBalanceHolder, + std::int64_t preCreditBalanceIssuer) +{ + XRPL_ASSERT( + amount.holds(), + "xrpl::detail::DeferredCredits::creditMPT : amount is for MPTIssue"); + XRPL_ASSERT(!amount.negative(), "xrpl::detail::DeferredCredits::creditMPT : positive amount"); + XRPL_ASSERT( + sender != receiver, "xrpl::detail::DeferredCredits::creditMPT : sender is not receiver"); + + auto const mptAmtVal = amount.mpt().value(); + auto const& issuer = amount.getIssuer(); + auto const& mptIssue = amount.get(); + auto const& mptID = mptIssue.getMptID(); + bool const isSenderIssuer = sender == issuer; + + auto i = creditsMPT_.find(mptID); + if (i == creditsMPT_.end()) + { + IssuerValueMPT v; + if (isSenderIssuer) + { + v.credit = mptAmtVal; + v.holders[receiver].origBalance = preCreditBalanceHolder; + } + else + { + v.holders[sender].debit = mptAmtVal; + v.holders[sender].origBalance = preCreditBalanceHolder; + } + v.origBalance = preCreditBalanceIssuer; + creditsMPT_.emplace(mptID, std::move(v)); + } + else + { + // only record the balance the first time, do not record it here + auto& v = i->second; + if (isSenderIssuer) + { + v.credit += mptAmtVal; + if (!v.holders.contains(receiver)) + { + v.holders[receiver].origBalance = preCreditBalanceHolder; + } + } + else + { + if (!v.holders.contains(sender)) + { + v.holders[sender].debit = mptAmtVal; + v.holders[sender].origBalance = preCreditBalanceHolder; + } + else + { + v.holders[sender].debit += mptAmtVal; + } + } + } +} + +void +DeferredCredits::issuerSelfDebitMPT( + MPTIssue const& issue, + std::uint64_t amount, + std::int64_t origBalance) +{ + auto const& mptID = issue.getMptID(); + auto i = creditsMPT_.find(mptID); + + if (i == creditsMPT_.end()) + { + IssuerValueMPT v; + v.origBalance = origBalance; + v.selfDebit = amount; + creditsMPT_.emplace(mptID, std::move(v)); + } + else + { + i->second.selfDebit += amount; + } +} + void DeferredCredits::ownerCount(AccountID const& id, std::uint32_t cur, std::uint32_t next) { @@ -88,16 +179,16 @@ DeferredCredits::ownerCount(AccountID const& id) const // Get the adjustments for the balance between main and other. auto -DeferredCredits::adjustments( +DeferredCredits::adjustmentsIOU( AccountID const& main, AccountID const& other, - Currency const& currency) const -> std::optional + Currency const& currency) const -> std::optional { - std::optional result; + std::optional result; - Key const k = makeKey(main, other, currency); - auto i = credits_.find(k); - if (i == credits_.end()) + KeyIOU const k = makeKeyIOU(main, other, currency); + auto i = creditsIOU_.find(k); + if (i == creditsIOU_.end()) return result; auto const& v = i->second; @@ -112,12 +203,21 @@ DeferredCredits::adjustments( return result; } +auto +DeferredCredits::adjustmentsMPT(xrpl::MPTID const& mptID) const -> std::optional +{ + auto i = creditsMPT_.find(mptID); + if (i == creditsMPT_.end()) + return std::nullopt; + return i->second; +} + void DeferredCredits::apply(DeferredCredits& to) { - for (auto const& i : credits_) + for (auto const& i : creditsIOU_) { - auto r = to.credits_.emplace(i); + auto r = to.creditsIOU_.emplace(i); if (!r.second) { auto& toVal = r.first->second; @@ -128,6 +228,30 @@ DeferredCredits::apply(DeferredCredits& to) } } + for (auto const& i : creditsMPT_) + { + auto r = to.creditsMPT_.emplace(i); + if (!r.second) + { + auto& toVal = r.first->second; + auto const& fromVal = i.second; + toVal.credit += fromVal.credit; + toVal.selfDebit += fromVal.selfDebit; + for (auto& [k, v] : fromVal.holders) + { + if (toVal.holders.find(k) == toVal.holders.end()) + { + toVal.holders[k] = v; + } + else + { + toVal.holders[k].debit += v.debit; + } + } + // Do not update the orig balance, it's already correct + } + } + for (auto const& i : ownerCounts_) { auto r = to.ownerCounts_.emplace(i); @@ -143,11 +267,13 @@ DeferredCredits::apply(DeferredCredits& to) } // namespace detail STAmount -PaymentSandbox::balanceHook( +PaymentSandbox::balanceHookIOU( AccountID const& account, AccountID const& issuer, STAmount const& amount) const { + XRPL_ASSERT(amount.holds(), "balanceHookIOU: amount is for Issue"); + /* There are two algorithms here. The pre-switchover algorithm takes the current amount and subtracts the recorded credits. The post-switchover @@ -159,14 +285,14 @@ PaymentSandbox::balanceHook( magnitudes, (B+C)-C may not equal B. */ - auto const currency = amount.getCurrency(); + auto const& currency = amount.get().currency; auto delta = amount.zeroed(); auto lastBal = amount; auto minBal = amount; for (auto curSB = this; curSB != nullptr; curSB = curSB->ps_) { - if (auto adj = curSB->tab_.adjustments(account, issuer, currency)) + if (auto adj = curSB->tab_.adjustmentsIOU(account, issuer, currency)) { delta += adj->debits; lastBal = adj->origBalance; @@ -180,13 +306,13 @@ PaymentSandbox::balanceHook( // to compute usable balance just slightly above what the ledger // calculates (but always less than the actual balance). auto adjustedAmt = std::min({amount, lastBal - delta, minBal}); - adjustedAmt.setIssuer(amount.getIssuer()); + adjustedAmt.get().account = amount.getIssuer(); if (isXRP(issuer) && adjustedAmt < beast::zero) { // A calculated negative XRP balance is not an error case. Consider a // payment snippet that credits a large XRP amount and then debits the - // same amount. The credit can't be used but we subtract the debit and + // same amount. The credit can't be used, but we subtract the debit and // calculate a negative value. It's not an error case. adjustedAmt.clear(); } @@ -194,6 +320,64 @@ PaymentSandbox::balanceHook( return adjustedAmt; } +STAmount +PaymentSandbox::balanceHookMPT(AccountID const& account, MPTIssue const& issue, std::int64_t amount) + const +{ + auto const& issuer = issue.getIssuer(); + bool const accountIsHolder = account != issuer; + + std::int64_t delta = 0; + std::int64_t lastBal = amount; + std::int64_t minBal = amount; + for (auto curSB = this; curSB != nullptr; curSB = curSB->ps_) + { + if (auto adj = curSB->tab_.adjustmentsMPT(issue)) + { + if (accountIsHolder) + { + if (auto const i = adj->holders.find(account); i != adj->holders.end()) + { + delta += i->second.debit; + lastBal = i->second.origBalance; + } + } + else + { + delta += adj->credit; + lastBal = adj->origBalance; + } + minBal = std::min(lastBal, minBal); + } + } + + // The adjusted amount should never be larger than the balance. + + auto const adjustedAmt = std::min({amount, lastBal - delta, minBal}); + + return adjustedAmt > 0 ? STAmount{issue, adjustedAmt} : STAmount{issue}; +} + +STAmount +PaymentSandbox::balanceHookSelfIssueMPT(xrpl::MPTIssue const& issue, std::int64_t amount) const +{ + std::int64_t selfDebited = 0; + std::int64_t lastBal = amount; + for (auto curSB = this; curSB != nullptr; curSB = curSB->ps_) + { + if (auto adj = curSB->tab_.adjustmentsMPT(issue)) + { + selfDebited += adj->selfDebit; + lastBal = adj->origBalance; + } + } + + if (lastBal > selfDebited) + return STAmount{issue, lastBal - selfDebited}; + + return STAmount{issue}; +} + std::uint32_t PaymentSandbox::ownerCountHook(AccountID const& account, std::uint32_t count) const { @@ -207,13 +391,39 @@ PaymentSandbox::ownerCountHook(AccountID const& account, std::uint32_t count) co } void -PaymentSandbox::creditHook( +PaymentSandbox::creditHookIOU( AccountID const& from, AccountID const& to, STAmount const& amount, STAmount const& preCreditBalance) { - tab_.credit(from, to, amount, preCreditBalance); + XRPL_ASSERT(amount.holds(), "creditHookIOU: amount is for Issue"); + + tab_.creditIOU(from, to, amount, preCreditBalance); +} + +void +PaymentSandbox::creditHookMPT( + AccountID const& from, + AccountID const& to, + STAmount const& amount, + std::uint64_t preCreditBalanceHolder, + std::int64_t preCreditBalanceIssuer) +{ + XRPL_ASSERT(amount.holds(), "creditHookMPT: amount is for MPTIssue"); + + tab_.creditMPT(from, to, amount, preCreditBalanceHolder, preCreditBalanceIssuer); +} + +void +PaymentSandbox::issuerSelfDebitHookMPT( + MPTIssue const& issue, + std::uint64_t amount, + std::int64_t origBalance) +{ + XRPL_ASSERT(amount > 0, "PaymentSandbox::issuerSelfDebitHookMPT: amount must be > 0"); + + tab_.issuerSelfDebitMPT(issue, amount, origBalance); } void @@ -346,7 +556,7 @@ PaymentSandbox::balanceChanges(ReadView const& view) const } // The following are now set, put them in the map auto delta = newBalance - oldBalance; - auto const cur = newBalance.getCurrency(); + auto const cur = newBalance.get().currency; result[std::make_tuple(lowID, highID, cur)] = delta; auto r = result.emplace(std::make_tuple(lowID, lowID, cur), delta); if (r.second) diff --git a/src/libxrpl/ledger/View.cpp b/src/libxrpl/ledger/View.cpp index 1702d4243b..c96940ec23 100644 --- a/src/libxrpl/ledger/View.cpp +++ b/src/libxrpl/ledger/View.cpp @@ -84,11 +84,10 @@ bool isLPTokenFrozen( ReadView const& view, AccountID const& account, - Issue const& asset, - Issue const& asset2) + Asset const& asset, + Asset const& asset2) { - return isFrozen(view, account, asset.currency, asset.account) || - isFrozen(view, account, asset2.currency, asset2.account); + return isFrozen(view, account, asset) || isFrozen(view, account, asset2); } bool @@ -334,22 +333,19 @@ withdrawToDestExceedsLimit( if (from == to || to == issuer || isXRP(issuer)) return tesSUCCESS; - return std::visit( - [&](TIss const& issue) -> TER { - if constexpr (std::is_same_v) + return amount.asset().visit( + [&](Issue const& issue) -> TER { + auto const& currency = issue.currency; + auto const owed = creditBalance(view, to, issuer, currency); + if (owed <= beast::zero) { - auto const& currency = issue.currency; - auto const owed = creditBalance(view, to, issuer, currency); - if (owed <= beast::zero) - { - auto const limit = creditLimit(view, to, issuer, currency); - if (-owed >= limit || amount > (limit + owed)) - return tecNO_LINE; - } + auto const limit = creditLimit(view, to, issuer, currency); + if (-owed >= limit || amount > (limit + owed)) + return tecNO_LINE; } return tesSUCCESS; }, - amount.asset().value()); + [](MPTIssue const&) -> TER { return tesSUCCESS; }); } [[nodiscard]] TER diff --git a/src/libxrpl/ledger/helpers/AMMHelpers.cpp b/src/libxrpl/ledger/helpers/AMMHelpers.cpp index c65bb1ff11..4c161bd135 100644 --- a/src/libxrpl/ledger/helpers/AMMHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AMMHelpers.cpp @@ -3,7 +3,7 @@ namespace xrpl { STAmount -ammLPTokens(STAmount const& asset1, STAmount const& asset2, Issue const& lptIssue) +ammLPTokens(STAmount const& asset1, STAmount const& asset2, Asset const& lptIssue) { // AMM invariant: sqrt(asset1 * asset2) >= LPTokensBalance auto const rounding = isFeatureEnabled(fixAMMv1_3) ? Number::downward : Number::getround(); @@ -32,7 +32,7 @@ lpTokensOut( if (!isFeatureEnabled(fixAMMv1_3)) { auto const t = lptAMMBalance * (r - c) / (1 + c); - return toSTAmount(lptAMMBalance.issue(), t); + return toSTAmount(lptAMMBalance.asset(), t); } // minimize tokens out @@ -68,7 +68,7 @@ ammAssetIn( auto const c = d * d - f2 * f2; if (!isFeatureEnabled(fixAMMv1_3)) { - return toSTAmount(asset1Balance.issue(), asset1Balance * solveQuadraticEq(a, b, c)); + return toSTAmount(asset1Balance.asset(), asset1Balance * solveQuadraticEq(a, b, c)); } // maximize deposit @@ -93,7 +93,7 @@ lpTokensIn( if (!isFeatureEnabled(fixAMMv1_3)) { auto const t = lptAMMBalance * (c - root2(c * c - 4 * fr)) / 2; - return toSTAmount(lptAMMBalance.issue(), t); + return toSTAmount(lptAMMBalance.asset(), t); } // maximize tokens in @@ -123,7 +123,7 @@ ammAssetOut( if (!isFeatureEnabled(fixAMMv1_3)) { auto const b = assetBalance * (t1 * t1 - t1 * (2 - f)) / (t1 * f - 1); - return toSTAmount(assetBalance.issue(), b); + return toSTAmount(assetBalance.asset(), b); } // minimize withdraw @@ -183,8 +183,8 @@ adjustAmountsByLPTokens( if (amount2) { Number const fr = lpTokensActual / lpTokens; - auto const amountActual = toSTAmount(amount.issue(), fr * amount); - auto const amount2Actual = toSTAmount(amount2->issue(), fr * *amount2); + auto const amountActual = toSTAmount(amount.asset(), fr * amount); + auto const amount2Actual = toSTAmount(amount2->asset(), fr * *amount2); if (!ammRoundingEnabled) { return std::make_tuple( @@ -253,7 +253,7 @@ multiply(STAmount const& amount, Number const& frac, Number::rounding_mode rm) { NumberRoundModeGuard const g(rm); auto const t = amount * frac; - return toSTAmount(amount.issue(), t, rm); + return toSTAmount(amount.asset(), t, rm); } STAmount @@ -265,13 +265,13 @@ getRoundedAsset( IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) - return toSTAmount(balance.issue(), noRoundCb()); + return toSTAmount(balance.asset(), noRoundCb()); auto const rm = detail::getAssetRounding(isDeposit); if (isDeposit == IsDeposit::Yes) return multiply(balance, productCb(), rm); NumberRoundModeGuard const g(rm); - return toSTAmount(balance.issue(), productCb(), rm); + return toSTAmount(balance.asset(), productCb(), rm); } STAmount @@ -282,7 +282,7 @@ getRoundedLPTokens( IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) - return toSTAmount(balance.issue(), balance * frac); + return toSTAmount(balance.asset(), balance * frac); auto const rm = detail::getLPTokenRounding(isDeposit); auto const tokens = multiply(balance, frac, rm); @@ -298,14 +298,14 @@ getRoundedLPTokens( IsDeposit isDeposit) { if (!rules.enabled(fixAMMv1_3)) - return toSTAmount(lptAMMBalance.issue(), noRoundCb()); + return toSTAmount(lptAMMBalance.asset(), noRoundCb()); auto const tokens = [&] { auto const rm = detail::getLPTokenRounding(isDeposit); if (isDeposit == IsDeposit::Yes) { NumberRoundModeGuard const g(rm); - return toSTAmount(lptAMMBalance.issue(), productCb(), rm); + return toSTAmount(lptAMMBalance.asset(), productCb(), rm); } return multiply(lptAMMBalance, productCb(), rm); }(); diff --git a/src/libxrpl/ledger/helpers/AMMUtils.cpp b/src/libxrpl/ledger/helpers/AMMUtils.cpp index 4b71a2e438..166e9e9494 100644 --- a/src/libxrpl/ledger/helpers/AMMUtils.cpp +++ b/src/libxrpl/ledger/helpers/AMMUtils.cpp @@ -12,13 +12,16 @@ std::pair ammPoolHolds( ReadView const& view, AccountID const& ammAccountID, - Issue const& issue1, - Issue const& issue2, + Asset const& asset1, + Asset const& asset2, FreezeHandling freezeHandling, + AuthHandling authHandling, beast::Journal const j) { - auto const assetInBalance = accountHolds(view, ammAccountID, issue1, freezeHandling, j); - auto const assetOutBalance = accountHolds(view, ammAccountID, issue2, freezeHandling, j); + auto const assetInBalance = + accountHolds(view, ammAccountID, asset1, freezeHandling, authHandling, j); + auto const assetOutBalance = + accountHolds(view, ammAccountID, asset2, freezeHandling, authHandling, j); return std::make_pair(assetInBalance, assetOutBalance); } @@ -26,38 +29,39 @@ Expected, TER> ammHolds( ReadView const& view, SLE const& ammSle, - std::optional const& optIssue1, - std::optional const& optIssue2, + std::optional const& optAsset1, + std::optional const& optAsset2, FreezeHandling freezeHandling, + AuthHandling authHandling, beast::Journal const j) { - auto const issues = [&]() -> std::optional> { - auto const issue1 = ammSle[sfAsset].get(); - auto const issue2 = ammSle[sfAsset2].get(); - if (optIssue1 && optIssue2) + auto const assets = [&]() -> std::optional> { + auto const asset1 = ammSle[sfAsset]; + auto const asset2 = ammSle[sfAsset2]; + if (optAsset1 && optAsset2) { if (invalidAMMAssetPair( - *optIssue1, *optIssue2, std::make_optional(std::make_pair(issue1, issue2)))) + *optAsset1, *optAsset2, std::make_optional(std::make_pair(asset1, asset2)))) { // This error can only be hit if the AMM is corrupted // LCOV_EXCL_START - JLOG(j.debug()) << "ammHolds: Invalid optIssue1 or optIssue2 " << *optIssue1 << " " - << *optIssue2; + JLOG(j.debug()) << "ammHolds: Invalid optAsset1 or optAsset2 " << *optAsset1 << " " + << *optAsset2; return std::nullopt; // LCOV_EXCL_STOP } - return std::make_optional(std::make_pair(*optIssue1, *optIssue2)); + return std::make_optional(std::make_pair(*optAsset1, *optAsset2)); } - auto const singleIssue = [&issue1, &issue2, &j]( - Issue checkIssue, - char const* label) -> std::optional> { - if (checkIssue == issue1) + auto const singleAsset = [&asset1, &asset2, &j]( + Asset checkIssue, + char const* label) -> std::optional> { + if (checkIssue == asset1) { - return std::make_optional(std::make_pair(issue1, issue2)); + return std::make_optional(std::make_pair(asset1, asset2)); } - if (checkIssue == issue2) + if (checkIssue == asset2) { - return std::make_optional(std::make_pair(issue2, issue1)); + return std::make_optional(std::make_pair(asset2, asset1)); } // Unreachable unless AMM corrupted. // LCOV_EXCL_START @@ -65,29 +69,35 @@ ammHolds( return std::nullopt; // LCOV_EXCL_STOP }; - if (optIssue1) + if (optAsset1) { - return singleIssue(*optIssue1, "optIssue1"); + return singleAsset(*optAsset1, "optAsset1"); } - if (optIssue2) + if (optAsset2) { // Cannot have Amount2 without Amount. - return singleIssue(*optIssue2, "optIssue2"); // LCOV_EXCL_LINE + return singleAsset(*optAsset2, "optAsset2"); // LCOV_EXCL_LINE } - return std::make_optional(std::make_pair(issue1, issue2)); + return std::make_optional(std::make_pair(asset1, asset2)); }(); - if (!issues) + if (!assets) return Unexpected(tecAMM_INVALID_TOKENS); - auto const [asset1, asset2] = ammPoolHolds( - view, ammSle.getAccountID(sfAccount), issues->first, issues->second, freezeHandling, j); - return std::make_tuple(asset1, asset2, ammSle[sfLPTokenBalance]); + auto const [amount1, amount2] = ammPoolHolds( + view, + ammSle.getAccountID(sfAccount), + assets->first, + assets->second, + freezeHandling, + authHandling, + j); + return std::make_tuple(amount1, amount2, ammSle[sfLPTokenBalance]); } STAmount ammLPHolds( ReadView const& view, - Currency const& cur1, - Currency const& cur2, + Asset const& asset1, + Asset const& asset2, AccountID const& ammAccount, AccountID const& lpAccount, beast::Journal const j) @@ -97,7 +107,7 @@ ammLPHolds( // checks if the underlying assets of LPToken are frozen with the // fixFrozenLPTokenTransfer amendment - auto const currency = ammLPTCurrency(cur1, cur2); + auto const currency = ammLPTCurrency(asset1, asset2); STAmount amount; auto const sle = view.read(keylet::line(lpAccount, ammAccount, currency)); @@ -123,14 +133,14 @@ ammLPHolds( // Put balance in account terms. amount.negate(); } - amount.setIssuer(ammAccount); + amount.get().account = ammAccount; JLOG(j.trace()) << "ammLPHolds:" << " lpAccount=" << to_string(lpAccount) << " amount=" << amount.getFullText(); } - return view.balanceHook(lpAccount, ammAccount, amount); + return view.balanceHookIOU(lpAccount, ammAccount, amount); } STAmount @@ -140,13 +150,7 @@ ammLPHolds( AccountID const& lpAccount, beast::Journal const j) { - return ammLPHolds( - view, - ammSle[sfAsset].get().currency, - ammSle[sfAsset2].get().currency, - ammSle[sfAccount], - lpAccount, - j); + return ammLPHolds(view, ammSle[sfAsset], ammSle[sfAsset2], ammSle[sfAccount], lpAccount, j); } std::uint16_t @@ -180,25 +184,35 @@ getTradingFee(ReadView const& view, SLE const& ammSle, AccountID const& account) } STAmount -ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Issue const& issue) +ammAccountHolds(ReadView const& view, AccountID const& ammAccountID, Asset const& asset) { - if (isXRP(issue)) - { - if (auto const sle = view.read(keylet::account(ammAccountID))) - return (*sle)[sfBalance]; - } - else if ( - auto const sle = view.read(keylet::line(ammAccountID, issue.account, issue.currency)); - sle && !isFrozen(view, ammAccountID, issue.currency, issue.account)) - { - auto amount = (*sle)[sfBalance]; - if (ammAccountID > issue.account) - amount.negate(); - amount.setIssuer(issue.account); - return amount; - } - - return STAmount{issue}; + // Get the actual AMM balance without factoring in the balance hook + return asset.visit( + [&](MPTIssue const& issue) { + if (auto const sle = view.read(keylet::mptoken(issue, ammAccountID)); + sle && !isFrozen(view, ammAccountID, issue)) + return STAmount{issue, (*sle)[sfMPTAmount]}; + return STAmount{asset}; + }, + [&](Issue const& issue) { + if (isXRP(issue)) + { + if (auto const sle = view.read(keylet::account(ammAccountID))) + return (*sle)[sfBalance]; + } + else if ( + auto const sle = + view.read(keylet::line(ammAccountID, issue.account, issue.currency)); + sle && !isFrozen(view, ammAccountID, issue.currency, issue.account)) + { + STAmount amount = (*sle)[sfBalance]; + if (ammAccountID > issue.account) + amount.negate(); + amount.get().account = issue.account; + return amount; + } + return STAmount{asset}; + }); } static TER @@ -214,36 +228,80 @@ deleteAMMTrustLines( [&](LedgerEntryType nodeType, uint256 const&, std::shared_ptr& sleItem) -> std::pair { - // Skip AMM - if (nodeType == LedgerEntryType::ltAMM) + // Skip AMM and MPToken + if (nodeType == ltAMM || nodeType == ltMPTOKEN) return {tesSUCCESS, SkipEntry::Yes}; - // Should only have the trustlines - if (nodeType != LedgerEntryType::ltRIPPLE_STATE) - { - // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMTrustLines: deleting non-trustline " << nodeType; - return {tecINTERNAL, SkipEntry::No}; - // LCOV_EXCL_STOP - } - // Trustlines must have zero balance - if (sleItem->getFieldAmount(sfBalance) != beast::zero) + if (nodeType == ltRIPPLE_STATE) { - // LCOV_EXCL_START - JLOG(j.error()) << "deleteAMMTrustLines: deleting trustline with " - "non-zero balance."; - return {tecINTERNAL, SkipEntry::No}; - // LCOV_EXCL_STOP - } + // Trustlines must have zero balance + if (sleItem->getFieldAmount(sfBalance) != beast::zero) + { + // LCOV_EXCL_START + JLOG(j.error()) << "deleteAMMObjects: deleting trustline with " + "non-zero balance."; + return {tecINTERNAL, SkipEntry::No}; + // LCOV_EXCL_STOP + } - return {deleteAMMTrustLine(sb, sleItem, ammAccountID, j), SkipEntry::No}; + return {deleteAMMTrustLine(sb, sleItem, ammAccountID, j), SkipEntry::No}; + } + // LCOV_EXCL_START + JLOG(j.error()) << "deleteAMMObjects: deleting non-trustline or non-MPT " << nodeType; + return {tecINTERNAL, SkipEntry::No}; + // LCOV_EXCL_STOP }, j, maxTrustlinesToDelete); } +static TER +deleteAMMMPTokens(Sandbox& sb, AccountID const& ammAccountID, beast::Journal j) +{ + return cleanupOnAccountDelete( + sb, + keylet::ownerDir(ammAccountID), + [&](LedgerEntryType nodeType, + uint256 const&, + std::shared_ptr& sleItem) -> std::pair { + // Skip AMM + if (nodeType == ltAMM) + return {tesSUCCESS, SkipEntry::Yes}; + + if (nodeType == ltMPTOKEN) + { + // MPT must have zero balance + if (sleItem->getFieldU64(sfMPTAmount) != 0 || + (*sleItem)[~sfLockedAmount].value_or(0) != 0) + { + // LCOV_EXCL_START + JLOG(j.error()) << "deleteAMMObjects: deleting MPT with " + "non-zero balance."; + return {tecINTERNAL, SkipEntry::No}; + // LCOV_EXCL_STOP + } + + return {deleteAMMMPToken(sb, sleItem, ammAccountID, j), SkipEntry::No}; + } + if (nodeType == ltRIPPLE_STATE) + { + // Trustlines should have been deleted + // LCOV_EXCL_START + JLOG(j.error()) << "deleteAMMObjects: trustlines should have been deleted"; + return {tecINTERNAL, SkipEntry::No}; + // LCOV_EXCL_STOP + } + // LCOV_EXCL_START + JLOG(j.error()) << "deleteAMMObjects: deleting non-trustline or non-MPT " << nodeType; + return {tecINTERNAL, SkipEntry::No}; + // LCOV_EXCL_STOP + }, + j, + 3); // At most two MPToken plus AMM object +} + TER -deleteAMMAccount(Sandbox& sb, Issue const& asset, Issue const& asset2, beast::Journal j) +deleteAMMAccount(Sandbox& sb, Asset const& asset, Asset const& asset2, beast::Journal j) { auto ammSle = sb.peek(keylet::amm(asset, asset2)); if (!ammSle) @@ -269,6 +327,12 @@ deleteAMMAccount(Sandbox& sb, Issue const& asset, Issue const& asset2, beast::Jo !isTesSuccess(ter)) return ter; + // Delete AMM's MPTokens only if all trustlines are deleted. If trustlines + // are not deleted then AMM can be re-created with Deposit and + // AMM's MPToken(s) must exist. + if (auto const ter = deleteAMMMPTokens(sb, ammAccountID, j); !isTesSuccess(ter)) + return ter; + auto const ownerDirKeylet = keylet::ownerDir(ammAccountID); if (!sb.dirRemove(ownerDirKeylet, (*ammSle)[sfOwnerNode], ammSle->key(), false)) { @@ -297,7 +361,7 @@ initializeFeeAuctionVote( ApplyView& view, std::shared_ptr& ammSle, AccountID const& account, - Issue const& lptIssue, + Asset const& lptAsset, std::uint16_t tfee) { auto const& rules = view.rules(); @@ -326,7 +390,7 @@ initializeFeeAuctionVote( .count() + TOTAL_TIME_SLOT_SECS; auctionSlot.setFieldU32(sfExpiration, expiration); - auctionSlot.setFieldAmount(sfPrice, STAmount{lptIssue, 0}); + auctionSlot.setFieldAmount(sfPrice, STAmount{lptAsset, 0}); // Set the fee if (tfee != 0) { @@ -351,17 +415,23 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { // Liquidity Provider (LP) must have one LPToken trustline std::uint8_t nLPTokenTrustLines = 0; - // There are at most two IOU trustlines. One or both could be to the LP - // if LP is the issuer, or a different account if LP is not an issuer. - // For instance, if AMM has two tokens USD and EUR and LP is not the issuer - // of the tokens then the trustlines are between AMM account and the issuer. + // AMM account has at most two IOU (pool tokens, not LPToken) trustlines. + // One or both trustlines could be to the LP if LP is the issuer, + // or a different account if LP is not an issuer. For instance, + // if AMM has two tokens USD and EUR and LP is not the issuer of the tokens + // then the trustlines are between AMM account and the issuer. + // There is one LPToken trustline for each LP. Only remaining LP has + // exactly one LPToken trustlines and at most two IOU trustline for each + // pool token. One or both tokens could be MPT. std::uint8_t nIOUTrustLines = 0; + // There are at most two MPT objects, one for each side of the pool. + std::uint8_t nMPT = 0; // There is only one AMM object bool hasAMM = false; - // AMM LP has at most three trustlines and only one AMM object must exist. - // If there are more than five objects then it's either an error or - // there are more than one LP. Ten pages should be sufficient to include - // five objects. + // AMM LP has at most three trustlines, at most two MPTs, and only one + // AMM object must exist. If there are more than four objects then + // it's either an error or there are more than one LP. Ten pages should + // be sufficient to include four objects. std::uint8_t limit = 10; auto const root = keylet::ownerDir(ammIssue.account); auto currentIndex = root; @@ -377,22 +447,28 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c auto const sle = view.read(keylet::child(key)); if (!sle) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE + auto const entryType = sle->getFieldU16(sfLedgerEntryType); // Only one AMM object - if (sle->getFieldU16(sfLedgerEntryType) == ltAMM) + if (entryType == ltAMM) { if (hasAMM) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE hasAMM = true; continue; } - if (sle->getFieldU16(sfLedgerEntryType) != ltRIPPLE_STATE) + if (entryType == ltMPTOKEN) + { + ++nMPT; + continue; + } + if (entryType != ltRIPPLE_STATE) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE auto const lowLimit = sle->getFieldAmount(sfLowLimit); auto const highLimit = sle->getFieldAmount(sfHighLimit); auto const isLPTrustline = lowLimit.getIssuer() == lpAccount || highLimit.getIssuer() == lpAccount; auto const isLPTokenTrustline = - lowLimit.issue() == ammIssue || highLimit.issue() == ammIssue; + lowLimit.asset() == ammIssue || highLimit.asset() == ammIssue; // Liquidity Provider trustline if (isLPTrustline) @@ -400,9 +476,11 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c // LPToken trustline if (isLPTokenTrustline) { + // LP has exactly one LPToken trustline if (++nLPTokenTrustLines > 1) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE } + // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE @@ -413,6 +491,7 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c { return false; } + // AMM account has at most two IOU trustlines else if (++nIOUTrustLines > 2) { return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE @@ -421,7 +500,8 @@ isOnlyLiquidityProvider(ReadView const& view, Issue const& ammIssue, AccountID c auto const uNodeNext = ownerDir->getFieldU64(sfIndexNext); if (uNodeNext == 0) { - if (nLPTokenTrustLines != 1 || nIOUTrustLines == 0 || nIOUTrustLines > 2) + if (nLPTokenTrustLines != 1 || (nIOUTrustLines == 0 && nMPT == 0) || + (nIOUTrustLines > 2 || nMPT > 2) || (nIOUTrustLines + nMPT) > 2) return Unexpected(tecINTERNAL); // LCOV_EXCL_LINE return true; } @@ -437,7 +517,7 @@ verifyAndAdjustLPTokenBalance( std::shared_ptr& ammSle, AccountID const& account) { - auto const res = isOnlyLiquidityProvider(sb, lpTokens.issue(), account); + auto const res = isOnlyLiquidityProvider(sb, lpTokens.get(), account); if (!res.has_value()) { return Unexpected(res.error()); diff --git a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp index 399494bc5f..19c2a9d7a7 100644 --- a/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp +++ b/src/libxrpl/ledger/helpers/AccountRootHelpers.cpp @@ -80,7 +80,7 @@ xrpLiquid(ReadView const& view, AccountID const& id, std::int32_t ownerCountAdj, auto const fullBalance = sle->getFieldAmount(sfBalance); - auto const balance = view.balanceHook(id, xrpAccount(), fullBalance); + auto const balance = view.balanceHookIOU(id, xrpAccount(), fullBalance); STAmount const amount = (balance < reserve) ? STAmount{0} : balance - reserve; diff --git a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp index 05e4fe1448..3cc359408a 100644 --- a/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/MPTokenHelpers.cpp @@ -306,18 +306,11 @@ requireAuth( return tefINTERNAL; // LCOV_EXCL_LINE auto const asset = sleVault->at(sfAsset); - if (auto const err = std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return requireAuth(view, issue, account, authType); - } - else - { - return requireAuth(view, issue, account, authType, depth + 1); - } - }, - asset.value()); + if (auto const err = asset.visit( + [&](Issue const& issue) { return requireAuth(view, issue, account, authType); }, + [&](MPTIssue const& issue) { + return requireAuth(view, issue, account, authType, depth + 1); + }); !isTesSuccess(err)) return err; } @@ -487,6 +480,21 @@ canTransfer( return tesSUCCESS; } +TER +canTrade(ReadView const& view, Asset const& asset) +{ + return asset.visit( + [&](Issue const&) -> TER { return tesSUCCESS; }, + [&](MPTIssue const& mptIssue) -> TER { + auto const sleIssuance = view.read(keylet::mptIssuance(mptIssue.getMptID())); + if (!sleIssuance) + return tecOBJECT_NOT_FOUND; + if (!sleIssuance->isFlag(lsfMPTCanTrade)) + return tecNO_PERMISSION; + return tesSUCCESS; + }); +} + TER lockEscrowMPT(ApplyView& view, AccountID const& sender, STAmount const& amount, beast::Journal j) { @@ -770,4 +778,149 @@ createMPToken( return tesSUCCESS; } +TER +checkCreateMPT( + xrpl::ApplyView& view, + xrpl::MPTIssue const& mptIssue, + xrpl::AccountID const& holder, + beast::Journal j) +{ + if (mptIssue.getIssuer() == holder) + return tesSUCCESS; + + auto const mptIssuanceID = keylet::mptIssuance(mptIssue.getMptID()); + auto const mptokenID = keylet::mptoken(mptIssuanceID.key, holder); + if (!view.exists(mptokenID)) + { + if (auto const err = createMPToken(view, mptIssue.getMptID(), holder, 0); + !isTesSuccess(err)) + { + return err; + } + auto const sleAcct = view.peek(keylet::account(holder)); + if (!sleAcct) + { + return tecINTERNAL; + } + adjustOwnerCount(view, sleAcct, 1, j); + } + return tesSUCCESS; +} + +std::int64_t +maxMPTAmount(SLE const& sleIssuance) +{ + return sleIssuance[~sfMaximumAmount].value_or(maxMPTokenAmount); +} + +std::int64_t +availableMPTAmount(SLE const& sleIssuance) +{ + auto const max = maxMPTAmount(sleIssuance); + auto const outstanding = sleIssuance[sfOutstandingAmount]; + return max - outstanding; +} + +std::int64_t +availableMPTAmount(ReadView const& view, MPTID const& mptID) +{ + auto const sle = view.read(keylet::mptIssuance(mptID)); + if (!sle) + Throw(transHuman(tecINTERNAL)); + return availableMPTAmount(*sle); +} + +bool +isMPTOverflow( + std::int64_t sendAmount, + std::uint64_t outstandingAmount, + std::int64_t maximumAmount, + AllowMPTOverflow allowOverflow) +{ + std::uint64_t const limit = (allowOverflow == AllowMPTOverflow::Yes) + ? std::numeric_limits::max() + : maximumAmount; + return (sendAmount > maximumAmount || outstandingAmount > (limit - sendAmount)); +} + +STAmount +issuerFundsToSelfIssue(ReadView const& view, MPTIssue const& issue) +{ + STAmount amount{issue}; + + auto const sle = view.read(keylet::mptIssuance(issue)); + if (!sle) + return amount; + auto const available = availableMPTAmount(*sle); + return view.balanceHookSelfIssueMPT(issue, available); +} + +void +issuerSelfDebitHookMPT(ApplyView& view, MPTIssue const& issue, std::uint64_t amount) +{ + auto const available = availableMPTAmount(view, issue); + view.issuerSelfDebitHookMPT(issue, amount, available); +} + +static TER +checkMPTAllowed(ReadView const& view, TxType txType, Asset const& asset, AccountID const& accountID) +{ + if (!asset.holds()) + return tesSUCCESS; + + auto const& issuanceID = asset.get().getMptID(); + auto const validTx = txType == ttAMM_CREATE || txType == ttAMM_DEPOSIT || + txType == ttAMM_WITHDRAW || txType == ttOFFER_CREATE || txType == ttCHECK_CREATE || + txType == ttCHECK_CASH || txType == ttPAYMENT; + XRPL_ASSERT(validTx, "xrpl::checkMPTAllowed : all MPT tx or DEX"); + if (!validTx) + return tefINTERNAL; // LCOV_EXCL_LINE + + auto const& issuer = asset.getIssuer(); + if (!view.exists(keylet::account(issuer))) + return tecNO_ISSUER; // LCOV_EXCL_LINE + + auto const issuanceKey = keylet::mptIssuance(issuanceID); + auto const issuanceSle = view.read(issuanceKey); + if (!issuanceSle) + return tecOBJECT_NOT_FOUND; // LCOV_EXCL_LINE + + auto const flags = issuanceSle->getFlags(); + + if ((flags & lsfMPTLocked) != 0u) + return tecLOCKED; // LCOV_EXCL_LINE + // Offer crossing and Payment + if ((flags & lsfMPTCanTrade) == 0) + return tecNO_PERMISSION; + + if (accountID != issuer) + { + if ((flags & lsfMPTCanTransfer) == 0) + return tecNO_PERMISSION; + + auto const mptSle = view.read(keylet::mptoken(issuanceKey.key, accountID)); + // Allow to succeed since some tx create MPToken if it doesn't exist. + // Tx's have their own check for missing MPToken. + if (!mptSle) + return tesSUCCESS; + + if (mptSle->isFlag(lsfMPTLocked)) + return tecLOCKED; + } + + return tesSUCCESS; +} + +TER +checkMPTTxAllowed( + ReadView const& view, + TxType txType, + Asset const& asset, + AccountID const& accountID) +{ + // use isDEXAllowed for payment/offer crossing + XRPL_ASSERT(txType != ttPAYMENT, "xrpl::checkMPTTxAllowed : not payment"); + return checkMPTAllowed(view, txType, asset, accountID); +} + } // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp b/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp index d6921b5c88..4652bccca8 100644 --- a/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/NFTokenHelpers.cpp @@ -855,15 +855,15 @@ tokenOfferCreatePreclaim( if (view.rules().enabled(featureNFTokenMintOffer)) { if (nftIssuer != amount.getIssuer() && - !view.read(keylet::line(nftIssuer, amount.issue()))) + !view.read(keylet::line(nftIssuer, amount.get()))) return tecNO_LINE; } - else if (!view.exists(keylet::line(nftIssuer, amount.issue()))) + else if (!view.exists(keylet::line(nftIssuer, amount.get()))) { return tecNO_LINE; } - if (isFrozen(view, nftIssuer, amount.getCurrency(), amount.getIssuer())) + if (isFrozen(view, nftIssuer, amount.get().currency, amount.getIssuer())) return tecFROZEN; } @@ -876,7 +876,7 @@ tokenOfferCreatePreclaim( return tefNFTOKEN_IS_NOT_TRANSFERABLE; } - if (isFrozen(view, acctID, amount.getCurrency(), amount.getIssuer())) + if (isFrozen(view, acctID, amount.get().currency, amount.getIssuer())) return tecFROZEN; // If this is an offer to buy the token, the account must have the diff --git a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp index 697b8fc293..2c676f14af 100644 --- a/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp +++ b/src/libxrpl/ledger/helpers/RippleStateHelpers.cpp @@ -33,11 +33,14 @@ creditLimit( if (sleRippleState) { result = sleRippleState->getFieldAmount(account < issuer ? sfLowLimit : sfHighLimit); - result.setIssuer(account); + result.get().account = account; } XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditLimit : result issuer match"); - XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditLimit : result currency match"); + XRPL_ASSERT( + result.get().currency == currency, + "xrpl::creditLimit : result currency " + "match"); return result; } @@ -63,11 +66,14 @@ creditBalance( result = sleRippleState->getFieldAmount(sfBalance); if (account < issuer) result.negate(); - result.setIssuer(account); + result.get().account = account; } XRPL_ASSERT(result.getIssuer() == account, "xrpl::creditBalance : result issuer match"); - XRPL_ASSERT(result.getCurrency() == currency, "xrpl::creditBalance : result currency match"); + XRPL_ASSERT( + result.get().currency == currency, + "xrpl::creditBalance : result currency " + "match"); return result; } @@ -222,7 +228,7 @@ trustCreate( sleRippleState->setFieldAmount(bSetHigh ? sfHighLimit : sfLowLimit, saLimit); sleRippleState->setFieldAmount( bSetHigh ? sfLowLimit : sfHighLimit, - STAmount(Issue{saBalance.getCurrency(), bSetDst ? uSrcAccountID : uDstAccountID})); + STAmount(Issue{saBalance.get().currency, bSetDst ? uSrcAccountID : uDstAccountID})); if (uQualityIn != 0u) sleRippleState->setFieldU32(bSetHigh ? sfHighQualityIn : sfLowQualityIn, uQualityIn); @@ -261,7 +267,7 @@ trustCreate( // ONLY: Create ripple balance. sleRippleState->setFieldAmount(sfBalance, bSetHigh ? -saBalance : saBalance); - view.creditHook(uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); + view.creditHookIOU(uSrcAccountID, uDstAccountID, saBalance, saBalance.zeroed()); return tesSUCCESS; } @@ -367,7 +373,7 @@ issueIOU( "xrpl::issueIOU : neither account nor issuer is XRP"); // Consistency check - XRPL_ASSERT(issue == amount.issue(), "xrpl::issueIOU : matching issue"); + XRPL_ASSERT(issue == amount.get(), "xrpl::issueIOU : matching issue"); // Can't send to self! XRPL_ASSERT(issue.account != account, "xrpl::issueIOU : not issuer account"); @@ -392,7 +398,7 @@ issueIOU( auto const must_delete = updateTrustLine( view, state, bSenderHigh, issue.account, start_balance, final_balance, j); - view.creditHook(issue.account, account, amount, start_balance); + view.creditHookIOU(issue.account, account, amount, start_balance); if (bSenderHigh) final_balance.negate(); @@ -422,7 +428,7 @@ issueIOU( STAmount const limit(Issue{issue.currency, account}); STAmount final_balance = amount; - final_balance.setIssuer(noAccount()); + final_balance.get().account = noAccount(); auto const receiverAccount = view.peek(keylet::account(account)); if (!receiverAccount) @@ -461,7 +467,7 @@ redeemIOU( "xrpl::redeemIOU : neither account nor issuer is XRP"); // Consistency check - XRPL_ASSERT(issue == amount.issue(), "xrpl::redeemIOU : matching issue"); + XRPL_ASSERT(issue == amount.get(), "xrpl::redeemIOU : matching issue"); // Can't send to self! XRPL_ASSERT(issue.account != account, "xrpl::redeemIOU : not issuer account"); @@ -484,7 +490,7 @@ redeemIOU( auto const must_delete = updateTrustLine(view, state, bSenderHigh, account, start_balance, final_balance, j); - view.creditHook(account, issue.account, amount, start_balance); + view.creditHookIOU(account, issue.account, amount, start_balance); if (bSenderHigh) final_balance.negate(); @@ -757,4 +763,20 @@ deleteAMMTrustLine( return tesSUCCESS; } +TER +deleteAMMMPToken( + ApplyView& view, + std::shared_ptr sleMpt, + AccountID const& ammAccountID, + beast::Journal j) +{ + if (!view.dirRemove( + keylet::ownerDir(ammAccountID), (*sleMpt)[sfOwnerNode], sleMpt->key(), false)) + return tefBAD_LEDGER; // LCOV_EXCL_LINE + + view.erase(sleMpt); + + return tesSUCCESS; +} + } // namespace xrpl diff --git a/src/libxrpl/ledger/helpers/TokenHelpers.cpp b/src/libxrpl/ledger/helpers/TokenHelpers.cpp index 332cfd83b2..ec9ccaa7ae 100644 --- a/src/libxrpl/ledger/helpers/TokenHelpers.cpp +++ b/src/libxrpl/ledger/helpers/TokenHelpers.cpp @@ -23,8 +23,8 @@ bool isLPTokenFrozen( ReadView const& view, AccountID const& account, - Issue const& asset, - Issue const& asset2); + Asset const& asset, + Asset const& asset2); //------------------------------------------------------------------------------ // @@ -35,18 +35,9 @@ isLPTokenFrozen( bool isGlobalFrozen(ReadView const& view, Asset const& asset) { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return isGlobalFrozen(view, issue.getIssuer()); - } - else - { - return isGlobalFrozen(view, issue); - } - }, - asset.value()); + return asset.visit( + [&](Issue const& issue) { return isGlobalFrozen(view, issue.getIssuer()); }, + [&](MPTIssue const& issue) { return isGlobalFrozen(view, issue); }); } bool @@ -103,18 +94,9 @@ isAnyFrozen( Asset const& asset, int depth) { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return isAnyFrozen(view, accounts, issue); - } - else - { - return isAnyFrozen(view, accounts, issue, depth); - } - }, - asset.value()); + return asset.visit( + [&](Issue const& issue) { return isAnyFrozen(view, accounts, issue); }, + [&](MPTIssue const& issue) { return isAnyFrozen(view, accounts, issue, depth); }); } bool @@ -190,11 +172,7 @@ getLineIfUsable( auto const sleAmm = view.read(keylet::amm((*sleIssuer)[sfAMMID])); if (!sleAmm || - isLPTokenFrozen( - view, - account, - (*sleAmm)[sfAsset].get(), - (*sleAmm)[sfAsset2].get())) + isLPTokenFrozen(view, account, (*sleAmm)[sfAsset], (*sleAmm)[sfAsset2])) { return nullptr; } @@ -230,7 +208,7 @@ getTrustLineBalance( { amount += sle->getFieldAmount(oppositeField); } - amount.setIssuer(issuer); + amount.get().account = issuer; } else { @@ -240,7 +218,7 @@ getTrustLineBalance( JLOG(j.trace()) << "getTrustLineBalance:" << " account=" << to_string(account) << " amount=" << amount.getFullText(); - return view.balanceHook(account, issuer, amount); + return view.balanceHookIOU(account, issuer, amount); } STAmount @@ -298,6 +276,9 @@ accountHolds( SpendableHandling includeFullBalance) { bool const returnSpendable = (includeFullBalance == shFULL_BALANCE); + STAmount amount{mptIssue}; + auto const& issuer = mptIssue.getIssuer(); + bool const mptokensV2 = view.rules().enabled(featureMPTokensV2); if (returnSpendable && account == mptIssue.getIssuer()) { @@ -307,16 +288,14 @@ accountHolds( if (!issuance) { - return STAmount{mptIssue}; + return amount; } - return STAmount{ - mptIssue, - issuance->at(~sfMaximumAmount).value_or(maxMPTokenAmount) - - issuance->at(sfOutstandingAmount)}; + auto const available = availableMPTAmount(*issuance); + if (!mptokensV2) + return STAmount{mptIssue, available}; + return view.balanceHookMPT(issuer, mptIssue, available); } - STAmount amount; - auto const sleMpt = view.read(keylet::mptoken(mptIssue.getMptID(), account)); if (!sleMpt) @@ -352,6 +331,8 @@ accountHolds( } } + if (view.rules().enabled(featureMPTokensV2)) + return view.balanceHookMPT(account, mptIssue, amount.mpt().value()); return amount; } @@ -365,19 +346,14 @@ accountHolds( beast::Journal j, SpendableHandling includeFullBalance) { - return std::visit( - [&](TIss const& value) { - if constexpr (std::is_same_v) - { - return accountHolds(view, account, value, zeroIfFrozen, j, includeFullBalance); - } - else if constexpr (std::is_same_v) - { - return accountHolds( - view, account, value, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); - } + return asset.visit( + [&](Issue const& issue) { + return accountHolds(view, account, issue, zeroIfFrozen, j, includeFullBalance); }, - asset.value()); + [&](MPTIssue const& issue) { + return accountHolds( + view, account, issue, zeroIfFrozen, zeroIfUnauthorized, j, includeFullBalance); + }); } STAmount @@ -388,28 +364,38 @@ accountFunds( FreezeHandling freezeHandling, beast::Journal j) { + XRPL_ASSERT(saDefault.holds(), "xrpl::accountFunds: saDefault holds Issue"); + if (!saDefault.native() && saDefault.getIssuer() == id) return saDefault; return accountHolds( - view, id, saDefault.getCurrency(), saDefault.getIssuer(), freezeHandling, j); + view, id, saDefault.get().currency, saDefault.getIssuer(), freezeHandling, j); +} + +STAmount +accountFunds( + ReadView const& view, + AccountID const& id, + STAmount const& saDefault, + FreezeHandling freezeHandling, + AuthHandling authHandling, + beast::Journal j) +{ + return saDefault.asset().visit( + [&](Issue const&) { return accountFunds(view, id, saDefault, freezeHandling, j); }, + [&](MPTIssue const&) { + return accountHolds( + view, id, saDefault.asset(), freezeHandling, authHandling, j, shFULL_BALANCE); + }); } Rate transferRate(ReadView const& view, STAmount const& amount) { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return transferRate(view, issue.getIssuer()); - } - else - { - return transferRate(view, issue.getMptID()); - } - }, - amount.asset().value()); + return amount.asset().visit( + [&](Issue const& issue) { return transferRate(view, issue.getIssuer()); }, + [&](MPTIssue const& issue) { return transferRate(view, issue.getMptID()); }); } //------------------------------------------------------------------------------ @@ -522,7 +508,7 @@ directSendNoFeeIOU( beast::Journal j) { AccountID const& issuer = saAmount.getIssuer(); - Currency const& currency = saAmount.getCurrency(); + Currency const& currency = saAmount.get().currency; // Make sure issuer is involved. XRPL_ASSERT( @@ -551,7 +537,7 @@ directSendNoFeeIOU( if (bSenderHigh) saBalance.negate(); // Put balance in sender terms. - view.creditHook(uSenderID, uReceiverID, saAmount, saBalance); + view.creditHookIOU(uSenderID, uReceiverID, saAmount, saBalance); STAmount const saBefore = saBalance; @@ -622,7 +608,7 @@ directSendNoFeeIOU( STAmount const saReceiverLimit(Issue{currency, uReceiverID}); STAmount saBalance{saAmount}; - saBalance.setIssuer(noAccount()); + saBalance.get().account = noAccount(); JLOG(j.debug()) << "directSendNoFeeIOU: " "create line: " @@ -859,7 +845,7 @@ accountSendIOU( else { auto const sndBal = sender->getFieldAmount(sfBalance); - view.creditHook(uSenderID, xrpAccount(), saAmount, sndBal); + view.creditHookIOU(uSenderID, xrpAccount(), saAmount, sndBal); // Decrement XRP balance. sender->setFieldAmount(sfBalance, sndBal - saAmount); @@ -872,7 +858,7 @@ accountSendIOU( // Increment XRP balance. auto const rcvBal = receiver->getFieldAmount(sfBalance); receiver->setFieldAmount(sfBalance, rcvBal + saAmount); - view.creditHook(xrpAccount(), uReceiverID, saAmount, -rcvBal); + view.creditHookIOU(xrpAccount(), uReceiverID, saAmount, -rcvBal); view.update(receiver); } @@ -975,7 +961,7 @@ accountSendMultiIOU( // Increment XRP balance. auto const rcvBal = receiver->getFieldAmount(sfBalance); receiver->setFieldAmount(sfBalance, rcvBal + amount); - view.creditHook(xrpAccount(), receiverID, amount, -rcvBal); + view.creditHookIOU(xrpAccount(), receiverID, amount, -rcvBal); view.update(receiver); @@ -1003,7 +989,7 @@ accountSendMultiIOU( return TER{tecFAILED_PROCESSING}; } auto const sndBal = sender->getFieldAmount(sfBalance); - view.creditHook(senderID, xrpAccount(), takeFromSender, sndBal); + view.creditHookIOU(senderID, xrpAccount(), takeFromSender, sndBal); // Decrement XRP balance. sender->setFieldAmount(sfBalance, sndBal - takeFromSender); @@ -1037,9 +1023,20 @@ directSendNoFeeMPT( auto sleIssuance = view.peek(mptID); if (!sleIssuance) return tecOBJECT_NOT_FOUND; + + auto const maxAmount = maxMPTAmount(*sleIssuance); + auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); + auto const available = availableMPTAmount(*sleIssuance); + auto const amt = saAmount.mpt().value(); + if (uSenderID == issuer) { - (*sleIssuance)[sfOutstandingAmount] += saAmount.mpt().value(); + if (view.rules().enabled(featureMPTokensV2)) + { + if (isMPTOverflow(amt, outstanding, maxAmount, AllowMPTOverflow::Yes)) + return tecPATH_DRY; + } + (*sleIssuance)[sfOutstandingAmount] += amt; view.update(sleIssuance); } else @@ -1047,11 +1044,11 @@ directSendNoFeeMPT( auto const mptokenID = keylet::mptoken(mptID.key, uSenderID); if (auto sle = view.peek(mptokenID)) { - auto const amt = sle->getFieldU64(sfMPTAmount); - auto const pay = saAmount.mpt().value(); - if (amt < pay) + auto const senderBalance = sle->getFieldU64(sfMPTAmount); + if (senderBalance < amt) return tecINSUFFICIENT_FUNDS; - (*sle)[sfMPTAmount] = amt - pay; + view.creditHookMPT(uSenderID, uReceiverID, saAmount, (*sle)[sfMPTAmount], available); + (*sle)[sfMPTAmount] = senderBalance - amt; view.update(sle); } else @@ -1062,11 +1059,9 @@ directSendNoFeeMPT( if (uReceiverID == issuer) { - auto const outstanding = sleIssuance->getFieldU64(sfOutstandingAmount); - auto const redeem = saAmount.mpt().value(); - if (outstanding >= redeem) + if (outstanding >= amt) { - sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - redeem); + sleIssuance->setFieldU64(sfOutstandingAmount, outstanding - amt); view.update(sleIssuance); } else @@ -1079,7 +1074,8 @@ directSendNoFeeMPT( auto const mptokenID = keylet::mptoken(mptID.key, uReceiverID); if (auto sle = view.peek(mptokenID)) { - (*sle)[sfMPTAmount] += saAmount.mpt().value(); + view.creditHookMPT(uSenderID, uReceiverID, saAmount, (*sle)[sfMPTAmount], available); + (*sle)[sfMPTAmount] += amt; view.update(sle); } else @@ -1099,7 +1095,8 @@ directSendNoLimitMPT( STAmount const& saAmount, STAmount& saActual, beast::Journal j, - WaiveTransferFee waiveFee) + WaiveTransferFee waiveFee, + AllowMPTOverflow allowOverflow) { XRPL_ASSERT(uSenderID != uReceiverID, "xrpl::directSendNoLimitMPT : sender is not receiver"); @@ -1117,9 +1114,13 @@ directSendNoLimitMPT( if (uSenderID == issuer) { auto const sendAmount = saAmount.mpt().value(); - auto const maximumAmount = sle->at(~sfMaximumAmount).value_or(maxMPTokenAmount); - if (sendAmount > maximumAmount || - sle->getFieldU64(sfOutstandingAmount) > maximumAmount - sendAmount) + auto const maxAmount = maxMPTAmount(*sle); + auto const outstanding = sle->getFieldU64(sfOutstandingAmount); + auto const mptokensV2 = view.rules().enabled(featureMPTokensV2); + allowOverflow = (allowOverflow == AllowMPTOverflow::Yes && mptokensV2) + ? AllowMPTOverflow::Yes + : AllowMPTOverflow::No; + if (isMPTOverflow(sendAmount, outstanding, maxAmount, allowOverflow)) return tecPATH_DRY; } @@ -1233,7 +1234,8 @@ directSendNoLimitMultiMPT( } // Direct send: redeeming MPTs and/or sending own MPTs. - if (auto const ter = directSendNoFeeMPT(view, senderID, receiverID, amount, j)) + if (auto const ter = directSendNoFeeMPT(view, senderID, receiverID, amount, j); + !isTesSuccess(ter)) return ter; actual += amount; // Do not add amount to takeFromSender, because directSendNoFeeMPT took it. @@ -1252,13 +1254,15 @@ directSendNoLimitMultiMPT( << to_string(receiverID) << " : deliver=" << amount.getFullText() << " cost=" << actualSend.getFullText(); - if (auto const terResult = directSendNoFeeMPT(view, issuer, receiverID, amount, j)) - return terResult; + if (auto const ter = directSendNoFeeMPT(view, issuer, receiverID, amount, j); + !isTesSuccess(ter)) + return ter; } if (senderID != issuer && takeFromSender) { - if (TER const terResult = directSendNoFeeMPT(view, senderID, issuer, takeFromSender, j)) - return terResult; + if (auto const ter = directSendNoFeeMPT(view, senderID, issuer, takeFromSender, j); + !isTesSuccess(ter)) + return ter; } return tesSUCCESS; @@ -1271,7 +1275,8 @@ accountSendMPT( AccountID const& uReceiverID, STAmount const& saAmount, beast::Journal j, - WaiveTransferFee waiveFee) + WaiveTransferFee waiveFee, + AllowMPTOverflow allowOverflow) { XRPL_ASSERT( saAmount >= beast::zero && saAmount.holds(), @@ -1285,7 +1290,8 @@ accountSendMPT( STAmount saActual{saAmount.asset()}; - return directSendNoLimitMPT(view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee); + return directSendNoLimitMPT( + view, uSenderID, uReceiverID, saAmount, saActual, j, waiveFee, allowOverflow); } static TER @@ -1317,19 +1323,14 @@ directSendNoFee( bool bCheckIssuer, beast::Journal j) { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return directSendNoFeeIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); - } - else - { - XRPL_ASSERT(!bCheckIssuer, "xrpl::directSendNoFee : not checking issuer"); - return directSendNoFeeMPT(view, uSenderID, uReceiverID, saAmount, j); - } + return saAmount.asset().visit( + [&](Issue const&) { + return directSendNoFeeIOU(view, uSenderID, uReceiverID, saAmount, bCheckIssuer, j); }, - saAmount.asset().value()); + [&](MPTIssue const&) { + XRPL_ASSERT(!bCheckIssuer, "xrpl::directSendNoFee : not checking issuer"); + return directSendNoFeeMPT(view, uSenderID, uReceiverID, saAmount, j); + }); } TER @@ -1339,20 +1340,17 @@ accountSend( AccountID const& uReceiverID, STAmount const& saAmount, beast::Journal j, - WaiveTransferFee waiveFee) + WaiveTransferFee waiveFee, + AllowMPTOverflow allowOverflow) { - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee); - } - else - { - return accountSendMPT(view, uSenderID, uReceiverID, saAmount, j, waiveFee); - } + return saAmount.asset().visit( + [&](Issue const&) { + return accountSendIOU(view, uSenderID, uReceiverID, saAmount, j, waiveFee); }, - saAmount.asset().value()); + [&](MPTIssue const&) { + return accountSendMPT( + view, uSenderID, uReceiverID, saAmount, j, waiveFee, allowOverflow); + }); } TER @@ -1366,18 +1364,13 @@ accountSendMulti( { XRPL_ASSERT_PARTS( receivers.size() > 1, "xrpl::accountSendMulti", "multiple recipients provided"); - return std::visit( - [&](TIss const& issue) { - if constexpr (std::is_same_v) - { - return accountSendMultiIOU(view, senderID, issue, receivers, j, waiveFee); - } - else - { - return accountSendMultiMPT(view, senderID, issue, receivers, j, waiveFee); - } + return asset.visit( + [&](Issue const& issue) { + return accountSendMultiIOU(view, senderID, issue, receivers, j, waiveFee); }, - asset.value()); + [&](MPTIssue const& issue) { + return accountSendMultiMPT(view, senderID, issue, receivers, j, waiveFee); + }); } TER diff --git a/src/libxrpl/protocol/AMMCore.cpp b/src/libxrpl/protocol/AMMCore.cpp index 9061d04689..e7a5daf6c1 100644 --- a/src/libxrpl/protocol/AMMCore.cpp +++ b/src/libxrpl/protocol/AMMCore.cpp @@ -21,12 +21,23 @@ namespace xrpl { Currency -ammLPTCurrency(Currency const& cur1, Currency const& cur2) +ammLPTCurrency(Asset const& asset1, Asset const& asset2) { // AMM LPToken is 0x03 plus 19 bytes of the hash std::int32_t constexpr AMMCurrencyCode = 0x03; - auto const [minC, maxC] = std::minmax(cur1, cur2); - auto const hash = sha512Half(minC, maxC); + auto const& [minA, maxA] = std::minmax(asset1, asset2); + uint256 const hash = std::visit( + [](auto&& issue1, auto&& issue2) { + auto fromIss = [](T const& issue) { + if constexpr (std::is_same_v) + return issue.currency; + if constexpr (std::is_same_v) + return issue.getMptID(); + }; + return sha512Half(fromIss(issue1), fromIss(issue2)); + }, + minA.value(), + maxA.value()); Currency currency; *currency.begin() = AMMCurrencyCode; std::copy(hash.begin(), hash.begin() + currency.size() - 1, currency.begin() + 1); @@ -34,34 +45,45 @@ ammLPTCurrency(Currency const& cur1, Currency const& cur2) } Issue -ammLPTIssue(Currency const& cur1, Currency const& cur2, AccountID const& ammAccountID) +ammLPTIssue(Asset const& asset1, Asset const& asset2, AccountID const& ammAccountID) { - return Issue(ammLPTCurrency(cur1, cur2), ammAccountID); + return Issue(ammLPTCurrency(asset1, asset2), ammAccountID); } NotTEC -invalidAMMAsset(Issue const& issue, std::optional> const& pair) +invalidAMMAsset(Asset const& asset, std::optional> const& pair) { - if (badCurrency() == issue.currency) - return temBAD_CURRENCY; - if (isXRP(issue) && issue.account.isNonZero()) - return temBAD_ISSUER; - if (pair && issue != pair->first && issue != pair->second) + auto const err = asset.visit( + [](MPTIssue const& issue) -> std::optional { + if (issue.getIssuer() == beast::zero) + return temBAD_MPT; + return std::nullopt; + }, + [](Issue const& issue) -> std::optional { + if (badCurrency() == issue.currency) + return temBAD_CURRENCY; + if (isXRP(issue) && issue.getIssuer().isNonZero()) + return temBAD_ISSUER; + return std::nullopt; + }); + if (err) + return *err; + if (pair && asset != pair->first && asset != pair->second) return temBAD_AMM_TOKENS; return tesSUCCESS; } NotTEC invalidAMMAssetPair( - Issue const& issue1, - Issue const& issue2, - std::optional> const& pair) + Asset const& asset1, + Asset const& asset2, + std::optional> const& pair) { - if (issue1 == issue2) + if (asset1 == asset2) return temBAD_AMM_TOKENS; - if (auto const res = invalidAMMAsset(issue1, pair)) + if (auto const res = invalidAMMAsset(asset1, pair)) return res; - if (auto const res = invalidAMMAsset(issue2, pair)) + if (auto const res = invalidAMMAsset(asset2, pair)) return res; return tesSUCCESS; } @@ -69,10 +91,10 @@ invalidAMMAssetPair( NotTEC invalidAMMAmount( STAmount const& amount, - std::optional> const& pair, + std::optional> const& pair, bool validZero) { - if (auto const res = invalidAMMAsset(amount.issue(), pair)) + if (auto const res = invalidAMMAsset(amount.asset(), pair)) return res; if (amount < beast::zero || (!validZero && amount == beast::zero)) return temBAD_AMOUNT; diff --git a/src/libxrpl/protocol/Asset.cpp b/src/libxrpl/protocol/Asset.cpp index 0076da6570..a01ff2bbda 100644 --- a/src/libxrpl/protocol/Asset.cpp +++ b/src/libxrpl/protocol/Asset.cpp @@ -62,4 +62,11 @@ assetFromJson(Json::Value const& v) return mptIssueFromJson(v); } +std::ostream& +operator<<(std::ostream& os, Asset const& x) +{ + std::visit([&](TIss const& issue) { os << issue; }, x.value()); + return os; +} + } // namespace xrpl diff --git a/src/libxrpl/protocol/Indexes.cpp b/src/libxrpl/protocol/Indexes.cpp index 61a64b2a54..7c771423a8 100644 --- a/src/libxrpl/protocol/Indexes.cpp +++ b/src/libxrpl/protocol/Indexes.cpp @@ -99,19 +99,36 @@ getBookBase(Book const& book) { XRPL_ASSERT(isConsistent(book), "xrpl::getBookBase : input is consistent"); - auto const index = book.domain ? indexHash( - LedgerNameSpace::BOOK_DIR, - book.in.currency, - book.out.currency, - book.in.account, - book.out.account, - *(book.domain)) - : indexHash( - LedgerNameSpace::BOOK_DIR, - book.in.currency, - book.out.currency, - book.in.account, - book.out.account); + auto getIndexHash = [&book](Args... args) { + if (book.domain) + return indexHash(std::forward(args)..., *book.domain); + return indexHash(std::forward(args)...); + }; + + auto const index = std::visit( + [&](TIn const& in, TOut const& out) { + if constexpr (std::is_same_v && std::is_same_v) + { + return getIndexHash( + LedgerNameSpace::BOOK_DIR, in.currency, out.currency, in.account, out.account); + } + else if constexpr (std::is_same_v && std::is_same_v) + { + return getIndexHash( + LedgerNameSpace::BOOK_DIR, in.currency, out.getMptID(), in.account); + } + else if constexpr (std::is_same_v && std::is_same_v) + { + return getIndexHash( + LedgerNameSpace::BOOK_DIR, in.getMptID(), out.currency, out.account); + } + else + { + return getIndexHash(LedgerNameSpace::BOOK_DIR, in.getMptID(), out.getMptID()); + } + }, + book.in.value(), + book.out.value()); // Return with quality 0. auto k = keylet::quality({ltDIR_NODE, index}, 0); @@ -401,11 +418,37 @@ nft_sells(uint256 const& id) noexcept } Keylet -amm(Asset const& issue1, Asset const& issue2) noexcept +amm(Asset const& asset1, Asset const& asset2) noexcept { - auto const& [minI, maxI] = std::minmax(issue1.get(), issue2.get()); - return amm( - indexHash(LedgerNameSpace::AMM, minI.account, minI.currency, maxI.account, maxI.currency)); + auto const& [minA, maxA] = std::minmax(asset1, asset2); + return std::visit( + [](TIss1 const& issue1, TIss2 const& issue2) { + if constexpr (std::is_same_v && std::is_same_v) + { + return amm(indexHash( + LedgerNameSpace::AMM, + issue1.account, + issue1.currency, + issue2.account, + issue2.currency)); + } + else if constexpr (std::is_same_v && std::is_same_v) + { + return amm(indexHash( + LedgerNameSpace::AMM, issue1.account, issue1.currency, issue2.getMptID())); + } + else if constexpr (std::is_same_v && std::is_same_v) + { + return amm(indexHash( + LedgerNameSpace::AMM, issue1.getMptID(), issue2.account, issue2.currency)); + } + else if constexpr (std::is_same_v && std::is_same_v) + { + return amm(indexHash(LedgerNameSpace::AMM, issue1.getMptID(), issue2.getMptID())); + } + }, + minA.value(), + maxA.value()); } Keylet diff --git a/src/libxrpl/protocol/MPTIssue.cpp b/src/libxrpl/protocol/MPTIssue.cpp index c2f7f1fa50..70fb9dc8e7 100644 --- a/src/libxrpl/protocol/MPTIssue.cpp +++ b/src/libxrpl/protocol/MPTIssue.cpp @@ -2,9 +2,8 @@ #include #include #include -#include +#include #include -#include #include #include @@ -17,6 +16,11 @@ MPTIssue::MPTIssue(MPTID const& issuanceID) : mptID_(issuanceID) { } +MPTIssue::MPTIssue(std::uint32_t sequence, AccountID const& account) + : MPTIssue(xrpl::makeMptID(sequence, account)) +{ +} + AccountID const& MPTIssue::getIssuer() const { @@ -86,4 +90,11 @@ mptIssueFromJson(Json::Value const& v) return MPTIssue{id}; } +std::ostream& +operator<<(std::ostream& os, MPTIssue const& x) +{ + os << to_string(x); + return os; +} + } // namespace xrpl diff --git a/src/libxrpl/protocol/PathAsset.cpp b/src/libxrpl/protocol/PathAsset.cpp new file mode 100644 index 0000000000..063b1fdd33 --- /dev/null +++ b/src/libxrpl/protocol/PathAsset.cpp @@ -0,0 +1,19 @@ +#include +#include + +namespace xrpl { + +std::string +to_string(PathAsset const& asset) +{ + return std::visit([&](auto const& issue) { return to_string(issue); }, asset.value()); +} + +std::ostream& +operator<<(std::ostream& os, PathAsset const& x) +{ + os << to_string(x); + return os; +} + +} // namespace xrpl diff --git a/src/libxrpl/protocol/STAmount.cpp b/src/libxrpl/protocol/STAmount.cpp index cc935cff61..6fe5eed498 100644 --- a/src/libxrpl/protocol/STAmount.cpp +++ b/src/libxrpl/protocol/STAmount.cpp @@ -90,11 +90,23 @@ getMPTValue(STAmount const& amount) static bool areComparable(STAmount const& v1, STAmount const& v2) { - if (v1.holds() && v2.holds()) - return v1.native() == v2.native() && v1.get().currency == v2.get().currency; - if (v1.holds() && v2.holds()) - return v1.get() == v2.get(); - return false; + return std::visit( + [&](TIss1 const& issue1, TIss2 const& issue2) { + if constexpr (is_issue_v && is_issue_v) + { + return v1.native() == v2.native() && issue1.currency == issue2.currency; + } + else if constexpr (is_mptissue_v && is_mptissue_v) + { + return issue1 == issue2; + } + else + { + return false; + } + }, + v1.asset().value(), + v2.asset().value()); } static_assert(INITIAL_XRP.drops() == STAmount::cMaxNativeN); @@ -513,26 +525,35 @@ canAdd(STAmount const& a, STAmount const& b) } // IOU case (precision check) - if (a.holds() && b.holds()) - { - static STAmount const one{IOUAmount{1, 0}, noIssue()}; - static STAmount const maxLoss{IOUAmount{1, -4}, noIssue()}; - STAmount const lhs = divide((a - b) + b, a, noIssue()) - one; - STAmount const rhs = divide((b - a) + a, b, noIssue()) - one; - return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= maxLoss; - } + auto const ret = std::visit( + [&]( + TIss1 const&, TIss2 const&) -> std::optional { + if constexpr (is_issue_v && is_issue_v) + { + static STAmount const one{IOUAmount{1, 0}, noIssue()}; + static STAmount const maxLoss{IOUAmount{1, -4}, noIssue()}; + STAmount const lhs = divide((a - b) + b, a, noIssue()) - one; + STAmount const rhs = divide((b - a) + a, b, noIssue()) - one; + return ((rhs.negative() ? -rhs : rhs) + (lhs.negative() ? -lhs : lhs)) <= maxLoss; + } - // MPT (overflow & underflow check) - if (a.holds() && b.holds()) - { - MPTAmount const A = a.mpt(); - MPTAmount const B = b.mpt(); - return !( - (B > MPTAmount{0} && - A > MPTAmount{std::numeric_limits::max()} - B) || - (B < MPTAmount{0} && - A < MPTAmount{std::numeric_limits::min()} - B)); - } + // MPT (overflow & underflow check) + if constexpr (is_mptissue_v && is_mptissue_v) + { + MPTAmount const A = a.mpt(); + MPTAmount const B = b.mpt(); + return !( + (B > MPTAmount{0} && + A > MPTAmount{std::numeric_limits::max()} - B) || + (B < MPTAmount{0} && + A < MPTAmount{std::numeric_limits::min()} - B)); + } + return std::nullopt; + }, + a.asset().value(), + b.asset().value()); + if (ret) + return *ret; // LCOV_EXCL_START UNREACHABLE("STAmount::canAdd : unexpected STAmount type"); return false; @@ -585,27 +606,36 @@ canSubtract(STAmount const& a, STAmount const& b) } // IOU case (no underflow) - if (a.holds() && b.holds()) - { - return true; - } + auto const ret = std::visit( + [&]( + TIss1 const&, TIss2 const&) -> std::optional { + if constexpr (is_issue_v && is_issue_v) + { + return true; + } - // MPT case (underflow & overflow check) - if (a.holds() && b.holds()) - { - MPTAmount const A = a.mpt(); - MPTAmount const B = b.mpt(); + // MPT case (underflow & overflow check) + if constexpr (is_mptissue_v && is_mptissue_v) + { + MPTAmount const A = a.mpt(); + MPTAmount const B = b.mpt(); - // Underflow check - if (B > MPTAmount{0} && A < B) - return false; + // Underflow check + if (B > MPTAmount{0} && A < B) + return false; - // Overflow check - if (B < MPTAmount{0} && - A > MPTAmount{std::numeric_limits::max()} + B) - return false; - return true; - } + // Overflow check + if (B < MPTAmount{0} && + A > MPTAmount{std::numeric_limits::max()} + B) + return false; + return true; + } + return std::nullopt; + }, + a.asset().value(), + b.asset().value()); + if (ret) + return *ret; // LCOV_EXCL_START UNREACHABLE("STAmount::canSubtract : unexpected STAmount type"); return false; @@ -751,45 +781,49 @@ STAmount::getJson(JsonOptions) const void STAmount::add(Serializer& s) const { - if (native()) - { - XRPL_ASSERT(mOffset == 0, "xrpl::STAmount::add : zero offset"); - - if (!mIsNegative) - { - s.add64(mValue | cPositive); - } - else - { + mAsset.visit( + [&](MPTIssue const& issue) { + auto u8 = static_cast(cMPToken >> 56); + if (!mIsNegative) + u8 |= static_cast(cPositive >> 56); + s.add8(u8); s.add64(mValue); - } - } - else if (mAsset.holds()) - { - auto u8 = static_cast(cMPToken >> 56); - if (!mIsNegative) - u8 |= static_cast(cPositive >> 56); - s.add8(u8); - s.add64(mValue); - s.addBitString(mAsset.get().getMptID()); - } - else - { - if (*this == beast::zero) - { - s.add64(cIssuedCurrency); - } - else if (mIsNegative) - { // 512 = not native - s.add64(mValue | (static_cast(mOffset + 512 + 97) << (64 - 10))); - } - else - { // 256 = positive - s.add64(mValue | (static_cast(mOffset + 512 + 256 + 97) << (64 - 10))); - } - s.addBitString(mAsset.get().currency); - s.addBitString(mAsset.get().account); - } + s.addBitString(issue.getMptID()); + }, + [&](Issue const& issue) { + if (native()) + { + XRPL_ASSERT(mOffset == 0, "xrpl::STAmount::add : zero offset"); + + if (!mIsNegative) + { + s.add64(mValue | cPositive); + } + else + { + s.add64(mValue); + } + } + else + { + if (*this == beast::zero) + { + s.add64(cIssuedCurrency); + } + else if (mIsNegative) // 512 = not native + { + s.add64(mValue | (static_cast(mOffset + 512 + 97) << (64 - 10))); + } + else // 256 = positive + { + s.add64( + mValue | + (static_cast(mOffset + 512 + 256 + 97) << (64 - 10))); + } + s.addBitString(issue.currency); + s.addBitString(issue.account); + } + }); } bool @@ -1065,7 +1099,7 @@ amountFromJson(SField const& name, Json::Value const& v) if (isMPT) { // sequence (32 bits) + account (160 bits) - uint192 u; + MPTID u; if (!u.parseHex(currencyOrMPTID.asString())) Throw("invalid MPTokenIssuanceID"); asset = u; @@ -1255,7 +1289,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) int numOffset = num.exponent(); int denOffset = den.exponent(); - if (num.native() || num.holds()) + if (num.integral()) { while (numVal < STAmount::cMinValue) { @@ -1265,7 +1299,7 @@ divide(STAmount const& num, STAmount const& den, Asset const& asset) } } - if (den.native() || den.holds()) + if (den.integral()) { while (denVal < STAmount::cMinValue) { @@ -1330,7 +1364,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) int offset1 = v1.exponent(); int offset2 = v2.exponent(); - if (v1.native() || v1.holds()) + if (v1.integral()) { while (value1 < STAmount::cMinValue) { @@ -1339,7 +1373,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) } } - if (v2.native() || v2.holds()) + if (v2.integral()) { while (value2 < STAmount::cMinValue) { @@ -1363,7 +1397,7 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) // for years, so it is deeply embedded in the behavior of cross-currency // transactions. // -// However in 2022 it was noticed that the rounding characteristics were +// However, in 2022 it was noticed that the rounding characteristics were // surprising. When the code converts from IOU-like to XRP-like there may // be a fraction of the IOU-like representation that is too small to be // represented in drops. `canonicalizeRound()` currently does some unusual @@ -1380,9 +1414,9 @@ multiply(STAmount const& v1, STAmount const& v2, Asset const& asset) // So an alternative rounding approach was introduced. You'll see that // alternative below. static void -canonicalizeRound(bool native, std::uint64_t& value, int& offset, bool) +canonicalizeRound(bool integral, std::uint64_t& value, int& offset, bool) { - if (native) + if (integral) { if (offset < 0) { @@ -1419,9 +1453,9 @@ canonicalizeRound(bool native, std::uint64_t& value, int& offset, bool) // rounding decisions. canonicalizeRoundStrict() tracks all of the bits in // the value being rounded. static void -canonicalizeRoundStrict(bool native, std::uint64_t& value, int& offset, bool roundUp) +canonicalizeRoundStrict(bool integral, std::uint64_t& value, int& offset, bool roundUp) { - if (native) + if (integral) { if (offset < 0) { @@ -1512,9 +1546,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro if (v1 == beast::zero || v2 == beast::zero) return {asset}; - bool const xrp = asset.native(); - - if (v1.native() && v2.native() && xrp) + if (v1.native() && v2.native() && asset.native()) { std::uint64_t const minV = std::min(getSNValue(v1), getSNValue(v2)); std::uint64_t const maxV = std::max(getSNValue(v1), getSNValue(v2)); @@ -1545,7 +1577,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro std::uint64_t value1 = v1.mantissa(), value2 = v2.mantissa(); int offset1 = v1.exponent(), offset2 = v2.exponent(); - if (v1.native() || v1.holds()) + if (v1.integral()) { while (value1 < STAmount::cMinValue) { @@ -1554,7 +1586,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro } } - if (v2.native() || v2.holds()) + if (v2.integral()) { while (value2 < STAmount::cMinValue) { @@ -1570,7 +1602,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro // range. Dividing their product by 10^14 maintains the // precision, by scaling the result to 10^16 to 10^18. // - // If the we're rounding up, we want to round up away + // If we're rounding up, we want to round up away // from zero, and if we're rounding down, truncation // is implicit. std::uint64_t amount = @@ -1579,7 +1611,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro int offset = offset1 + offset2 + 14; if (resultNegative != roundUp) { - CanonicalizeFunc(xrp, amount, offset, roundUp); + CanonicalizeFunc(asset.integral(), amount, offset, roundUp); } STAmount result = [&]() { // If appropriate, tell Number to round down. This gives the desired @@ -1590,7 +1622,7 @@ mulRoundImpl(STAmount const& v1, STAmount const& v2, Asset const& asset, bool ro if (roundUp && !resultNegative && !result) { - if (xrp) + if (asset.integral()) { // return the smallest value above zero amount = 1; @@ -1634,7 +1666,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool std::uint64_t numVal = num.mantissa(), denVal = den.mantissa(); int numOffset = num.exponent(), denOffset = den.exponent(); - if (num.native() || num.holds()) + if (num.integral()) { while (numVal < STAmount::cMinValue) { @@ -1643,7 +1675,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool } } - if (den.native() || den.holds()) + if (den.integral()) { while (denVal < STAmount::cMinValue) { @@ -1668,12 +1700,12 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool int offset = numOffset - denOffset - 17; if (resultNegative != roundUp) - canonicalizeRound(asset.native() || asset.holds(), amount, offset, roundUp); + canonicalizeRound(asset.integral(), amount, offset, roundUp); STAmount result = [&]() { // If appropriate, tell Number the rounding mode we are using. // Note that "roundUp == true" actually means "round away from zero". - // Otherwise round toward zero. + // Otherwise, round toward zero. using enum Number::rounding_mode; MightSaveRound const savedRound(roundUp ^ resultNegative ? upward : downward); return STAmount(asset, amount, offset, resultNegative); @@ -1681,7 +1713,7 @@ divRoundImpl(STAmount const& num, STAmount const& den, Asset const& asset, bool if (roundUp && !resultNegative && !result) { - if (asset.native() || asset.holds()) + if (asset.integral()) { // return the smallest value above zero amount = 1; diff --git a/src/libxrpl/protocol/STIssue.cpp b/src/libxrpl/protocol/STIssue.cpp index 5acf4abcb6..f73bad4b0d 100644 --- a/src/libxrpl/protocol/STIssue.cpp +++ b/src/libxrpl/protocol/STIssue.cpp @@ -88,22 +88,19 @@ STIssue::getJson(JsonOptions) const void STIssue::add(Serializer& s) const { - if (holds()) - { - auto const& issue = asset_.get(); - s.addBitString(issue.currency); - if (!isXRP(issue.currency)) - s.addBitString(issue.account); - } - else - { - auto const& issue = asset_.get(); - s.addBitString(issue.getIssuer()); - s.addBitString(noAccount()); - std::uint32_t sequence = 0; - memcpy(&sequence, issue.getMptID().data(), sizeof(sequence)); - s.add32(sequence); - } + asset_.visit( + [&](Issue const& issue) { + s.addBitString(issue.currency); + if (!isXRP(issue.currency)) + s.addBitString(issue.account); + }, + [&](MPTIssue const& issue) { + s.addBitString(issue.getIssuer()); + s.addBitString(noAccount()); + std::uint32_t sequence = 0; + memcpy(&sequence, issue.getMptID().data(), sizeof(sequence)); + s.add32(sequence); + }); } bool @@ -116,7 +113,9 @@ STIssue::isEquivalent(STBase const& t) const bool STIssue::isDefault() const { - return holds() && asset_.get() == xrpIssue(); + return asset_.visit( + [](Issue const& issue) { return issue == xrpIssue(); }, + [](MPTIssue const&) { return false; }); } STBase* diff --git a/src/libxrpl/protocol/STObject.cpp b/src/libxrpl/protocol/STObject.cpp index f758760337..be257d2c57 100644 --- a/src/libxrpl/protocol/STObject.cpp +++ b/src/libxrpl/protocol/STObject.cpp @@ -749,6 +749,12 @@ STObject::setFieldH128(SField const& field, uint128 const& v) setFieldUsingSetValue(field, v); } +void +STObject::setFieldH192(SField const& field, uint192 const& v) +{ + setFieldUsingSetValue(field, v); +} + void STObject::setFieldH256(SField const& field, uint256 const& v) { diff --git a/src/libxrpl/protocol/STParsedJSON.cpp b/src/libxrpl/protocol/STParsedJSON.cpp index c928f49375..5eba36b9e1 100644 --- a/src/libxrpl/protocol/STParsedJSON.cpp +++ b/src/libxrpl/protocol/STParsedJSON.cpp @@ -736,7 +736,7 @@ parseLeaf( std::string const element_name(json_name + "." + ss.str()); // each element in this path has some combination of - // account, currency, or issuer + // account, asset, or issuer Json::Value pathEl = value[i][j]; @@ -746,14 +746,22 @@ parseLeaf( return ret; } - Json::Value const& account = pathEl["account"]; - Json::Value const& currency = pathEl["currency"]; - Json::Value const& issuer = pathEl["issuer"]; - bool hasCurrency = false; - AccountID uAccount, uIssuer; - Currency uCurrency; + if (pathEl.isMember(jss::currency) && pathEl.isMember(jss::mpt_issuance_id)) + { + error = RPC::make_error(rpcINVALID_PARAMS, "Invalid Asset."); + return ret; + } - if (!account && !currency && !issuer) + bool const isMPT = pathEl.isMember(jss::mpt_issuance_id); + auto const assetName = isMPT ? jss::mpt_issuance_id : jss::currency; + Json::Value const& account = pathEl[jss::account]; + Json::Value const& asset = pathEl[assetName]; + Json::Value const& issuer = pathEl[jss::issuer]; + bool hasAsset = false; + AccountID uAccount, uIssuer; + PathAsset uAsset; + + if (!account && !asset && !issuer) { error = invalid_data(element_name); return ret; @@ -764,7 +772,7 @@ parseLeaf( // human account id if (!account.isString()) { - error = string_expected(element_name, "account"); + error = string_expected(element_name, jss::account.c_str()); return ret; } @@ -775,31 +783,51 @@ parseLeaf( auto const a = parseBase58(account.asString()); if (!a) { - error = invalid_data(element_name, "account"); + error = invalid_data(element_name, jss::account.c_str()); return ret; } uAccount = *a; } } - if (currency) + if (asset) { - // human currency - if (!currency.isString()) + // human asset + if (!asset.isString()) { - error = string_expected(element_name, "currency"); + error = string_expected(element_name, assetName.c_str()); return ret; } - hasCurrency = true; + hasAsset = true; - if (!uCurrency.parseHex(currency.asString())) + if (isMPT) { - if (!to_currency(uCurrency, currency.asString())) + MPTID u; + if (!u.parseHex(asset.asString())) { - error = invalid_data(element_name, "currency"); + error = invalid_data(element_name, assetName.c_str()); return ret; } + if (getMPTIssuer(u) == beast::zero) + { + error = invalid_data(element_name, jss::account.c_str()); + return ret; + } + uAsset = u; + } + else + { + Currency currency; + if (!currency.parseHex(asset.asString())) + { + if (!to_currency(currency, asset.asString())) + { + error = invalid_data(element_name, assetName.c_str()); + return ret; + } + } + uAsset = currency; } } @@ -808,7 +836,7 @@ parseLeaf( // human account id if (!issuer.isString()) { - error = string_expected(element_name, "issuer"); + error = string_expected(element_name, jss::issuer.c_str()); return ret; } @@ -817,14 +845,20 @@ parseLeaf( auto const a = parseBase58(issuer.asString()); if (!a) { - error = invalid_data(element_name, "issuer"); + error = invalid_data(element_name, jss::issuer.c_str()); return ret; } uIssuer = *a; } + + if (isMPT && uIssuer != getMPTIssuer(uAsset.get())) + { + error = invalid_data(element_name, jss::issuer.c_str()); + return ret; + } } - p.emplace_back(uAccount, uCurrency, uIssuer, hasCurrency); + p.emplace_back(uAccount, uAsset, uIssuer, hasAsset); } tail.push_back(p); diff --git a/src/libxrpl/protocol/STPathSet.cpp b/src/libxrpl/protocol/STPathSet.cpp index 2536c18e4e..39c1d8b29e 100644 --- a/src/libxrpl/protocol/STPathSet.cpp +++ b/src/libxrpl/protocol/STPathSet.cpp @@ -31,8 +31,15 @@ STPathElement::get_hash(STPathElement const& element) for (auto const x : element.getAccountID()) hash_account += (hash_account * 257) ^ x; - for (auto const x : element.getCurrency()) - hash_currency += (hash_currency * 509) ^ x; + // Check pathAsset type instead of element's mType + // In some cases mType might be account but the asset + // is still set to either MPT or currency (see Pathfinder::addLink()) + element.getPathAsset().visit( + [&](MPTID const& mpt) { hash_currency += beast::uhash<>{}(mpt); }, + [&](Currency const& currency) { + for (auto const x : currency) + hash_currency += (hash_currency * 509) ^ x; + }); for (auto const x : element.getIssuerID()) hash_issuer += (hash_issuer * 911) ^ x; @@ -68,24 +75,30 @@ STPathSet::STPathSet(SerialIter& sit, SField const& name) : STBase(name) } else { - auto hasAccount = iType & STPathElement::typeAccount; - auto hasCurrency = iType & STPathElement::typeCurrency; - auto hasIssuer = iType & STPathElement::typeIssuer; + auto const hasAccount = (iType & STPathElement::typeAccount) != 0u; + auto const hasCurrency = (iType & STPathElement::typeCurrency) != 0u; + auto const hasIssuer = (iType & STPathElement::typeIssuer) != 0u; + auto const hasMPT = (iType & STPathElement::typeMPT) != 0u; AccountID account; - Currency currency; + PathAsset asset; AccountID issuer; - if (hasAccount != 0) + if (hasAccount) account = sit.get160(); - if (hasCurrency != 0) - currency = sit.get160(); + XRPL_ASSERT( + !(hasCurrency && hasMPT), "xrpl::STPathSet::STPathSet : not has Currency and MPT"); + if (hasCurrency) + asset = static_cast(sit.get160()); - if (hasIssuer != 0) + if (hasMPT) + asset = sit.get192(); + + if (hasIssuer) issuer = sit.get160(); - path.emplace_back(account, currency, issuer, hasCurrency); + path.emplace_back(account, asset, issuer, hasCurrency); } } } @@ -137,11 +150,11 @@ STPathSet::isDefault() const } bool -STPath::hasSeen(AccountID const& account, Currency const& currency, AccountID const& issuer) const +STPath::hasSeen(AccountID const& account, PathAsset const& asset, AccountID const& issuer) const { for (auto& p : mPath) { - if (p.getAccountID() == account && p.getCurrency() == currency && p.getIssuerID() == issuer) + if (p.getAccountID() == account && p.getPathAsset() == asset && p.getIssuerID() == issuer) return true; } @@ -163,9 +176,16 @@ STPath::getJson(JsonOptions) const if ((iType & STPathElement::typeAccount) != 0u) elem[jss::account] = to_string(it.getAccountID()); + XRPL_ASSERT( + ((iType & STPathElement::typeCurrency) == 0u) || + ((iType & STPathElement::typeMPT) == 0u), + "xrpl::STPath::getJson : not type Currency and MPT"); if ((iType & STPathElement::typeCurrency) != 0u) elem[jss::currency] = to_string(it.getCurrency()); + if ((iType & STPathElement::typeMPT) != 0u) + elem[jss::mpt_issuance_id] = to_string(it.getMPTID()); + if ((iType & STPathElement::typeIssuer) != 0u) elem[jss::issuer] = to_string(it.getIssuerID()); @@ -209,13 +229,16 @@ STPathSet::add(Serializer& s) const s.add8(iType); - if ((iType & STPathElement::typeAccount) != 0) + if ((iType & STPathElement::typeAccount) != 0u) s.addBitString(speElement.getAccountID()); - if ((iType & STPathElement::typeCurrency) != 0) + if ((iType & STPathElement::typeMPT) != 0u) + s.addBitString(speElement.getMPTID()); + + if ((iType & STPathElement::typeCurrency) != 0u) s.addBitString(speElement.getCurrency()); - if ((iType & STPathElement::typeIssuer) != 0) + if ((iType & STPathElement::typeIssuer) != 0u) s.addBitString(speElement.getIssuerID()); } diff --git a/src/libxrpl/protocol/TER.cpp b/src/libxrpl/protocol/TER.cpp index 5d732a5876..30e7662f56 100644 --- a/src/libxrpl/protocol/TER.cpp +++ b/src/libxrpl/protocol/TER.cpp @@ -156,6 +156,7 @@ transResults() MAKE_ERROR(temBAD_FEE, "Invalid fee, negative or not XRP."), MAKE_ERROR(temBAD_ISSUER, "Malformed: Bad issuer."), MAKE_ERROR(temBAD_LIMIT, "Limits must be non-negative."), + MAKE_ERROR(temBAD_MPT, "Malformed: Bad MPT."), MAKE_ERROR(temBAD_OFFER, "Malformed: Bad offer."), MAKE_ERROR(temBAD_PATH, "Malformed: Bad path."), MAKE_ERROR(temBAD_PATH_LOOP, "Malformed: Loop in path."), diff --git a/src/libxrpl/tx/Transactor.cpp b/src/libxrpl/tx/Transactor.cpp index 57d2207336..5010763afd 100644 --- a/src/libxrpl/tx/Transactor.cpp +++ b/src/libxrpl/tx/Transactor.cpp @@ -1006,6 +1006,26 @@ removeDeletedTrustLines( } } +static void +removeDeletedMPTs(ApplyView& view, std::vector const& mpts, beast::Journal viewJ) +{ + // There could be at most two MPTs - one for each side of AMM pool + if (mpts.size() > 2) + { + JLOG(viewJ.error()) << "removeDeletedMPTs: deleted mpts exceed 2 " << mpts.size(); + return; + } + + for (auto const& index : mpts) + { + if (auto const sleState = view.peek({ltMPTOKEN, index}); sleState && + deleteAMMMPToken(view, sleState, (*sleState)[sfIssuer], viewJ) != tesSUCCESS) + { + JLOG(viewJ.error()) << "removeDeletedMPTs: failed to delete AMM MPT"; + } + } +} + /** Reset the context, discarding any changes made and adjust the fee. @param fee The transaction fee to be charged. @@ -1144,19 +1164,21 @@ Transactor::operator()() // when transactions fail with a `tec` code. std::vector removedOffers; std::vector removedTrustLines; + std::vector removedMPTs; std::vector expiredNFTokenOffers; std::vector expiredCredentials; bool const doOffers = ((result == tecOVERSIZE) || (result == tecKILLED)); - bool const doLines = (result == tecINCOMPLETE); + bool const doLinesOrMPTs = (result == tecINCOMPLETE); bool const doNFTokenOffers = (result == tecEXPIRED); bool const doCredentials = (result == tecEXPIRED); - if (doOffers || doLines || doNFTokenOffers || doCredentials) + if (doOffers || doLinesOrMPTs || doNFTokenOffers || doCredentials) { ctx_.visit([doOffers, &removedOffers, - doLines, + doLinesOrMPTs, &removedTrustLines, + &removedMPTs, doNFTokenOffers, &expiredNFTokenOffers, doCredentials, @@ -1178,10 +1200,17 @@ Transactor::operator()() removedOffers.push_back(index); } - if (doLines && before && after && (before->getType() == ltRIPPLE_STATE)) + if (doLinesOrMPTs && before && after) { // Removal of obsolete AMM trust line - removedTrustLines.push_back(index); + if (before->getType() == ltRIPPLE_STATE) + { + removedTrustLines.push_back(index); + } + else if (before->getType() == ltMPTOKEN) + { + removedMPTs.push_back(index); + } } if (doNFTokenOffers && before && after && @@ -1219,6 +1248,7 @@ Transactor::operator()() { removeDeletedTrustLines( view(), removedTrustLines, ctx_.registry.get().getJournal("View")); + removeDeletedMPTs(view(), removedMPTs, ctx_.registry.get().getJournal("View")); } if (result == tecEXPIRED) diff --git a/src/libxrpl/tx/invariants/AMMInvariant.cpp b/src/libxrpl/tx/invariants/AMMInvariant.cpp index 0be4bedc07..03eb4c1d4a 100644 --- a/src/libxrpl/tx/invariants/AMMInvariant.cpp +++ b/src/libxrpl/tx/invariants/AMMInvariant.cpp @@ -128,15 +128,16 @@ ValidAMM::finalizeCreate( auto const [amount, amount2] = ammPoolHolds( view, *ammAccount_, - tx[sfAmount].get(), - tx[sfAmount2].get(), + tx[sfAmount].asset(), + tx[sfAmount2].asset(), fhIGNORE_FREEZE, + ahIGNORE_AUTH, j); // Create invariant: // sqrt(amount * amount2) == LPTokens // all balances are greater than zero if (!validBalances(amount, amount2, *lptAMMBalanceAfter_, ZeroAllowed::No) || - ammLPTokens(amount, amount2, lptAMMBalanceAfter_->issue()) != *lptAMMBalanceAfter_) + ammLPTokens(amount, amount2, lptAMMBalanceAfter_->get()) != *lptAMMBalanceAfter_) { JLOG(j.error()) << "AMMCreate invariant failed: " << amount << " " << amount2 << " " << *lptAMMBalanceAfter_; @@ -188,12 +189,7 @@ ValidAMM::generalInvariant( beast::Journal const& j) const { auto const [amount, amount2] = ammPoolHolds( - view, - *ammAccount_, - tx[sfAsset].get(), - tx[sfAsset2].get(), - fhIGNORE_FREEZE, - j); + view, *ammAccount_, tx[sfAsset], tx[sfAsset2], fhIGNORE_FREEZE, ahIGNORE_AUTH, j); // Deposit and Withdrawal invariant: // sqrt(amount * amount2) >= LPTokens // all balances are greater than zero diff --git a/src/libxrpl/tx/invariants/FreezeInvariant.cpp b/src/libxrpl/tx/invariants/FreezeInvariant.cpp index ee82157d44..e6be7c5e82 100644 --- a/src/libxrpl/tx/invariants/FreezeInvariant.cpp +++ b/src/libxrpl/tx/invariants/FreezeInvariant.cpp @@ -172,7 +172,7 @@ TransfersNotFrozen::recordBalanceChanges( STAmount const& balanceChange) { auto const balanceChangeSign = balanceChange.signum(); - auto const currency = after->at(sfBalance).getCurrency(); + auto const currency = after->at(sfBalance).get().currency; // Change from low account's perspective, which is trust line default recordBalance({currency, after->at(sfHighLimit).getIssuer()}, {after, balanceChangeSign}); diff --git a/src/libxrpl/tx/invariants/InvariantCheck.cpp b/src/libxrpl/tx/invariants/InvariantCheck.cpp index bf0f65f000..1d6756eaca 100644 --- a/src/libxrpl/tx/invariants/InvariantCheck.cpp +++ b/src/libxrpl/tx/invariants/InvariantCheck.cpp @@ -284,25 +284,29 @@ NoZeroEscrow::visitEntry( } else { - // IOU case - if (amount.holds()) - { - if (amount <= beast::zero) - return true; + return amount.asset().visit( + [&](Issue const& issue) { + // IOU case + if (amount <= beast::zero) + return true; - if (badCurrency() == amount.getCurrency()) - return true; - } + if (badCurrency() == issue.currency) + return true; - // MPT case - if (amount.holds()) - { - if (amount <= beast::zero) - return true; + return false; + } - if (amount.mpt() > MPTAmount{maxMPTokenAmount}) - return true; // LCOV_EXCL_LINE - } + // MPT case + , + [&](MPTIssue const&) { + if (amount <= beast::zero) + return true; + + if (amount.mpt() > MPTAmount{maxMPTokenAmount}) + return true; // LCOV_EXCL_LINE + + return false; + }); } return false; }; @@ -600,8 +604,8 @@ NoXRPTrustLines::visitEntry( // checking the issue directly here instead of // relying on .native() just in case native somehow // were systematically incorrect - xrpTrustLine_ = after->getFieldAmount(sfLowLimit).issue() == xrpIssue() || - after->getFieldAmount(sfHighLimit).issue() == xrpIssue(); + xrpTrustLine_ = after->getFieldAmount(sfLowLimit).asset() == xrpIssue() || + after->getFieldAmount(sfHighLimit).asset() == xrpIssue(); } } @@ -774,17 +778,23 @@ ValidClawback::finalize( return false; } - if (trustlinesChanged == 1) + bool const mptV2Enabled = view.rules().enabled(featureMPTokensV2); + if (trustlinesChanged == 1 || (mptV2Enabled && mptokensChanged == 1)) { AccountID const issuer = tx.getAccountID(sfAccount); STAmount const& amount = tx.getFieldAmount(sfAmount); AccountID const& holder = amount.getIssuer(); - STAmount const holderBalance = - accountHolds(view, holder, amount.getCurrency(), issuer, fhIGNORE_FREEZE, j); + STAmount const holderBalance = amount.asset().visit( + [&](Issue const& issue) { + return accountHolds(view, holder, issue.currency, issuer, fhIGNORE_FREEZE, j); + }, + [&](MPTIssue const& issue) { + return accountHolds(view, issuer, issue, fhIGNORE_FREEZE, ahIGNORE_AUTH, j); + }); if (holderBalance.signum() < 0) { - JLOG(j.fatal()) << "Invariant failed: trustline balance is negative"; + JLOG(j.fatal()) << "Invariant failed: trustline or MPT balance is negative"; return false; } } diff --git a/src/libxrpl/tx/invariants/MPTInvariant.cpp b/src/libxrpl/tx/invariants/MPTInvariant.cpp index 7b76e70c86..de7bcb790a 100644 --- a/src/libxrpl/tx/invariants/MPTInvariant.cpp +++ b/src/libxrpl/tx/invariants/MPTInvariant.cpp @@ -2,6 +2,7 @@ // #include #include +#include #include #include #include @@ -52,9 +53,10 @@ ValidMPTIssuance::finalize( ReadView const& view, beast::Journal const& j) const { - if (isTesSuccess(result)) + auto const& rules = view.rules(); + bool const mptV2Enabled = rules.enabled(featureMPTokensV2); + if (isTesSuccess(result) || (mptV2Enabled && result == tecINCOMPLETE)) { - auto const& rules = view.rules(); [[maybe_unused]] bool const enforceCreatedByIssuer = rules.enabled(featureSingleAssetVault) || rules.enabled(featureLendingProtocol); @@ -112,12 +114,12 @@ ValidMPTIssuance::finalize( return mptIssuancesCreated_ == 0 && mptIssuancesDeleted_ == 1; } - bool const lendingProtocolEnabled = view.rules().enabled(featureLendingProtocol); + bool const lendingProtocolEnabled = rules.enabled(featureLendingProtocol); // ttESCROW_FINISH may authorize an MPT, but it can't have the // mayAuthorizeMPT privilege, because that may cause // non-amendment-gated side effects. bool const enforceEscrowFinish = (txnType == ttESCROW_FINISH) && - (view.rules().enabled(featureSingleAssetVault) || lendingProtocolEnabled); + (rules.enabled(featureSingleAssetVault) || lendingProtocolEnabled); if (hasPrivilege(tx, mustAuthorizeMPT | mayAuthorizeMPT) || enforceEscrowFinish) { bool const submittedByIssuer = tx.isFieldPresent(sfHolder); @@ -134,19 +136,42 @@ ValidMPTIssuance::finalize( "succeeded but deleted issuances"; return false; } - if (lendingProtocolEnabled && mptokensCreated_ + mptokensDeleted_ > 1) + if (mptV2Enabled && hasPrivilege(tx, mayAuthorizeMPT) && + (txnType == ttAMM_WITHDRAW || txnType == ttAMM_CLAWBACK)) + { + if (submittedByIssuer && txnType == ttAMM_WITHDRAW && mptokensCreated_ > 0) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize " + "submitted by issuer succeeded " + "but created bad number of mptokens"; + return false; + } + // At most one MPToken may be created on withdraw/clawback since: + // - Liquidity Provider must have at least one token in order + // participate in AMM pool liquidity. + // - At most two MPTokens may be deleted if AMM pool, which has exactly + // two tokens, is empty after withdraw/clawback. + if (mptokensCreated_ > 1 || mptokensDeleted_ > 2) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize succeeded " + "but created/deleted bad number of mptokens"; + return false; + } + } + else if (lendingProtocolEnabled && (mptokensCreated_ + mptokensDeleted_) > 1) { JLOG(j.fatal()) << "Invariant failed: MPT authorize succeeded " "but created/deleted bad number mptokens"; return false; } - if (submittedByIssuer && (mptokensCreated_ > 0 || mptokensDeleted_ > 0)) + else if (submittedByIssuer && (mptokensCreated_ > 0 || mptokensDeleted_ > 0)) { JLOG(j.fatal()) << "Invariant failed: MPT authorize submitted by issuer " "succeeded but created/deleted mptokens"; return false; } - if (!submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && + else if ( + !submittedByIssuer && hasPrivilege(tx, mustAuthorizeMPT) && (mptokensCreated_ + mptokensDeleted_ != 1)) { // if the holder submitted this tx, then a mptoken must be @@ -158,6 +183,52 @@ ValidMPTIssuance::finalize( return true; } + + if (hasPrivilege(tx, mayCreateMPT)) + { + bool const submittedByIssuer = tx.isFieldPresent(sfHolder); + + if (mptIssuancesCreated_ > 0) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize " + "succeeded but created MPT issuances"; + return false; + } + if (mptIssuancesDeleted_ > 0) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize " + "succeeded but deleted issuances"; + return false; + } + if (mptokensDeleted_ > 0) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize " + "succeeded but deleted MPTokens"; + return false; + } + // AMMCreate may auto-create up to two MPT objects: + // - one per asset side in an MPT/MPT AMM, or one in an IOU/MPT AMM. + // CheckCash may auto-create at most one MPT object for the receiver. + if ((txnType == ttAMM_CREATE && mptokensCreated_ > 2) || + (txnType == ttCHECK_CASH && mptokensCreated_ > 1)) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize " + "succeeded but created bad number of mptokens"; + return false; + } + if (submittedByIssuer) + { + JLOG(j.fatal()) << "Invariant failed: MPT authorize submitted by issuer " + "succeeded but created mptokens"; + return false; + } + + // Offer crossing or payment may consume multiple offers + // where takerPays is MPT amount. If the offer owner doesn't + // own MPT then MPT is created automatically. + return true; + } + if (txnType == ttESCROW_FINISH) { // ttESCROW_FINISH may authorize an MPT, but it can't have the @@ -168,8 +239,9 @@ ValidMPTIssuance::finalize( return true; } - if (hasPrivilege(tx, mayDeleteMPT) && mptokensDeleted_ == 1 && mptokensCreated_ == 0 && - mptIssuancesCreated_ == 0 && mptIssuancesDeleted_ == 0) + if (hasPrivilege(tx, mayDeleteMPT) && + ((txnType == ttAMM_DELETE && mptokensDeleted_ <= 2) || mptokensDeleted_ == 1) && + mptokensCreated_ == 0 && mptIssuancesCreated_ == 0 && mptIssuancesDeleted_ == 0) return true; } @@ -194,4 +266,107 @@ ValidMPTIssuance::finalize( mptokensDeleted_ == 0; } +void +ValidMPTPayment::visitEntry( + bool, + std::shared_ptr const& before, + std::shared_ptr const& after) +{ + if (overflow_) + return; + + auto makeKey = [](SLE const& sle) { + if (sle.getType() == ltMPTOKEN_ISSUANCE) + return makeMptID(sle[sfSequence], sle[sfIssuer]); + return sle[sfMPTokenIssuanceID]; + }; + + auto update = [&](SLE const& sle, Order order) -> bool { + auto const type = sle.getType(); + if (type == ltMPTOKEN_ISSUANCE) + { + auto const outstanding = sle[sfOutstandingAmount]; + if (outstanding > maxMPTokenAmount) + { + overflow_ = true; + return false; + } + data_[makeKey(sle)].outstanding[order] = outstanding; + } + else if (type == ltMPTOKEN) + { + auto const mptAmt = sle[sfMPTAmount]; + auto const lockedAmt = sle[~sfLockedAmount].value_or(0); + if (mptAmt > maxMPTokenAmount || lockedAmt > maxMPTokenAmount || + lockedAmt > (maxMPTokenAmount - mptAmt)) + { + overflow_ = true; + return false; + } + auto const res = static_cast(mptAmt + lockedAmt); + // subtract before from after + if (order == Before) + { + data_[makeKey(sle)].mptAmount -= res; + } + else + { + data_[makeKey(sle)].mptAmount += res; + } + } + return true; + }; + + if (before && !update(*before, Before)) + return; + + if (after) + { + if (after->getType() == ltMPTOKEN_ISSUANCE) + { + overflow_ = (*after)[sfOutstandingAmount] > maxMPTAmount(*after); + } + if (!update(*after, After)) + return; + } +} + +bool +ValidMPTPayment::finalize( + STTx const& tx, + TER const result, + XRPAmount const, + ReadView const& view, + beast::Journal const& j) +{ + if (isTesSuccess(result)) + { + bool const enforce = view.rules().enabled(featureMPTokensV2); + if (overflow_) + { + JLOG(j.fatal()) << "Invariant failed: OutstandingAmount overflow"; + return !enforce; + } + + auto const signedMax = static_cast(maxMPTokenAmount); + for (auto const& [id, data] : data_) + { + (void)id; + bool const addOverflows = + (data.mptAmount > 0 && data.outstanding[Before] > (signedMax - data.mptAmount)) || + (data.mptAmount < 0 && data.outstanding[Before] < (-signedMax - data.mptAmount)); + if (addOverflows || + data.outstanding[After] != (data.outstanding[Before] + data.mptAmount)) + { + JLOG(j.fatal()) << "Invariant failed: invalid OutstandingAmount balance " + << data.outstanding[Before] << " " << data.outstanding[After] << " " + << data.mptAmount; + return !enforce; + } + } + } + + return true; +} + } // namespace xrpl diff --git a/src/libxrpl/tx/paths/AMMLiquidity.cpp b/src/libxrpl/tx/paths/AMMLiquidity.cpp index bb7f229374..29fcc3d4da 100644 --- a/src/libxrpl/tx/paths/AMMLiquidity.cpp +++ b/src/libxrpl/tx/paths/AMMLiquidity.cpp @@ -8,15 +8,15 @@ AMMLiquidity::AMMLiquidity( ReadView const& view, AccountID const& ammAccountID, std::uint32_t tradingFee, - Issue const& in, - Issue const& out, + Asset const& in, + Asset const& out, AMMContext& ammContext, beast::Journal j) : ammContext_(ammContext) , ammAccountID_(ammAccountID) , tradingFee_(tradingFee) - , issueIn_(in) - , issueOut_(out) + , assetIn_(in) + , assetOut_(out) , initialBalances_{fetchBalances(view)} , j_(j) { @@ -26,13 +26,13 @@ template TAmounts AMMLiquidity::fetchBalances(ReadView const& view) const { - auto const assetIn = ammAccountHolds(view, ammAccountID_, issueIn_); - auto const assetOut = ammAccountHolds(view, ammAccountID_, issueOut_); + auto const amountIn = ammAccountHolds(view, ammAccountID_, assetIn_); + auto const amountOut = ammAccountHolds(view, ammAccountID_, assetOut_); // This should not happen. - if (assetIn < beast::zero || assetOut < beast::zero) + if (amountIn < beast::zero || amountOut < beast::zero) Throw("AMMLiquidity: invalid balances"); - return TAmounts{get(assetIn), get(assetOut)}; + return TAmounts{get(amountIn), get(amountOut)}; } template @@ -42,7 +42,7 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances TAmounts cur{}; cur.in = toAmount( - getIssue(balances.in), + getAsset(balances.in), InitialFibSeqPct * initialBalances_.in, Number::rounding_mode::upward); cur.out = swapAssetIn(initialBalances_, cur.in, tradingFee_); @@ -60,7 +60,7 @@ AMMLiquidity::generateFibSeqOffer(TAmounts const& balances "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations"); cur.out = toAmount( - getIssue(balances.out), + getAsset(balances.out), cur.out * fib[ammContext_.curIters() - 1], Number::rounding_mode::downward); // swapAssetOut() returns negative in this case @@ -89,14 +89,18 @@ maxAmount() { return STAmount(STAmount::cMaxValue / 2, STAmount::cMaxOffset); } + else if constexpr (std::is_same_v) + { + return MPTAmount(maxMPTokenAmount); + } } template T -maxOut(T const& out, Issue const& iss) +maxOut(T const& out, Asset const& asset) { Number const res = out * Number{99, -2}; - return toAmount(iss, res, Number::rounding_mode::downward); + return toAmount(asset, res, Number::rounding_mode::downward); } } // namespace @@ -113,7 +117,7 @@ AMMLiquidity::maxOffer(TAmounts const& balances, Rules con Quality{balances}); } - auto const out = maxOut(balances.out, issueOut()); + auto const out = maxOut(balances.out, assetOut()); if (out <= TOut{0} || out >= balances.out) return std::nullopt; return AMMOffer( @@ -211,8 +215,8 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c if (offer->amount().in > beast::zero && offer->amount().out > beast::zero) { JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in) - << "/" << issueIn_ << " " << to_string(offer->amount().out) << "/" - << issueOut_; + << "/" << assetIn_ << " " << to_string(offer->amount().out) << "/" + << assetOut_; return offer; } @@ -225,9 +229,13 @@ AMMLiquidity::getOffer(ReadView const& view, std::optional c return std::nullopt; } -template class AMMLiquidity; template class AMMLiquidity; template class AMMLiquidity; template class AMMLiquidity; +template class AMMLiquidity; +template class AMMLiquidity; +template class AMMLiquidity; +template class AMMLiquidity; +template class AMMLiquidity; } // namespace xrpl diff --git a/src/libxrpl/tx/paths/AMMOffer.cpp b/src/libxrpl/tx/paths/AMMOffer.cpp index 79071850c2..c147e9197f 100644 --- a/src/libxrpl/tx/paths/AMMOffer.cpp +++ b/src/libxrpl/tx/paths/AMMOffer.cpp @@ -4,7 +4,7 @@ namespace xrpl { -template +template AMMOffer::AMMOffer( AMMLiquidity const& ammLiquidity, TAmounts const& amounts, @@ -15,28 +15,35 @@ AMMOffer::AMMOffer( { } -template -Issue const& -AMMOffer::issueIn() const +template +Asset const& +AMMOffer::assetIn() const { - return ammLiquidity_.issueIn(); + return ammLiquidity_.assetIn(); } -template +template +Asset const& +AMMOffer::assetOut() const +{ + return ammLiquidity_.assetOut(); +} + +template AccountID const& AMMOffer::owner() const { return ammLiquidity_.ammAccount(); } -template +template TAmounts const& AMMOffer::amount() const { return amounts_; } -template +template void AMMOffer::consume(ApplyView& view, TAmounts const& consumed) { @@ -52,7 +59,7 @@ AMMOffer::consume(ApplyView& view, TAmounts const& consume ammLiquidity_.context().setAMMUsed(); } -template +template TAmounts AMMOffer::limitOut( TAmounts const& offerAmount, @@ -77,7 +84,7 @@ AMMOffer::limitOut( return {swapAssetOut(balances_, limit, ammLiquidity_.tradingFee()), limit}; } -template +template TAmounts AMMOffer::limitIn(TAmounts const& offerAmount, TIn const& limit, bool roundUp) const @@ -94,7 +101,7 @@ AMMOffer::limitIn(TAmounts const& offerAmount, TIn const& return {limit, swapAssetIn(balances_, limit, ammLiquidity_.tradingFee())}; } -template +template QualityFunction AMMOffer::getQualityFunc() const { @@ -103,7 +110,7 @@ AMMOffer::getQualityFunc() const return QualityFunction{balances_, ammLiquidity_.tradingFee(), QualityFunction::AMMTag{}}; } -template +template bool AMMOffer::checkInvariant(TAmounts const& consumed, beast::Journal j) const { @@ -133,9 +140,13 @@ AMMOffer::checkInvariant(TAmounts const& consumed, beast:: return false; } -template class AMMOffer; template class AMMOffer; template class AMMOffer; template class AMMOffer; +template class AMMOffer; +template class AMMOffer; +template class AMMOffer; +template class AMMOffer; +template class AMMOffer; } // namespace xrpl diff --git a/src/libxrpl/tx/paths/BookStep.cpp b/src/libxrpl/tx/paths/BookStep.cpp index b17ccf1ea5..253f702114 100644 --- a/src/libxrpl/tx/paths/BookStep.cpp +++ b/src/libxrpl/tx/paths/BookStep.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -14,6 +15,7 @@ #include #include #include +#include #include @@ -40,7 +42,7 @@ protected: /** Number of offers consumed or partially consumed the last time the step ran, including expired and unfunded offers. - N.B. This this not the total number offers consumed by this step for the + N.B. This is not the total number offers consumed by this step for the entire payment, it is only the number the last time it ran. Offers may be partially consumed multiple times during a payment. */ @@ -50,6 +52,7 @@ protected: // quality or there is no CLOB offer. std::optional> ammLiquidity_; beast::Journal const j_; + Asset const strandDeliver_; struct Cache { @@ -64,13 +67,14 @@ protected: std::optional cache_; private: - BookStep(StrandContext const& ctx, Issue const& in, Issue const& out) + BookStep(StrandContext const& ctx, Asset const& in, Asset const& out) : book_(in, out, ctx.domainID) , strandSrc_(ctx.strandSrc) , strandDst_(ctx.strandDst) , prevStep_(ctx.prevStep) , ownerPaysTransferFee_(ctx.ownerPaysTransferFee) , j_(ctx.j) + , strandDeliver_(ctx.strandDeliver) { if (auto const ammSle = ctx.view.read(keylet::amm(in, out)); ammSle && ammSle->getFieldAmount(sfLPTokenBalance) != beast::zero) @@ -163,11 +167,14 @@ protected: { std::ostringstream ostr; ostr << name << ": " - << "\ninIss: " << book_.in.account << "\noutIss: " << book_.out.account - << "\ninCur: " << book_.in.currency << "\noutCur: " << book_.out.currency; + << "\ninIss: " << book_.in.getIssuer() << "\noutIss: " << book_.out.getIssuer() + << "\ninCur: " << to_string(book_.in) << "\noutCur: " << to_string(book_.out); return ostr.str(); } + Rate + rate(ReadView const& view, Asset const& asset, AccountID const& dstAccount) const; + private: friend bool operator==(BookStep const& lhs, BookStep const& rhs) @@ -188,7 +195,7 @@ private: // Unfunded offers and bad offers are skipped (and returned). // callback is called with the offer SLE, taker pays, taker gets. // If callback returns false, don't process any more offers. - // Return the unfunded and bad offers and the number of offers consumed. + // Return the unfunded, bad offers and the number of offers consumed. template std::pair, std::uint32_t> forEachOffer( @@ -227,6 +234,11 @@ private: std::optional tipOfferQualityF(ReadView const& view) const; + // Check that takerPays/takerGets can be transferred/traded. + // Applies to MPT assets. + bool + checkMPTDEX(ReadView const& view, AccountID const& owner) const; + friend TDerived; }; @@ -245,7 +257,7 @@ class BookPaymentStep : public BookStep> public: explicit BookPaymentStep() = default; - BookPaymentStep(StrandContext const& ctx, Issue const& in, Issue const& out) + BookPaymentStep(StrandContext const& ctx, Asset const& in, Asset const& out) : BookStep>(ctx, in, out) { } @@ -310,17 +322,12 @@ public: // (the old code does not charge a fee) // Calculate amount that goes to the taker and the amount charged the // offer owner - auto rate = [&](AccountID const& id) { - if (isXRP(id) || id == this->strandDst_) - return parityRate; - return transferRate(v, id); - }; - - auto const trIn = redeems(prevStepDir) ? rate(this->book_.in.account) : parityRate; + auto const trIn = + redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : parityRate; // Always charge the transfer fee, even if the owner is the issuer, // unless the fee is waived auto const trOut = (this->ownerPaysTransferFee_ && waiveFee == WaiveTransferFee::No) - ? rate(this->book_.out.account) + ? this->rate(v, this->book_.out, this->strandDst_) : parityRate; Quality const q1{getRate(STAmount(trOut.value), STAmount(trIn.value))}; @@ -355,7 +362,7 @@ private: } public: - BookOfferCrossingStep(StrandContext const& ctx, Issue const& in, Issue const& out) + BookOfferCrossingStep(StrandContext const& ctx, Asset const& in, Asset const& out) : BookStep>(ctx, in, out) , defaultPath_(ctx.isDefaultPath) , qualityThreshold_(getQuality(ctx.limitQuality)) @@ -454,7 +461,7 @@ public: auto const srcAcct = (prevStep != nullptr) ? prevStep->directStepSrcAcct() : std::nullopt; return owner == srcAcct // If offer crossing && prevStep is DirectI - ? QUALITY_ONE // && src is offer owner + ? QUALITY_ONE // or MPTEndpoint && src is offer owner : trIn; // then rate = QUALITY_ONE } @@ -502,13 +509,8 @@ public: return ofrQ; } - auto rate = [&](AccountID const& id) { - if (isXRP(id) || id == this->strandDst_) - return parityRate; - return transferRate(v, id); - }; - - auto const trIn = redeems(prevStepDir) ? rate(this->book_.in.account) : parityRate; + auto const trIn = + redeems(prevStepDir) ? this->rate(v, this->book_.in, this->strandDst_) : parityRate; // AMM doesn't pay the transfer fee on the out amount auto const trOut = parityRate; @@ -659,15 +661,11 @@ BookStep::forEachOffer( // (the old code does not charge a fee) // Calculate amount that goes to the taker and the amount charged the offer // owner - auto rate = [this, &sb](AccountID const& id) -> std::uint32_t { - if (isXRP(id) || id == this->strandDst_) - return QUALITY_ONE; - return transferRate(sb, id).value; - }; - - std::uint32_t const trIn = redeems(prevStepDir) ? rate(book_.in.account) : QUALITY_ONE; + std::uint32_t const trIn = + redeems(prevStepDir) ? rate(sb, book_.in, this->strandDst_).value : QUALITY_ONE; // Always charge the transfer fee, even if the owner is the issuer - std::uint32_t const trOut = ownerPaysTransferFee_ ? rate(book_.out.account) : QUALITY_ONE; + std::uint32_t const trOut = + ownerPaysTransferFee_ ? rate(sb, book_.out, this->strandDst_).value : QUALITY_ONE; typename FlowOfferStream::StepCounter counter(MaxOffersToConsume, j_); @@ -691,45 +689,49 @@ BookStep::forEachOffer( strandSrc_, strandDst_, offer, ofrQ, offers, offerAttempted)) return true; - // Make sure offer owner has authorization to own IOUs from issuer. - // An account can always own XRP or their own IOUs. - if (!isXRP(offer.issueIn().currency) && offer.owner() != offer.issueIn().account) + Asset const& assetIn = offer.assetIn(); + bool const isAssetInMPT = assetIn.holds(); + auto const& owner = offer.owner(); + + if (isAssetInMPT) { - auto const& issuerID = offer.issueIn().account; - auto const issuer = afView.read(keylet::account(issuerID)); - if (issuer && ((*issuer)[sfFlags] & lsfRequireAuth)) + // Create MPToken for the offer's owner. No need to check + // for the reserve since the offer is removed if it is consumed. + // Therefore, the owner count remains the same. + if (auto const err = checkCreateMPT(sb, assetIn.get(), owner, j_); + !isTesSuccess(err)) { - // Issuer requires authorization. See if offer owner has that. - auto const& ownerID = offer.owner(); - auto const authFlag = issuerID > ownerID ? lsfHighAuth : lsfLowAuth; - - auto const line = - afView.read(keylet::line(ownerID, issuerID, offer.issueIn().currency)); - - if (!line || (((*line)[sfFlags] & authFlag) == 0)) - { - // Offer owner not authorized to hold IOU from issuer. - // Remove this offer even if no crossing occurs. - if (auto const key = offer.key()) - offers.permRmOffer(*key); - if (!offerAttempted) - { - // Change quality only if no previous offers were tried. - ofrQ = std::nullopt; - } - // Returning true causes offers.step() to delete the offer. - return true; - } + return true; } } + // It shouldn't matter from auth point of view whether it's sb + // or afView. Amendment guard this change just in case. + auto& applyView = sb.rules().enabled(featureMPTokensV2) ? sb : afView; + // Make sure offer owner has authorization to own Assets from issuer + // and MPT assets can be traded/transferred. + // An account can always own XRP or their own Assets. + if (!isTesSuccess(requireAuth(applyView, assetIn, owner)) || !checkMPTDEX(sb, owner)) + { + // Offer owner not authorized to hold IOU/MPT from issuer. + // Remove this offer even if no crossing occurs. + if (auto const key = offer.key()) + offers.permRmOffer(*key); + if (!offerAttempted) + { + // Change quality only if no previous offers were tried. + ofrQ = std::nullopt; + } + // Returning true causes offers.step() to delete the offer. + return true; + } + if (!static_cast(this)->checkQualityThreshold(offer.quality())) return false; auto const [ofrInRate, ofrOutRate] = offer.adjustRates( - static_cast(this)->getOfrInRate(prevStep_, offer.owner(), trIn), - static_cast(this)->getOfrOutRate( - prevStep_, offer.owner(), strandDst_, trOut)); + static_cast(this)->getOfrInRate(prevStep_, owner, trIn), + static_cast(this)->getOfrOutRate(prevStep_, owner, strandDst_, trOut)); auto ofrAmt = offer.amount(); TAmounts stpAmt{mulRatio(ofrAmt.in, ofrInRate, QUALITY_ONE, /*roundUp*/ true), ofrAmt.out}; @@ -756,6 +758,26 @@ BookStep::forEachOffer( stpAmt.in = mulRatio(ofrAmt.in, ofrInRate, QUALITY_ONE, /*roundUp*/ true); } + // Limit offer's input if MPT, BookStep is the first step (an issuer + // is making a cross-currency payment), and this offer is not owned + // by the issuer. Otherwise, OutstandingAmount may overflow. + auto const& issuer = assetIn.getIssuer(); + if (isAssetInMPT && !prevStep_ && offer.owner() != issuer) + { + // Funds available to issue + auto const available = toAmount(accountFunds( + sb, + issuer, + assetIn, // STAmount{0}, but the default is not used + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + j_)); + if (stpAmt.in > available) + { + limitStepIn(offer, ofrAmt, stpAmt, ownerGives, ofrInRate, ofrOutRate, available); + } + } + offerAttempted = true; return callback(offer, ofrAmt, stpAmt, ownerGives, ofrInRate, ofrOutRate); }; @@ -820,8 +842,8 @@ BookStep::consumeOffer( // The offer owner gets the ofrAmt. The difference between ofrAmt and // stepAmt is a transfer fee that goes to book_.in.account { - auto const dr = - offer.send(sb, book_.in.account, offer.owner(), toSTAmount(ofrAmt.in, book_.in), j_); + auto const dr = offer.send( + sb, book_.in.getIssuer(), offer.owner(), toSTAmount(ofrAmt.in, book_.in), j_); if (!isTesSuccess(dr)) Throw(dr); } @@ -829,10 +851,16 @@ BookStep::consumeOffer( // The offer owner pays `ownerGives`. The difference between ownerGives and // stepAmt is a transfer fee that goes to book_.out.account { + auto const& issuer = book_.out.getIssuer(); auto const cr = - offer.send(sb, offer.owner(), book_.out.account, toSTAmount(ownerGives, book_.out), j_); + offer.send(sb, offer.owner(), issuer, toSTAmount(ownerGives, book_.out), j_); if (!isTesSuccess(cr)) Throw(cr); + if constexpr (std::is_same_v) + { + if (offer.owner() == issuer) + issuerSelfDebitHookMPT(sb, book_.out.get(), ofrAmt.out.value()); + } } offer.consume(sb, ofrAmt); @@ -1260,20 +1288,20 @@ BookStep::check(StrandContext const& ctx) const // Do not allow two books to output the same issue. This may cause offers on // one step to unfund offers in another step. if (!ctx.seenBookOuts.insert(book_.out).second || - (ctx.seenDirectIssues[0].count(book_.out) != 0u)) + (ctx.seenDirectAssets[0].count(book_.out) != 0u)) { JLOG(j_.debug()) << "BookStep: loop detected: " << *this; return temBAD_PATH_LOOP; } - if (ctx.seenDirectIssues[1].count(book_.out) != 0u) + if (ctx.seenDirectAssets[1].count(book_.out) != 0u) { JLOG(j_.debug()) << "BookStep: loop detected: " << *this; return temBAD_PATH_LOOP; } - auto issuerExists = [](ReadView const& view, Issue const& iss) -> bool { - return isXRP(iss.account) || view.read(keylet::account(iss.account)); + auto issuerExists = [](ReadView const& view, Asset const& iss) -> bool { + return isXRP(iss.getIssuer()) || view.exists(keylet::account(iss.getIssuer())); }; if (!issuerExists(ctx.view, book_.in) || !issuerExists(ctx.view, book_.out)) @@ -1287,19 +1315,101 @@ BookStep::check(StrandContext const& ctx) const if (auto const prev = ctx.prevStep->directStepSrcAcct()) { auto const& view = ctx.view; - auto const& cur = book_.in.account; + auto const& cur = book_.in.getIssuer(); - auto sle = view.read(keylet::line(*prev, cur, book_.in.currency)); - if (!sle) - return terNO_LINE; - if (((*sle)[sfFlags] & ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) != 0u) - return terNO_RIPPLE; + auto const err = book_.in.visit( + [&](Issue const& issue) -> std::optional { + auto sle = view.read(keylet::line(*prev, cur, issue.currency)); + if (!sle) + return terNO_LINE; + if (((*sle)[sfFlags] & ((cur > *prev) ? lsfHighNoRipple : lsfLowNoRipple)) != + 0u) + return terNO_RIPPLE; + return std::nullopt; + }, + [&](MPTIssue const& issue) -> std::optional { + // Check if can trade on DEX. + if (auto const ter = canTrade(view, book_.in); !isTesSuccess(ter)) + return ter; + if (auto const ter = canTrade(view, book_.out); !isTesSuccess(ter)) + return ter; + return std::nullopt; + }); + if (err) + return *err; } } return tesSUCCESS; } +template +Rate +BookStep::rate( + ReadView const& view, + Asset const& asset, + AccountID const& dstAccount) const +{ + auto const& issuer = asset.getIssuer(); + if (isXRP(issuer) || issuer == dstAccount) + return parityRate; + return asset.visit( + [&](Issue const&) { return transferRate(view, issuer); }, + [&](MPTIssue const& issue) { return transferRate(view, issue.getMptID()); }); +}; + +template +bool +BookStep::checkMPTDEX(ReadView const& view, AccountID const& owner) const +{ + if (!isTesSuccess(canTrade(view, book_.in)) || !isTesSuccess(canTrade(view, book_.out))) + return false; + + if (book_.in.holds()) + { + auto ret = [&]() { + auto const& asset = book_.in; + // Strand's source is an issuer + if (!prevStep_) + return true; + // Offer's owner is an issuer + if (asset.getIssuer() == owner) + return true; + // The previous step could be MPTEndpointStep with non issuer account or + // BookStep. Fail both if in asset is locked. In the former case it is holder + // to locked holder transfer. In the latter case it is not possible to tell if + // it is issuer to holder or holder to holder transfer. + if (isFrozen(view, owner, book_.in.get())) + return false; + // Previous step is BookStep. BookStep only sends if CanTransfer is + // set and not locked or the offer is owned by an issuer + if (prevStep_->bookStepBook()) + return true; + // Previous step is MPTEndpointStep and offer's owner is not an + // issuer + return isTesSuccess(canTransfer(view, asset, owner, owner)); + }(); + if (!ret) + return false; + } + + if (book_.out.holds()) + { + auto const& asset = book_.out; + // Last step if the strand's destination is an issuer + if (strandDeliver_ == asset && strandDst_ == asset.getIssuer()) + return true; + // Offer's owner is an issuer + if (asset.getIssuer() == owner) + return true; + + // Next step is BookStep and offer's owner is not an issuer. + return isTesSuccess(canTransfer(view, asset, owner, owner)); + } + + return true; +} + //------------------------------------------------------------------------------ namespace test { @@ -1317,22 +1427,21 @@ equalHelper(Step const& step, xrpl::Book const& book) bool bookStepEqual(Step const& step, xrpl::Book const& book) { - bool const inXRP = isXRP(book.in.currency); - bool const outXRP = isXRP(book.out.currency); - if (inXRP && outXRP) + if (isXRP(book.in) && isXRP(book.out)) { // LCOV_EXCL_START UNREACHABLE("xrpl::test::bookStepEqual : no XRP to XRP book step"); return false; // no such thing as xrp/xrp book step // LCOV_EXCL_STOP } - if (inXRP && !outXRP) - return equalHelper>(step, book); - if (!inXRP && outXRP) - return equalHelper>(step, book); - if (!inXRP && !outXRP) - return equalHelper>(step, book); - return false; + return std::visit( + [&](TIn const&, TOut const&) { + using TIn_ = typename TIn::amount_type; + using TOut_ = typename TOut::amount_type; + return equalHelper>(step, book); + }, + book.in.getAmountType(), + book.out.getAmountType()); } } // namespace test @@ -1340,7 +1449,7 @@ bookStepEqual(Step const& step, xrpl::Book const& book) template static std::pair> -make_BookStepHelper(StrandContext const& ctx, Issue const& in, Issue const& out) +make_BookStepHelper(StrandContext const& ctx, Asset const& in, Asset const& out) { TER ter = tefINTERNAL; std::unique_ptr r; @@ -1380,4 +1489,35 @@ make_BookStepXI(StrandContext const& ctx, Issue const& out) return make_BookStepHelper(ctx, xrpIssue(), out); } +// MPT's +std::pair> +make_BookStepMM(StrandContext const& ctx, MPTIssue const& in, MPTIssue const& out) +{ + return make_BookStepHelper(ctx, in, out); +} + +std::pair> +make_BookStepMI(StrandContext const& ctx, MPTIssue const& in, Issue const& out) +{ + return make_BookStepHelper(ctx, in, out); +} + +std::pair> +make_BookStepIM(StrandContext const& ctx, Issue const& in, MPTIssue const& out) +{ + return make_BookStepHelper(ctx, in, out); +} + +std::pair> +make_BookStepMX(StrandContext const& ctx, MPTIssue const& in) +{ + return make_BookStepHelper(ctx, in, xrpIssue()); +} + +std::pair> +make_BookStepXM(StrandContext const& ctx, MPTIssue const& out) +{ + return make_BookStepHelper(ctx, xrpIssue(), out); +} + } // namespace xrpl diff --git a/src/libxrpl/tx/paths/DirectStep.cpp b/src/libxrpl/tx/paths/DirectStep.cpp index 9fd90b7755..6bf76e9002 100644 --- a/src/libxrpl/tx/paths/DirectStep.cpp +++ b/src/libxrpl/tx/paths/DirectStep.cpp @@ -671,7 +671,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo auto const savCache = *cache_; - XRPL_ASSERT(!in.native, "xrpl::DirectStepI::validFwd : input is not XRP"); + XRPL_ASSERT(in.holds(), "xrpl::DirectStepI::validFwd : input is IOU"); auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxFlow(sb, cache_->srcToDst); @@ -680,7 +680,7 @@ DirectStepI::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmo try { boost::container::flat_set dummy; - fwdImp(sb, afView, dummy, in.iou); // changes cache + fwdImp(sb, afView, dummy, in.get()); // changes cache } catch (FlowException const&) { @@ -857,13 +857,13 @@ DirectStepI::check(StrandContext const& ctx) const // issue if (auto book = ctx.prevStep->bookStepBook()) { - if (book->out != srcIssue) + if (book->out.get() != srcIssue) return temBAD_PATH_LOOP; } } - if (!ctx.seenDirectIssues[0].insert(srcIssue).second || - !ctx.seenDirectIssues[1].insert(dstIssue).second) + if (!ctx.seenDirectAssets[0].insert(srcIssue).second || + !ctx.seenDirectAssets[1].insert(dstIssue).second) { JLOG(j_.debug()) << "DirectStepI: loop detected: Index: " << ctx.strandSize << ' ' << *this; diff --git a/src/libxrpl/tx/paths/Flow.cpp b/src/libxrpl/tx/paths/Flow.cpp index 5a706ea812..6226e550b7 100644 --- a/src/libxrpl/tx/paths/Flow.cpp +++ b/src/libxrpl/tx/paths/Flow.cpp @@ -12,7 +12,7 @@ namespace xrpl { template static auto -finishFlow(PaymentSandbox& sb, Issue const& srcIssue, Issue const& dstIssue, FlowResult&& f) +finishFlow(PaymentSandbox& sb, Asset const& srcAsset, Asset const& dstAsset, FlowResult&& f) { path::RippleCalc::Output result; if (isTesSuccess(f.ter)) @@ -25,8 +25,8 @@ finishFlow(PaymentSandbox& sb, Issue const& srcIssue, Issue const& dstIssue, Flo } result.setResult(f.ter); - result.actualAmountIn = toSTAmount(f.in, srcIssue); - result.actualAmountOut = toSTAmount(f.out, dstIssue); + result.actualAmountIn = toSTAmount(f.in, srcAsset); + result.actualAmountOut = toSTAmount(f.out, dstAsset); return result; }; @@ -48,19 +48,23 @@ flow( beast::Journal j, path::detail::FlowDebugInfo* flowDebugInfo) { - Issue const srcIssue = [&] { + Asset const srcAsset = [&]() -> Asset { if (sendMax) - return sendMax->issue(); - if (!isXRP(deliver.issue().currency)) - return Issue(deliver.issue().currency, src); - return xrpIssue(); + return sendMax->asset(); + return deliver.asset().visit( + [&](Issue const& issue) -> Asset { + if (isXRP(issue)) + return xrpIssue(); + return Issue(issue.currency, src); + }, + [&](MPTIssue const&) { return deliver.asset(); }); }(); - Issue const dstIssue = deliver.issue(); + Asset const dstAsset = deliver.asset(); - std::optional sendMaxIssue; + std::optional sendMaxAsset; if (sendMax) - sendMaxIssue = sendMax->issue(); + sendMaxAsset = sendMax->asset(); AMMContext ammContext(src, false); @@ -71,9 +75,9 @@ flow( sb, src, dst, - dstIssue, + dstAsset, limitQuality, - sendMaxIssue, + sendMaxAsset, paths, defaultPaths, ownerPaysTransferFee, @@ -93,8 +97,8 @@ flow( if (j.trace()) { - j.trace() << "\nsrc: " << src << "\ndst: " << dst << "\nsrcIssue: " << srcIssue - << "\ndstIssue: " << dstIssue; + j.trace() << "\nsrc: " << src << "\ndst: " << dst << "\nsrcAsset: " << srcAsset + << "\ndstAsset: " << dstAsset; j.trace() << "\nNumStrands: " << strands.size(); for (auto const& curStrand : strands) { @@ -106,87 +110,32 @@ flow( } } - bool const srcIsXRP = isXRP(srcIssue.currency); - bool const dstIsXRP = isXRP(dstIssue.currency); - - auto const asDeliver = toAmountSpec(deliver); - - // The src account may send either xrp or iou. The dst account may receive - // either xrp or iou. Since XRP and IOU amounts are represented by different - // types, use templates to tell `flow` about the amount types. - if (srcIsXRP && dstIsXRP) - { - return finishFlow( - sb, - srcIssue, - dstIssue, - flow( + // The src account may send either xrp,iou,or mpt. The dst account may + // receive either xrp,iou, or mpt. Since XRP, IOU, and MPT amounts are + // represented by different types, use templates to tell `flow` about the + // amount types. + return std::visit( + [&, &strands_ = strands](TIn const&, TOut const&) { + using TIn_ = typename TIn::amount_type; + using TOut_ = typename TOut::amount_type; + return finishFlow( sb, - strands, - asDeliver.xrp, - partialPayment, - offerCrossing, - limitQuality, - sendMax, - j, - ammContext, - flowDebugInfo)); - } - - if (srcIsXRP && !dstIsXRP) - { - return finishFlow( - sb, - srcIssue, - dstIssue, - flow( - sb, - strands, - asDeliver.iou, - partialPayment, - offerCrossing, - limitQuality, - sendMax, - j, - ammContext, - flowDebugInfo)); - } - - if (!srcIsXRP && dstIsXRP) - { - return finishFlow( - sb, - srcIssue, - dstIssue, - flow( - sb, - strands, - asDeliver.xrp, - partialPayment, - offerCrossing, - limitQuality, - sendMax, - j, - ammContext, - flowDebugInfo)); - } - - XRPL_ASSERT(!srcIsXRP && !dstIsXRP, "xrpl::flow : neither is XRP"); - return finishFlow( - sb, - srcIssue, - dstIssue, - flow( - sb, - strands, - asDeliver.iou, - partialPayment, - offerCrossing, - limitQuality, - sendMax, - j, - ammContext, - flowDebugInfo)); + srcAsset, + dstAsset, + flow( + sb, + strands_, + get(deliver), + partialPayment, + offerCrossing, + limitQuality, + sendMax, + j, + ammContext, + flowDebugInfo)); + }, + srcAsset.getAmountType(), + dstAsset.getAmountType()); } } // namespace xrpl diff --git a/src/libxrpl/tx/paths/MPTEndpointStep.cpp b/src/libxrpl/tx/paths/MPTEndpointStep.cpp new file mode 100644 index 0000000000..8944df953d --- /dev/null +++ b/src/libxrpl/tx/paths/MPTEndpointStep.cpp @@ -0,0 +1,919 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include + +namespace xrpl { + +template +class MPTEndpointStep : public StepImp> +{ +protected: + AccountID const src_; + AccountID const dst_; + MPTIssue const mptIssue_; + + // Charge transfer fees when the prev step redeems + Step const* const prevStep_ = nullptr; + bool const isLast_; + // Direct payment between the holders + // Used by maxFlow's last step. + bool const isDirectBetweenHolders_ = false; + beast::Journal const j_; + + struct Cache + { + MPTAmount in; + MPTAmount srcToDst; + MPTAmount out; + DebtDirection srcDebtDir; + + Cache( + MPTAmount const& in_, + MPTAmount const& srcToDst_, + MPTAmount const& out_, + DebtDirection srcDebtDir_) + : in(in_), srcToDst(srcToDst_), out(out_), srcDebtDir(srcDebtDir_) + { + } + }; + + std::optional cache_; + + // Compute the maximum value that can flow from src->dst at + // the best available quality. + // return: first element is max amount that can flow, + // second is the debt direction of the source w.r.t. the dst + std::pair + maxPaymentFlow(ReadView const& sb) const; + + // Compute srcQOut and dstQIn when the source redeems. + std::pair + qualitiesSrcRedeems(ReadView const& sb) const; + + // Compute srcQOut and dstQIn when the source issues. + std::pair + qualitiesSrcIssues(ReadView const& sb, DebtDirection prevStepDebtDirection) const; + + // Returns srcQOut, dstQIn + std::pair + qualities(ReadView const& sb, DebtDirection srcDebtDir, StrandDirection strandDir) const; + + void + resetCache(DebtDirection dir); + +private: + MPTEndpointStep( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + MPTID const& mpt) + : src_(src) + , dst_(dst) + , mptIssue_(mpt) + , prevStep_(ctx.prevStep) + , isLast_(ctx.isLast) + , isDirectBetweenHolders_( + mptIssue_ == ctx.strandDeliver && ctx.strandSrc != mptIssue_.getIssuer() && + ctx.strandDst != mptIssue_.getIssuer() && + (ctx.isFirst || (ctx.prevStep != nullptr && !ctx.prevStep->bookStepBook()))) + , j_(ctx.j) + { + XRPL_ASSERT( + src_ == mptIssue_.getIssuer() || dst_ == mptIssue_.getIssuer(), + "MPTEndpointStep::MPTEndpointStep src or dst must be an issuer"); + } + +public: + AccountID const& + src() const + { + return src_; + } + AccountID const& + dst() const + { + return dst_; + } + MPTID const& + mptID() const + { + return mptIssue_.getMptID(); + } + + std::optional + cachedIn() const override + { + if (!cache_) + return std::nullopt; + return EitherAmount(cache_->in); + } + + std::optional + cachedOut() const override + { + if (!cache_) + return std::nullopt; + return EitherAmount(cache_->out); + } + + std::optional + directStepSrcAcct() const override + { + return src_; + } + + std::optional> + directStepAccts() const override + { + return std::make_pair(src_, dst_); + } + + DebtDirection + debtDirection(ReadView const& sb, StrandDirection dir) const override; + + std::uint32_t + lineQualityIn(ReadView const& v) const override; + + std::pair, DebtDirection> + qualityUpperBound(ReadView const& v, DebtDirection dir) const override; + + std::pair + revImp( + PaymentSandbox& sb, + ApplyView& afView, + boost::container::flat_set& ofrsToRm, + MPTAmount const& out); + + std::pair + fwdImp( + PaymentSandbox& sb, + ApplyView& afView, + boost::container::flat_set& ofrsToRm, + MPTAmount const& in); + + std::pair + validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) override; + + // Check for error, existing liquidity, and violations of auth/frozen + // constraints. + TER + check(StrandContext const& ctx) const; + + void + setCacheLimiting( + MPTAmount const& fwdIn, + MPTAmount const& fwdSrcToDst, + MPTAmount const& fwdOut, + DebtDirection srcDebtDir); + + friend bool + operator==(MPTEndpointStep const& lhs, MPTEndpointStep const& rhs) + { + return lhs.src_ == rhs.src_ && lhs.dst_ == rhs.dst_ && lhs.mptIssue_ == rhs.mptIssue_; + } + + friend bool + operator!=(MPTEndpointStep const& lhs, MPTEndpointStep const& rhs) + { + return !(lhs == rhs); + } + +protected: + std::string + logStringImpl(char const* name) const + { + std::ostringstream ostr; + ostr << name << ": " + << "\nSrc: " << src_ << "\nDst: " << dst_; + return ostr.str(); + } + +private: + bool + equal(Step const& rhs) const override + { + if (auto ds = dynamic_cast(&rhs)) + { + return *this == *ds; + } + return false; + } + + friend TDerived; +}; + +//------------------------------------------------------------------------------ + +// Flow is used in two different circumstances for transferring funds: +// o Payments, and +// o Offer crossing. +// The rules for handling funds in these two cases are almost, but not +// quite, the same. + +// Payment MPTEndpointStep class (not offer crossing). +class MPTEndpointPaymentStep : public MPTEndpointStep +{ +public: + using MPTEndpointStep::MPTEndpointStep; + using MPTEndpointStep::check; + + MPTEndpointPaymentStep( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + MPTID const& mpt) + : MPTEndpointStep(ctx, src, dst, mpt) + { + } + + static bool + verifyPrevStepDebtDirection(DebtDirection) + { + // A payment doesn't care regardless of prevStepRedeems. + return true; + } + + // Verify the consistency of the step. These checks are specific to + // payments and assume that general checks were already performed. + TER + check(StrandContext const& ctx, std::shared_ptr const& sleSrc) const; + + std::string + logString() const override + { + return logStringImpl("MPTEndpointPaymentStep"); + } + + // Not applicable for payment + static TER + checkCreateMPT(ApplyView&, DebtDirection) + { + return tesSUCCESS; + } +}; + +// Offer crossing MPTEndpointStep class (not a payment). +class MPTEndpointOfferCrossingStep : public MPTEndpointStep +{ +public: + using MPTEndpointStep::MPTEndpointStep; + using MPTEndpointStep::check; + + MPTEndpointOfferCrossingStep( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + MPTID const& mpt) + : MPTEndpointStep(ctx, src, dst, mpt) + { + } + + static bool + verifyPrevStepDebtDirection(DebtDirection prevStepDir) + { + // During offer crossing we rely on the fact that prevStepRedeems + // will *always* issue. That's because: + // o If there's a prevStep_, it will always be a BookStep. + // o BookStep::debtDirection() always returns `issues` when offer + // crossing. + // An assert based on this return value will tell us if that + // behavior changes. + return issues(prevStepDir); + } + + // Verify the consistency of the step. These checks are specific to + // offer crossing and assume that general checks were already performed. + static TER + check(StrandContext const& ctx, std::shared_ptr const& sleSrc); + + std::string + logString() const override + { + return logStringImpl("MPTEndpointOfferCrossingStep"); + } + + // Can be created in rev or fwd (if limiting step) direction. + TER + checkCreateMPT(ApplyView& view, DebtDirection srcDebtDir); +}; + +//------------------------------------------------------------------------------ + +TER +MPTEndpointPaymentStep::check(StrandContext const& ctx, std::shared_ptr const& sleSrc) + const +{ + // Since this is a payment, MPToken must be present. Perform all + // MPToken related checks. + + // requireAuth checks if MPTIssuance exist. Note that issuer to issuer + // payment is invalid + auto const& issuer = mptIssue_.getIssuer(); + if (src_ != issuer) + { + if (auto const ter = requireAuth(ctx.view, mptIssue_, src_); !isTesSuccess(ter)) + return ter; + } + + if (dst_ != issuer) + { + if (auto const ter = requireAuth(ctx.view, mptIssue_, dst_); !isTesSuccess(ter)) + return ter; + } + + // Direct MPT payment, no DEX + if (mptIssue_ == ctx.strandDeliver && + (ctx.isFirst || (ctx.prevStep != nullptr && !ctx.prevStep->bookStepBook()))) + { + // Between holders + if (isDirectBetweenHolders_) + { + auto const& holder = ctx.isFirst ? src_ : dst_; + // Payment between the holders + if (isFrozen(ctx.view, holder, mptIssue_)) + return tecLOCKED; + + if (auto const ter = canTransfer(ctx.view, mptIssue_, holder, ctx.strandDst); + !isTesSuccess(ter)) + return ter; + } + // Don't need to check if a payment is between issuer and holder + // in either direction + } + // Cross-token MPT payment via DEX + else + { + if (auto const ter = canTrade(ctx.view, mptIssue_); !isTesSuccess(ter)) + return ter; + } + + // Can't check for creditBalance/Limit unless it's the first step. + // Otherwise, even if OutstandingAmount is equal to MaximumAmount + // a payment can still be successful. For instance, when a balance + // is shifted from one holder to another. + + if (prevStep_ == nullptr) + { + auto const owed = + accountFunds(ctx.view, src_, mptIssue_, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_); + // Already at MaximumAmount + if (owed <= beast::zero) + return tecPATH_DRY; + } + + return tesSUCCESS; +} + +TER +MPTEndpointOfferCrossingStep::check(StrandContext const& ctx, std::shared_ptr const&) +{ + return tesSUCCESS; +} + +TER +MPTEndpointOfferCrossingStep::checkCreateMPT(ApplyView& view, xrpl::DebtDirection srcDebtDir) +{ + // TakerPays is the last step if offer crossing + if (isLast_) + { + // Create MPToken for the offer's owner. No need to check + // for the reserve since the offer doesn't go on the books + // if crossed. Insufficient reserve is allowed if the offer + // crossed. See CreateOffer::applyGuts() for reserve check. + if (auto const err = xrpl::checkCreateMPT(view, mptIssue_, dst_, j_); !isTesSuccess(err)) + { + JLOG(j_.trace()) << "MPTEndpointStep::checkCreateMPT: failed create MPT"; + resetCache(srcDebtDir); + return err; + } + } + return tesSUCCESS; +} + +//------------------------------------------------------------------------------ + +template +std::pair +MPTEndpointStep::maxPaymentFlow(ReadView const& sb) const +{ + auto const maxFlow = accountFunds(sb, src_, mptIssue_, fhIGNORE_FREEZE, ahIGNORE_AUTH, j_); + + // From a holder to an issuer + if (src_ != mptIssue_.getIssuer()) + return {toAmount(maxFlow), DebtDirection::redeems}; + + // From an issuer to a holder + if (auto const sle = sb.read(keylet::mptIssuance(mptIssue_))) + { + // If issuer is the source account, and it is direct payment then + // MPTEndpointStep is the only step. Provide available maxFlow. + if (prevStep_ == nullptr) + return {toAmount(maxFlow), DebtDirection::issues}; + + // MPTEndpointStep is the last step. It's always issuing in + // this case. Can't infer at this point what the maxFlow is, because + // the previous step may issue or redeem. Allow OutstandingAmount + // to temporarily overflow. Let the previous step figure out how + // to limit the flow. + std::int64_t const maxAmount = maxMPTAmount(*sle); + return {MPTAmount{maxAmount}, DebtDirection::issues}; + } + + return {MPTAmount{0}, DebtDirection::issues}; +} + +template +DebtDirection +MPTEndpointStep::debtDirection(ReadView const& sb, StrandDirection dir) const +{ + if (dir == StrandDirection::forward && cache_) + return cache_->srcDebtDir; + + return (src_ == mptIssue_.getIssuer()) ? DebtDirection::issues : DebtDirection::redeems; +} + +template +std::pair +MPTEndpointStep::revImp( + PaymentSandbox& sb, + ApplyView& /*afView*/, + boost::container::flat_set& /*ofrsToRm*/, + MPTAmount const& out) +{ + cache_.reset(); + + auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxPaymentFlow(sb); + + auto const [srcQOut, dstQIn] = qualities(sb, srcDebtDir, StrandDirection::reverse); + (void)dstQIn; + + MPTIssue const srcToDstIss(mptIssue_); + + JLOG(j_.trace()) << "MPTEndpointStep::rev" + << " srcRedeems: " << redeems(srcDebtDir) << " outReq: " << to_string(out) + << " maxSrcToDst: " << to_string(maxSrcToDst) << " srcQOut: " << srcQOut + << " dstQIn: " << dstQIn; + + if (maxSrcToDst.signum() <= 0) + { + JLOG(j_.trace()) << "MPTEndpointStep::rev: dry"; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + + if (auto const err = static_cast(this)->checkCreateMPT(sb, srcDebtDir); + !isTesSuccess(err)) + return {beast::zero, beast::zero}; + + // Don't have to factor in dstQIn since it is always QUALITY_ONE + MPTAmount const srcToDst = out; + + if (srcToDst <= maxSrcToDst) + { + MPTAmount const in = mulRatio(srcToDst, srcQOut, QUALITY_ONE, /*roundUp*/ true); + cache_.emplace(in, srcToDst, srcToDst, srcDebtDir); + auto const ter = directSendNoFee( + sb, + src_, + dst_, + toSTAmount(srcToDst, srcToDstIss), + /*checkIssuer*/ false, + j_); + if (!isTesSuccess(ter)) + { + JLOG(j_.trace()) << "MPTEndpointStep::rev: error " << ter; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + JLOG(j_.trace()) << "MPTEndpointStep::rev: Non-limiting" + << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) + << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out); + return {in, out}; + } + + // limiting node + MPTAmount const in = mulRatio(maxSrcToDst, srcQOut, QUALITY_ONE, /*roundUp*/ true); + // Don't have to factor in dsqQIn since it's always QUALITY_ONE + MPTAmount const actualOut = maxSrcToDst; + cache_.emplace(in, maxSrcToDst, actualOut, srcDebtDir); + + auto const ter = directSendNoFee( + sb, + src_, + dst_, + toSTAmount(maxSrcToDst, srcToDstIss), + /*checkIssuer*/ false, + j_); + if (!isTesSuccess(ter)) + { + JLOG(j_.trace()) << "MPTEndpointStep::rev: error " << ter; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + JLOG(j_.trace()) << "MPTEndpointStep::rev: Limiting" + << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) + << " srcToDst: " << to_string(maxSrcToDst) << " out: " << to_string(out); + return {in, actualOut}; +} + +// The forward pass should never have more liquidity than the reverse +// pass. But sometimes rounding differences cause the forward pass to +// deliver more liquidity. Use the cached values from the reverse pass +// to prevent this. +template +void +MPTEndpointStep::setCacheLimiting( + MPTAmount const& fwdIn, + MPTAmount const& fwdSrcToDst, + MPTAmount const& fwdOut, + DebtDirection srcDebtDir) +{ + if (cache_->in < fwdIn) + { + MPTAmount const smallDiff(1); + auto const diff = fwdIn - cache_->in; + if (diff > smallDiff) + { + if (!cache_->in.value() || + (Number(fwdIn.value()) / Number(cache_->in.value())) > Number(101, -2)) + { + // Detect large diffs on forward pass so they may be + // investigated + JLOG(j_.warn()) << "MPTEndpointStep::fwd: setCacheLimiting" + << " fwdIn: " << to_string(fwdIn) + << " cacheIn: " << to_string(cache_->in) + << " fwdSrcToDst: " << to_string(fwdSrcToDst) + << " cacheSrcToDst: " << to_string(cache_->srcToDst) + << " fwdOut: " << to_string(fwdOut) + << " cacheOut: " << to_string(cache_->out); + cache_.emplace(fwdIn, fwdSrcToDst, fwdOut, srcDebtDir); + return; + } + } + } + cache_->in = fwdIn; + if (fwdSrcToDst < cache_->srcToDst) + cache_->srcToDst = fwdSrcToDst; + if (fwdOut < cache_->out) + cache_->out = fwdOut; + cache_->srcDebtDir = srcDebtDir; +}; + +template +std::pair +MPTEndpointStep::fwdImp( + PaymentSandbox& sb, + ApplyView& /*afView*/, + boost::container::flat_set& /*ofrsToRm*/, + MPTAmount const& in) +{ + XRPL_ASSERT(cache_, "MPTEndpointStep::fwdImp : valid cache"); + + auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxPaymentFlow(sb); + + auto const [srcQOut, dstQIn] = qualities(sb, srcDebtDir, StrandDirection::forward); + (void)dstQIn; + + MPTIssue const srcToDstIss(mptIssue_); + + JLOG(j_.trace()) << "MPTEndpointStep::fwd" + << " srcRedeems: " << redeems(srcDebtDir) << " inReq: " << to_string(in) + << " maxSrcToDst: " << to_string(maxSrcToDst) << " srcQOut: " << srcQOut + << " dstQIn: " << dstQIn; + + if (maxSrcToDst.signum() <= 0) + { + JLOG(j_.trace()) << "MPTEndpointStep::fwd: dry"; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + + if (auto const err = static_cast(this)->checkCreateMPT(sb, srcDebtDir); + !isTesSuccess(err)) + return {beast::zero, beast::zero}; + + MPTAmount const srcToDst = mulRatio(in, QUALITY_ONE, srcQOut, /*roundUp*/ false); + + if (srcToDst <= maxSrcToDst) + { + // Don't have to factor in dstQIn since it's always QUALITY_ONE + MPTAmount const out = srcToDst; + setCacheLimiting(in, srcToDst, out, srcDebtDir); + auto const ter = directSendNoFee( + sb, + src_, + dst_, + toSTAmount(cache_->srcToDst, srcToDstIss), + /*checkIssuer*/ false, + j_); + if (!isTesSuccess(ter)) + { + JLOG(j_.trace()) << "MPTEndpointStep::fwd: error " << ter; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + JLOG(j_.trace()) << "MPTEndpointStep::fwd: Non-limiting" + << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(in) + << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out); + } + else + { + // limiting node + MPTAmount const actualIn = mulRatio(maxSrcToDst, srcQOut, QUALITY_ONE, /*roundUp*/ true); + // Don't have to factor in dstQIn since it's always QUALITY_ONE + MPTAmount const out = maxSrcToDst; + setCacheLimiting(actualIn, maxSrcToDst, out, srcDebtDir); + auto const ter = directSendNoFee( + sb, + src_, + dst_, + toSTAmount(cache_->srcToDst, srcToDstIss), + /*checkIssuer*/ false, + j_); + if (!isTesSuccess(ter)) + { + JLOG(j_.trace()) << "MPTEndpointStep::fwd: error " << ter; + resetCache(srcDebtDir); + return {beast::zero, beast::zero}; + } + JLOG(j_.trace()) << "MPTEndpointStep::fwd: Limiting" + << " srcRedeems: " << redeems(srcDebtDir) << " in: " << to_string(actualIn) + << " srcToDst: " << to_string(srcToDst) << " out: " << to_string(out); + } + return {cache_->in, cache_->out}; +} + +template +std::pair +MPTEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, EitherAmount const& in) +{ + if (!cache_) + { + JLOG(j_.trace()) << "Expected valid cache in validFwd"; + return {false, EitherAmount(MPTAmount(beast::zero))}; + } + + auto const savCache = *cache_; + + XRPL_ASSERT(in.holds(), "MPTEndpoint::validFwd : is MPT"); + + auto const [maxSrcToDst, srcDebtDir] = static_cast(this)->maxPaymentFlow(sb); + (void)srcDebtDir; + + try + { + boost::container::flat_set dummy; + fwdImp(sb, afView, dummy, in.get()); // changes cache + } + catch (FlowException const&) + { + return {false, EitherAmount(MPTAmount(beast::zero))}; + } + + if (maxSrcToDst < cache_->srcToDst) + { + JLOG(j_.warn()) << "MPTEndpointStep: Strand re-execute check failed." + << " Exceeded max src->dst limit" + << " max src->dst: " << to_string(maxSrcToDst) + << " actual src->dst: " << to_string(cache_->srcToDst); + return {false, EitherAmount(cache_->out)}; + } + + if (!(checkNear(savCache.in, cache_->in) && checkNear(savCache.out, cache_->out))) + { + JLOG(j_.warn()) << "MPTEndpointStep: Strand re-execute check failed." + << " ExpectedIn: " << to_string(savCache.in) + << " CachedIn: " << to_string(cache_->in) + << " ExpectedOut: " << to_string(savCache.out) + << " CachedOut: " << to_string(cache_->out); + return {false, EitherAmount(cache_->out)}; + } + return {true, EitherAmount(cache_->out)}; +} + +// Returns srcQOut, dstQIn +template +std::pair +MPTEndpointStep::qualitiesSrcRedeems(ReadView const& sb) const +{ + if (prevStep_ == nullptr) + return {QUALITY_ONE, QUALITY_ONE}; + + auto const prevStepQIn = prevStep_->lineQualityIn(sb); + // Unlike trustline MPT doesn't have line quality field + auto srcQOut = QUALITY_ONE; + + srcQOut = std::max(prevStepQIn, srcQOut); + return {srcQOut, QUALITY_ONE}; +} + +// Returns srcQOut, dstQIn +template +std::pair +MPTEndpointStep::qualitiesSrcIssues( + ReadView const& sb, + DebtDirection prevStepDebtDirection) const +{ + // Charge a transfer rate when issuing and previous step redeems + + XRPL_ASSERT( + static_cast(this)->verifyPrevStepDebtDirection(prevStepDebtDirection), + "MPTEndpointStep::qualitiesSrcIssues : verify prev step debt " + "direction"); + + std::uint32_t const srcQOut = + redeems(prevStepDebtDirection) ? transferRate(sb, mptIssue_.getMptID()).value : QUALITY_ONE; + + // Unlike trustline, MPT doesn't have line quality field + return {srcQOut, QUALITY_ONE}; +} + +// Returns srcQOut, dstQIn +template +std::pair +MPTEndpointStep::qualities( + ReadView const& sb, + DebtDirection srcDebtDir, + StrandDirection strandDir) const +{ + if (redeems(srcDebtDir)) + { + return qualitiesSrcRedeems(sb); + } + + auto const prevStepDebtDirection = [&] { + if (prevStep_ != nullptr) + return prevStep_->debtDirection(sb, strandDir); + return DebtDirection::issues; + }(); + return qualitiesSrcIssues(sb, prevStepDebtDirection); +} + +template +std::uint32_t +MPTEndpointStep::lineQualityIn(ReadView const& v) const +{ + // dst quality in + return QUALITY_ONE; +} + +template +std::pair, DebtDirection> +MPTEndpointStep::qualityUpperBound(ReadView const& v, DebtDirection prevStepDir) const +{ + auto const dir = this->debtDirection(v, StrandDirection::forward); + + auto const [srcQOut, dstQIn] = + redeems(dir) ? qualitiesSrcRedeems(v) : qualitiesSrcIssues(v, prevStepDir); + (void)dstQIn; + + MPTIssue const iss{mptIssue_}; + // Be careful not to switch the parameters to `getRate`. The + // `getRate(offerOut, offerIn)` function is usually used for offers. It + // returns offerIn/offerOut. For a direct step, the rate is srcQOut/dstQIn + // (Input*dstQIn/srcQOut = Output; So rate = srcQOut/dstQIn). Although the + // first parameter is called `offerOut`, it should take the `dstQIn` + // variable. + return {Quality(getRate(STAmount(iss, QUALITY_ONE), STAmount(iss, srcQOut))), dir}; +} + +template +TER +MPTEndpointStep::check(StrandContext const& ctx) const +{ + // The following checks apply for both payments and offer crossing. + if (!src_ || !dst_) + { + JLOG(j_.debug()) << "MPTEndpointStep: specified bad account."; + return temBAD_PATH; + } + + if (src_ == dst_) + { + JLOG(j_.debug()) << "MPTEndpointStep: same src and dst."; + return temBAD_PATH; + } + + auto const sleSrc = ctx.view.read(keylet::account(src_)); + if (!sleSrc) + { + JLOG(j_.warn()) << "MPTEndpointStep: can't receive MPT from non-existent issuer: " << src_; + return terNO_ACCOUNT; + } + + // pure issue/redeem can't be frozen (issuer/holder) + if (!(ctx.isLast && ctx.isFirst)) + { + auto const& account = ctx.isFirst ? src_ : dst_; + if (isFrozen(ctx.view, account, mptIssue_)) + return terLOCKED; + } + + if (ctx.seenBookOuts.count(mptIssue_) > 0) + { + if (ctx.prevStep == nullptr) + { + UNREACHABLE( + "xrpl::MPTEndpointStep::check : prev seen book without a " + "prev step"); + return temBAD_PATH_LOOP; + } + + // This is OK if the previous step is a book step that outputs this + // issue + if (auto book = ctx.prevStep->bookStepBook()) + { + if (book->out.get() != mptIssue_) + return temBAD_PATH_LOOP; + } + } + + if ((ctx.isFirst && !ctx.seenDirectAssets[0].insert(mptIssue_).second) || + (ctx.isLast && !ctx.seenDirectAssets[1].insert(mptIssue_).second)) + { + JLOG(j_.debug()) << "MPTEndpointStep: loop detected: Index: " << ctx.strandSize << ' ' + << *this; + return temBAD_PATH_LOOP; + } + + // MPT can only be an endpoint + if (!ctx.isLast && !ctx.isFirst) + { + JLOG(j_.warn()) << "MPTEndpointStep: MPT can only be an endpoint"; + return temBAD_PATH; + } + + auto const& issuer = mptIssue_.getIssuer(); + if ((src_ != issuer && dst_ != issuer) || (src_ == issuer && dst_ == issuer)) + { + JLOG(j_.warn()) << "MPTEndpointStep: invalid src/dst"; + return temBAD_PATH; + } + + return static_cast(this)->check(ctx, sleSrc); +} + +template +void +MPTEndpointStep::resetCache(xrpl::DebtDirection dir) +{ + cache_.emplace(MPTAmount(beast::zero), MPTAmount(beast::zero), MPTAmount(beast::zero), dir); +} + +//------------------------------------------------------------------------------ + +std::pair> +make_MPTEndpointStep( + StrandContext const& ctx, + AccountID const& src, + AccountID const& dst, + MPTID const& mpt) +{ + TER ter = tefINTERNAL; + std::unique_ptr r; + if (ctx.offerCrossing != OfferCrossing::no) + { + auto offerCrossingStep = std::make_unique(ctx, src, dst, mpt); + ter = offerCrossingStep->check(ctx); + r = std::move(offerCrossingStep); + } + else // payment + { + auto paymentStep = std::make_unique(ctx, src, dst, mpt); + ter = paymentStep->check(ctx); + r = std::move(paymentStep); + } + if (!isTesSuccess(ter)) + return {ter, nullptr}; + + return {tesSUCCESS, std::move(r)}; +} + +namespace test { +// Needed for testing +bool +mptEndpointStepEqual( + Step const& step, + AccountID const& src, + AccountID const& dst, + MPTID const& mptid) +{ + if (auto ds = dynamic_cast const*>(&step)) + { + return ds->src() == src && ds->dst() == dst && ds->mptID() == mptid; + } + return false; +} +} // namespace test + +} // namespace xrpl diff --git a/src/libxrpl/tx/paths/OfferStream.cpp b/src/libxrpl/tx/paths/OfferStream.cpp index 411b5cb05b..929140cd61 100644 --- a/src/libxrpl/tx/paths/OfferStream.cpp +++ b/src/libxrpl/tx/paths/OfferStream.cpp @@ -1,5 +1,6 @@ #include #include +#include #include #include #include @@ -13,14 +14,15 @@ namespace { bool checkIssuers(ReadView const& view, Book const& book) { - auto issuerExists = [](ReadView const& view, Issue const& iss) -> bool { - return isXRP(iss.account) || view.read(keylet::account(iss.account)); + auto issuerExists = [](ReadView const& view, Asset const& asset) -> bool { + auto const& issuer = asset.getIssuer(); + return isXRP(issuer) || view.exists(keylet::account(issuer)); }; return issuerExists(view, book.in) && issuerExists(view, book.out); } } // namespace -template +template TOfferStreamBase::TOfferStreamBase( ApplyView& view, ApplyView& cancelView, @@ -42,7 +44,7 @@ TOfferStreamBase::TOfferStreamBase( // Handle the case where a directory item with no corresponding ledger entry // is found. This shouldn't happen but if it does we clean it up. -template +template void TOfferStreamBase::erase(ApplyView& view) { @@ -75,67 +77,42 @@ TOfferStreamBase::erase(ApplyView& view) << tip_.dir(); } -static STAmount +template +static T accountFundsHelper( ReadView const& view, AccountID const& id, - STAmount const& saDefault, - Issue const&, + T const& amtDefault, + Asset const& asset, FreezeHandling freezeHandling, + AuthHandling authHandling, beast::Journal j) { - return accountFunds(view, id, saDefault, freezeHandling, j); -} - -static IOUAmount -accountFundsHelper( - ReadView const& view, - AccountID const& id, - IOUAmount const& amtDefault, - Issue const& issue, - FreezeHandling freezeHandling, - beast::Journal j) -{ - if (issue.account == id) + if constexpr (std::is_same_v) { - // self funded - return amtDefault; + if (id == asset.getIssuer()) + { + // self funded + return amtDefault; + } + } + else if constexpr (std::is_same_v) + { + if (id == asset.getIssuer()) + { + return toAmount(issuerFundsToSelfIssue(view, asset.get())); + } } - return toAmount( - accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); + return toAmount(accountHolds(view, id, asset, freezeHandling, authHandling, j)); } -static XRPAmount -accountFundsHelper( - ReadView const& view, - AccountID const& id, - XRPAmount const& amtDefault, - Issue const& issue, - FreezeHandling freezeHandling, - beast::Journal j) -{ - return toAmount( - accountHolds(view, id, issue.currency, issue.account, freezeHandling, j)); -} - -template +template template + requires ValidTaker bool TOfferStreamBase::shouldRmSmallIncreasedQOffer() const { - static_assert( - std::is_same_v || std::is_same_v, - "STAmount is not supported"); - - static_assert( - std::is_same_v || std::is_same_v, - "STAmount is not supported"); - - static_assert( - !std::is_same_v || !std::is_same_v, - "Cannot have XRP/XRP offers"); - // Consider removing the offer if: // o `TakerPays` is XRP (because of XRP drops granularity) or // o `TakerPays` and `TakerGets` are both IOU and `TakerPays`<`TakerGets` @@ -156,14 +133,14 @@ TOfferStreamBase::shouldRmSmallIncreasedQOffer() const if constexpr (!inIsXRP && !outIsXRP) { - if (ofrAmts.in >= ofrAmts.out) + if (Number(ofrAmts.in) >= Number(ofrAmts.out)) return false; } TTakerGets const ownerFunds = toAmount(*ownerFunds_); auto const effectiveAmounts = [&] { - if (offer_.owner() != offer_.issueOut().account && ownerFunds < ofrAmts.out) + if (offer_.owner() != offer_.assetOut().getIssuer() && ownerFunds < ofrAmts.out) { // adjust the amounts by owner funds. // @@ -185,7 +162,7 @@ TOfferStreamBase::shouldRmSmallIncreasedQOffer() const return effectiveQuality < offer_.quality(); } -template +template bool TOfferStreamBase::step() { @@ -240,9 +217,7 @@ TOfferStreamBase::step() continue; } - bool const deepFrozen = isDeepFrozen( - view_, offer_.owner(), offer_.issueIn().currency, offer_.issueIn().account); - if (deepFrozen) + if (isDeepFrozen(view_, offer_.owner(), offer_.assetIn())) { JLOG(j_.trace()) << "Removing deep frozen unfunded offer " << entry->key(); permRmOffer(entry->key()); @@ -262,7 +237,13 @@ TOfferStreamBase::step() // Calculate owner funds ownerFunds_ = accountFundsHelper( - view_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + view_, + offer_.owner(), + amount.out, + offer_.assetOut(), + fhZERO_IF_FROZEN, + ahZERO_IF_UNAUTHORIZED, + j_); // Check for unfunded offer if (*ownerFunds_ <= beast::zero) @@ -271,7 +252,13 @@ TOfferStreamBase::step() // we haven't modified the balance and therefore the // offer is "found unfunded" versus "became unfunded" auto const original_funds = accountFundsHelper( - cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + cancelView_, + offer_.owner(), + amount.out, + offer_.assetOut(), + fhZERO_IF_FROZEN, + ahZERO_IF_UNAUTHORIZED, + j_); if (original_funds == *ownerFunds_) { @@ -287,44 +274,16 @@ TOfferStreamBase::step() continue; } - bool const rmSmallIncreasedQOffer = [&] { - bool const inIsXRP = isXRP(offer_.issueIn()); - bool const outIsXRP = isXRP(offer_.issueOut()); - if (inIsXRP && !outIsXRP) - { - // Without the `if constexpr`, the - // `shouldRmSmallIncreasedQOffer` template will be instantiated - // even if it is never used. This can cause compiler errors in - // some cases, hence the `if constexpr` guard. - // Note that TIn can be XRPAmount or STAmount, and TOut can be - // IOUAmount or STAmount. - if constexpr (!(std::is_same_v || std::is_same_v)) - return shouldRmSmallIncreasedQOffer(); - } - if (!inIsXRP && outIsXRP) - { - // See comment above for `if constexpr` rationale - if constexpr (!(std::is_same_v || std::is_same_v)) - return shouldRmSmallIncreasedQOffer(); - } - if (!inIsXRP && !outIsXRP) - { - // See comment above for `if constexpr` rationale - if constexpr (!(std::is_same_v || std::is_same_v)) - return shouldRmSmallIncreasedQOffer(); - } - // LCOV_EXCL_START - UNREACHABLE( - "xrpl::TOfferStreamBase::step::rmSmallIncreasedQOffer : XRP " - "vs XRP offer"); - return false; - // LCOV_EXCL_STOP - }(); - - if (rmSmallIncreasedQOffer) + if (shouldRmSmallIncreasedQOffer()) { auto const original_funds = accountFundsHelper( - cancelView_, offer_.owner(), amount.out, offer_.issueOut(), fhZERO_IF_FROZEN, j_); + cancelView_, + offer_.owner(), + amount.out, + offer_.assetOut(), + fhZERO_IF_FROZEN, + ahZERO_IF_UNAUTHORIZED, + j_); if (original_funds == *ownerFunds_) { @@ -348,26 +307,28 @@ TOfferStreamBase::step() return true; } -void -OfferStream::permRmOffer(uint256 const& offerIndex) -{ - offerDelete(cancelView_, cancelView_.peek(keylet::offer(offerIndex)), j_); -} - -template +template void FlowOfferStream::permRmOffer(uint256 const& offerIndex) { permToRemove_.insert(offerIndex); } -template class FlowOfferStream; template class FlowOfferStream; template class FlowOfferStream; template class FlowOfferStream; +template class FlowOfferStream; +template class FlowOfferStream; +template class FlowOfferStream; +template class FlowOfferStream; +template class FlowOfferStream; -template class TOfferStreamBase; template class TOfferStreamBase; template class TOfferStreamBase; template class TOfferStreamBase; +template class TOfferStreamBase; +template class TOfferStreamBase; +template class TOfferStreamBase; +template class TOfferStreamBase; +template class TOfferStreamBase; } // namespace xrpl diff --git a/src/libxrpl/tx/paths/PaySteps.cpp b/src/libxrpl/tx/paths/PaySteps.cpp index 33b63f7714..5a68228708 100644 --- a/src/libxrpl/tx/paths/PaySteps.cpp +++ b/src/libxrpl/tx/paths/PaySteps.cpp @@ -32,12 +32,6 @@ checkNear(IOUAmount const& expected, IOUAmount const& actual) return r <= ratTol; }; -bool -checkNear(XRPAmount const& expected, XRPAmount const& actual) -{ - return expected == actual; -}; - static bool isXRPAccount(STPathElement const& pe) { @@ -51,12 +45,12 @@ toStep( StrandContext const& ctx, STPathElement const* e1, STPathElement const* e2, - Issue const& curIssue) + Asset const& curAsset) { auto& j = ctx.j; if (ctx.isFirst && e1->isAccount() && - ((e1->getNodeType() & STPathElement::typeCurrency) != 0u) && isXRP(e1->getCurrency())) + ((e1->getNodeType() & STPathElement::typeCurrency) != 0u) && e1->getPathAsset().isXRP()) { return make_XRPEndpointStep(ctx, e1->getAccountID()); } @@ -64,9 +58,32 @@ toStep( if (ctx.isLast && isXRPAccount(*e1) && e2->isAccount()) return make_XRPEndpointStep(ctx, e2->getAccountID()); + // MPTEndpointStep is created in following cases: + // 1 Direct payment between an issuer and a holder + // e1 is issuer and e2 is holder or vise versa + // There is only one step in this case: holder->issuer or + // issuer->holder + // 2 Direct payment between the holders + // e1 is issuer and e2 is holder or vise versa + // There are two steps in this case: holder->issuer->holder1 + // 3 Cross-token payment with Amount or SendMax or both MPT + // If destination is an issuer then the last step is BookStep, + // otherwise the last step is MPTEndpointStep where e1 is + // the issuer and e2 is the holder. + // In all cases MPTEndpointStep is always first or last step, + // e1/e2 are always account types, and curAsset is always MPT. + if (e1->isAccount() && e2->isAccount()) { - return make_DirectStepI(ctx, e1->getAccountID(), e2->getAccountID(), curIssue.currency); + return curAsset.visit( + [&](MPTIssue const& issue) { + return make_MPTEndpointStep( + ctx, e1->getAccountID(), e2->getAccountID(), issue.getMptID()); + }, + [&](Issue const& issue) { + return make_DirectStepI( + ctx, e1->getAccountID(), e2->getAccountID(), issue.currency); + }); } if (e1->isOffer() && e2->isAccount()) @@ -80,17 +97,16 @@ toStep( } XRPL_ASSERT( - (e2->getNodeType() & STPathElement::typeCurrency) || + (e2->getNodeType() & STPathElement::typeAsset) || (e2->getNodeType() & STPathElement::typeIssuer), "xrpl::toStep : currency or issuer"); - auto const outCurrency = ((e2->getNodeType() & STPathElement::typeCurrency) != 0u) - ? e2->getCurrency() - : curIssue.currency; + PathAsset const outAsset = + ((e2->getNodeType() & STPathElement::typeAsset) != 0u) ? e2->getPathAsset() : curAsset; auto const outIssuer = ((e2->getNodeType() & STPathElement::typeIssuer) != 0u) ? e2->getIssuerID() - : curIssue.account; + : curAsset.getIssuer(); - if (isXRP(curIssue.currency) && isXRP(outCurrency)) + if (isXRP(curAsset) && outAsset.isXRP()) { JLOG(j.info()) << "Found xrp/xrp offer payment step"; return {temBAD_PATH, std::unique_ptr{}}; @@ -98,13 +114,35 @@ toStep( XRPL_ASSERT(e2->isOffer(), "xrpl::toStep : is offer"); - if (isXRP(outCurrency)) - return make_BookStepIX(ctx, curIssue); + if (outAsset.isXRP()) + { + return curAsset.visit( + [&](MPTIssue const& issue) { return make_BookStepMX(ctx, issue); }, + [&](Issue const& issue) { return make_BookStepIX(ctx, issue); }); + } - if (isXRP(curIssue.currency)) - return make_BookStepXI(ctx, {outCurrency, outIssuer}); + if (isXRP(curAsset)) + { + return outAsset.visit( + [&](MPTID const& mpt) { return make_BookStepXM(ctx, mpt); }, + [&](Currency const& currency) { return make_BookStepXI(ctx, {currency, outIssuer}); }); + } - return make_BookStepII(ctx, curIssue, {outCurrency, outIssuer}); + return curAsset.visit( + [&](MPTIssue const& issue) { + return outAsset.visit( + [&](Currency const& currency) { + return make_BookStepMI(ctx, issue, {currency, outIssuer}); + }, + [&](MPTID const& mpt) { return make_BookStepMM(ctx, issue, mpt); }); + }, + [&](Issue const& issue) { + return outAsset.visit( + [&](MPTID const& mpt) { return make_BookStepIM(ctx, issue, mpt); }, + [&](Currency const& currency) { + return make_BookStepII(ctx, issue, {currency, outIssuer}); + }); + }); } std::pair @@ -112,9 +150,9 @@ toStrand( ReadView const& view, AccountID const& src, AccountID const& dst, - Issue const& deliver, + Asset const& deliver, std::optional const& limitQuality, - std::optional const& sendMaxIssue, + std::optional const& sendMaxAsset, STPath const& path, bool ownerPaysTransferFee, OfferCrossing offerCrossing, @@ -123,15 +161,21 @@ toStrand( beast::Journal j) { if (isXRP(src) || isXRP(dst) || !isConsistent(deliver) || - (sendMaxIssue && !isConsistent(*sendMaxIssue))) + (sendMaxAsset && !isConsistent(*sendMaxAsset))) return {temBAD_PATH, Strand{}}; - if ((sendMaxIssue && sendMaxIssue->account == noAccount()) || (src == noAccount()) || - (dst == noAccount()) || (deliver.account == noAccount())) + if ((sendMaxAsset && sendMaxAsset->getIssuer() == noAccount()) || (src == noAccount()) || + (dst == noAccount()) || (deliver.getIssuer() == noAccount())) return {temBAD_PATH, Strand{}}; - for (auto const& pe : path) + if ((deliver.holds() && deliver.getIssuer() == beast::zero) || + (sendMaxAsset && sendMaxAsset->holds() && + sendMaxAsset->getIssuer() == beast::zero)) + return {temBAD_PATH, Strand{}}; + + for (std::size_t i = 0; i < path.size(); ++i) { + auto const& pe = path[i]; auto const t = pe.getNodeType(); if (((t & ~STPathElement::typeAll) != 0u) || (t == 0u)) @@ -140,6 +184,8 @@ toStrand( bool const hasAccount = (t & STPathElement::typeAccount) != 0u; bool const hasIssuer = (t & STPathElement::typeIssuer) != 0u; bool const hasCurrency = (t & STPathElement::typeCurrency) != 0u; + bool const hasMPT = (t & STPathElement::typeMPT) != 0u; + bool const hasAsset = (t & STPathElement::typeAsset) != 0u; if (hasAccount && (hasIssuer || hasCurrency)) return {temBAD_PATH, Strand{}}; @@ -158,17 +204,33 @@ toStrand( if (hasAccount && (pe.getAccountID() == noAccount())) return {temBAD_PATH, Strand{}}; + + if (hasMPT && (hasCurrency || hasAccount)) + return {temBAD_PATH, Strand{}}; + + if (hasMPT && hasIssuer && (pe.getIssuerID() != getMPTIssuer(pe.getMPTID()))) + return {temBAD_PATH, Strand{}}; + + // No rippling if MPT + if (i > 0 && path[i - 1].hasMPT() && (hasAccount || (hasIssuer && !hasAsset))) + return {temBAD_PATH, Strand{}}; } - Issue curIssue = [&] { - auto const& currency = sendMaxIssue ? sendMaxIssue->currency : deliver.currency; - if (isXRP(currency)) - return xrpIssue(); - return Issue{currency, src}; + Asset curAsset = [&]() -> Asset { + auto const& asset = sendMaxAsset ? *sendMaxAsset : deliver; + return asset.visit( + [&](MPTIssue const& issue) -> Asset { return asset; }, + [&](Issue const& issue) -> Asset { + if (isXRP(asset)) + return xrpIssue(); + // First step ripples from the source to the issuer. + return Issue{issue.currency, src}; + }); }(); - auto hasCurrency = [](STPathElement const pe) { - return pe.getNodeType() & STPathElement::typeCurrency; + // Currency or MPT + auto hasAsset = [](STPathElement const pe) { + return pe.getNodeType() & STPathElement::typeAsset; }; std::vector normPath; @@ -176,13 +238,28 @@ toStrand( // sendmax and deliver. normPath.reserve(4 + path.size()); { - normPath.emplace_back(STPathElement::typeAll, src, curIssue.currency, curIssue.account); + // The first step of a path is always implied to be the sender of the + // transaction, as defined by the transaction's Account field. The Asset + // is either SendMax or Deliver. + auto const t = [&]() { + auto const t = STPathElement::typeAccount | STPathElement::typeIssuer; + return curAsset.visit( + [&](MPTIssue const&) { return t | STPathElement::typeMPT; }, + [&](Issue const&) { return t | STPathElement::typeCurrency; }); + }(); + // If MPT then the issuer is the actual issuer, it is never the source + // account. + normPath.emplace_back(t, src, curAsset, curAsset.getIssuer()); - if (sendMaxIssue && sendMaxIssue->account != src && + // If transaction includes SendMax with the issuer, which is not + // the sender of the transaction, that issuer is implied to be + // the second step of the path. Unless the path starts at an address, + // which is the issuer of SendMax. + if (sendMaxAsset && sendMaxAsset->getIssuer() != src && (path.empty() || !path[0].isAccount() || - path[0].getAccountID() != sendMaxIssue->account)) + path[0].getAccountID() != sendMaxAsset->getIssuer())) { - normPath.emplace_back(sendMaxIssue->account, std::nullopt, std::nullopt); + normPath.emplace_back(sendMaxAsset->getIssuer(), std::nullopt, std::nullopt); } for (auto const& i : path) @@ -190,22 +267,32 @@ toStrand( { // Note that for offer crossing (only) we do use an offer book - // even if all that is changing is the Issue.account. - STPathElement const& lastCurrency = - *std::find_if(normPath.rbegin(), normPath.rend(), hasCurrency); - if ((lastCurrency.getCurrency() != deliver.currency) || - ((offerCrossing != 0u) && lastCurrency.getIssuerID() != deliver.account)) + // even if all that is changing is the Issue.account. Note + // that MPTIssue can't change the account. + STPathElement const& lastAsset = + *std::find_if(normPath.rbegin(), normPath.rend(), hasAsset); + if (lastAsset.getPathAsset() != deliver || + (offerCrossing != OfferCrossing::no && + lastAsset.getIssuerID() != deliver.getIssuer())) { - normPath.emplace_back(std::nullopt, deliver.currency, deliver.account); + normPath.emplace_back(std::nullopt, deliver, deliver.getIssuer()); } } - if (!((normPath.back().isAccount() && normPath.back().getAccountID() == deliver.account) || - (dst == deliver.account))) + // If the Amount field of the transaction includes an issuer that is not + // the same as the Destination of the transaction, that issuer is + // implied to be the second-to-last step of the path. If normPath.back + // is an offer, which sells MPT then the added path element account is + // the MPT's issuer. + if (!((normPath.back().isAccount() && + normPath.back().getAccountID() == deliver.getIssuer()) || + (dst == deliver.getIssuer()))) { - normPath.emplace_back(deliver.account, std::nullopt, std::nullopt); + normPath.emplace_back(deliver.getIssuer(), std::nullopt, std::nullopt); } + // Last step of a path is always implied to be the receiver of a + // transaction, as defined by the transaction's Destination field. if (!normPath.back().isAccount() || normPath.back().getAccountID() != dst) { normPath.emplace_back(dst, std::nullopt, std::nullopt); @@ -227,11 +314,11 @@ toStrand( at most twice: once as a src and once as a dst (hence the two element array). The strandSrc and strandDst will only show up once each. */ - std::array, 2> seenDirectIssues; + std::array, 2> seenDirectAssets; // A strand may not include the same offer book more than once - boost::container::flat_set seenBookOuts; - seenDirectIssues[0].reserve(normPath.size()); - seenDirectIssues[1].reserve(normPath.size()); + boost::container::flat_set seenBookOuts; + seenDirectAssets[0].reserve(normPath.size()); + seenDirectAssets[1].reserve(normPath.size()); seenBookOuts.reserve(normPath.size()); auto ctx = [&](bool isLast = false) { return StrandContext{ @@ -245,7 +332,7 @@ toStrand( ownerPaysTransferFee, offerCrossing, isDefaultPath, - seenDirectIssues, + seenDirectAssets, seenBookOuts, ammContext, domainID, @@ -265,58 +352,96 @@ toStrand( auto cur = &normPath[i]; auto const next = &normPath[i + 1]; - if (cur->isAccount()) + // Switch over from MPT to Currency. In this case curAsset account + // can be different from the issuer. If cur is MPT then curAsset + // is just set to MPTID. + if (curAsset.holds() && cur->hasCurrency()) { - curIssue.account = cur->getAccountID(); - } - else if (cur->hasIssuer()) - { - curIssue.account = cur->getIssuerID(); + curAsset = Issue{}; } + // Can only update the account for Issue since MPTIssue's account + // is immutable as it is part of MPTID. + curAsset.visit( + [&](Issue const&) { + if (cur->isAccount()) + { + curAsset.get().account = cur->getAccountID(); + } + else if (cur->hasIssuer()) + { + curAsset.get().account = cur->getIssuerID(); + } + }, + [](MPTIssue const&) {}); + if (cur->hasCurrency()) { - curIssue.currency = cur->getCurrency(); - if (isXRP(curIssue.currency)) - curIssue.account = xrpAccount(); + curAsset = Issue{cur->getCurrency(), curAsset.getIssuer()}; + if (isXRP(curAsset)) + curAsset.get().account = xrpAccount(); } + else if (cur->hasMPT()) + { + curAsset = cur->getPathAsset().get(); + } + + using ImpliedStepRet = std::pair>; + auto getImpliedStep = [&](AccountID const& src_, + AccountID const& dst_, + Asset const& asset_) -> ImpliedStepRet { + return asset_.visit( + [&](MPTIssue const&) -> ImpliedStepRet { + JLOG(j.error()) << "MPT is invalid with rippling"; + return {temBAD_PATH, nullptr}; + }, + [&](Issue const& issue) -> ImpliedStepRet { + return make_DirectStepI(ctx(), src_, dst_, issue.currency); + }); + }; if (cur->isAccount() && next->isAccount()) { - if (!isXRP(curIssue.currency) && curIssue.account != cur->getAccountID() && - curIssue.account != next->getAccountID()) + // This block doesn't execute + // since curAsset's account is set to cur's account above. + // It should not execute for MPT either because MPT rippling + // is invalid. Should this block be removed/amendment excluded? + if (!isXRP(curAsset) && curAsset.getIssuer() != cur->getAccountID() && + curAsset.getIssuer() != next->getAccountID()) { JLOG(j.trace()) << "Inserting implied account"; - auto msr = make_DirectStepI( - ctx(), cur->getAccountID(), curIssue.account, curIssue.currency); + auto msr = getImpliedStep(cur->getAccountID(), curAsset.getIssuer(), curAsset); if (!isTesSuccess(msr.first)) return {msr.first, Strand{}}; result.push_back(std::move(msr.second)); impliedPE.emplace( - STPathElement::typeAccount, curIssue.account, xrpCurrency(), xrpAccount()); + STPathElement::typeAccount, curAsset.getIssuer(), xrpCurrency(), xrpAccount()); cur = &*impliedPE; } } else if (cur->isAccount() && next->isOffer()) { - if (curIssue.account != cur->getAccountID()) + // Same as above, this block doesn't execute. + if (curAsset.getIssuer() != cur->getAccountID()) { JLOG(j.trace()) << "Inserting implied account before offer"; - auto msr = make_DirectStepI( - ctx(), cur->getAccountID(), curIssue.account, curIssue.currency); + auto msr = getImpliedStep(cur->getAccountID(), curAsset.getIssuer(), curAsset); if (!isTesSuccess(msr.first)) return {msr.first, Strand{}}; result.push_back(std::move(msr.second)); impliedPE.emplace( - STPathElement::typeAccount, curIssue.account, xrpCurrency(), xrpAccount()); + STPathElement::typeAccount, curAsset.getIssuer(), xrpCurrency(), xrpAccount()); cur = &*impliedPE; } } else if (cur->isOffer() && next->isAccount()) { - if (curIssue.account != next->getAccountID() && !isXRP(next->getAccountID())) + // If the offer sells MPT, then next's account is always the issuer. + // See how normPath step is added for second-to-last or last + // step. Therefore, this block never executes if MPT. + if (curAsset.getIssuer() != next->getAccountID() && !isXRP(next->getAccountID())) { - if (isXRP(curIssue)) + if (isXRP(curAsset)) { if (i != normPath.size() - 2) return {temBAD_PATH, Strand{}}; @@ -330,8 +455,7 @@ toStrand( else { JLOG(j.trace()) << "Inserting implied account after offer"; - auto msr = make_DirectStepI( - ctx(), curIssue.account, next->getAccountID(), curIssue.currency); + auto msr = getImpliedStep(curAsset.getIssuer(), next->getAccountID(), curAsset); if (!isTesSuccess(msr.first)) return {msr.first, Strand{}}; result.push_back(std::move(msr.second)); @@ -340,7 +464,7 @@ toStrand( continue; } - if (!next->isOffer() && next->hasCurrency() && next->getCurrency() != curIssue.currency) + if (!next->isOffer() && next->hasAsset() && next->getPathAsset() != curAsset) { // Should never happen // LCOV_EXCL_START @@ -349,7 +473,7 @@ toStrand( // LCOV_EXCL_STOP } - auto s = toStep(ctx(/*isLast*/ i == normPath.size() - 2), cur, next, curIssue); + auto s = toStep(ctx(/*isLast*/ i == normPath.size() - 2), cur, next, curAsset); if (isTesSuccess(s.first)) { result.emplace_back(std::move(s.second)); @@ -366,17 +490,21 @@ toStrand( if (auto r = s.directStepAccts()) return *r; if (auto const r = s.bookStepBook()) - return std::make_pair(r->in.account, r->out.account); + return std::make_pair(r->in.getIssuer(), r->out.getIssuer()); Throw(tefEXCEPTION, "Step should be either a direct or book step"); return std::make_pair(xrpAccount(), xrpAccount()); }; auto curAcc = src; - auto curIss = [&] { - auto& currency = sendMaxIssue ? sendMaxIssue->currency : deliver.currency; - if (isXRP(currency)) - return xrpIssue(); - return Issue{currency, src}; + auto curAsset = [&]() -> Asset { + auto const& asset = sendMaxAsset ? *sendMaxAsset : deliver; + return asset.visit( + [&](MPTIssue const&) -> Asset { return asset; }, + [&](Issue const& issue) -> Asset { + if (isXRP(asset)) + return xrpIssue(); + return Issue{issue.currency, src}; + }); }(); for (auto const& s : result) @@ -387,22 +515,25 @@ toStrand( if (auto const b = s->bookStepBook()) { - if (curIss != b->in) + if (curAsset != b->in) return false; - curIss = b->out; + curAsset = b->out; } - else + else if (curAsset.holds()) { - curIss.account = accts.second; + curAsset.get().account = accts.second; } curAcc = accts.second; } if (curAcc != dst) return false; - if (curIss.currency != deliver.currency) + if (curAsset.holds() != deliver.holds() || + (curAsset.holds() && + curAsset.get().currency != deliver.get().currency) || + (curAsset.holds() && curAsset.get() != deliver.get())) return false; - if (curIss.account != deliver.account && curIss.account != dst) + if (curAsset.getIssuer() != deliver.getIssuer() && curAsset.getIssuer() != dst) return false; return true; }; @@ -424,9 +555,9 @@ toStrands( ReadView const& view, AccountID const& src, AccountID const& dst, - Issue const& deliver, + Asset const& deliver, std::optional const& limitQuality, - std::optional const& sendMax, + std::optional const& sendMax, STPathSet const& paths, bool addDefaultPath, bool ownerPaysTransferFee, @@ -539,14 +670,14 @@ StrandContext::StrandContext( // replicates the source or destination. AccountID const& strandSrc_, AccountID const& strandDst_, - Issue const& strandDeliver_, + Asset const& strandDeliver_, std::optional const& limitQuality_, bool isLast_, bool ownerPaysTransferFee_, OfferCrossing offerCrossing_, bool isDefaultPath_, - std::array, 2>& seenDirectIssues_, - boost::container::flat_set& seenBookOuts_, + std::array, 2>& seenDirectAssets_, + boost::container::flat_set& seenBookOuts_, AMMContext& ammContext_, std::optional const& domainID_, beast::Journal j_) @@ -562,7 +693,7 @@ StrandContext::StrandContext( , isDefaultPath(isDefaultPath_) , strandSize(strand_.size()) , prevStep(!strand_.empty() ? strand_.back().get() : nullptr) - , seenDirectIssues(seenDirectIssues_) + , seenDirectAssets(seenDirectAssets_) , seenBookOuts(seenBookOuts_) , ammContext(ammContext_) , domainID(domainID_) @@ -570,25 +701,4 @@ StrandContext::StrandContext( { } -template -bool -isDirectXrpToXrp(Strand const& strand) -{ - return false; -} - -template <> -bool -isDirectXrpToXrp(Strand const& strand) -{ - return (strand.size() == 2); -} - -template bool -isDirectXrpToXrp(Strand const& strand); -template bool -isDirectXrpToXrp(Strand const& strand); -template bool -isDirectXrpToXrp(Strand const& strand); - } // namespace xrpl diff --git a/src/libxrpl/tx/paths/RippleCalc.cpp b/src/libxrpl/tx/paths/RippleCalc.cpp index c9f0c9e0fb..e1f1cb272c 100644 --- a/src/libxrpl/tx/paths/RippleCalc.cpp +++ b/src/libxrpl/tx/paths/RippleCalc.cpp @@ -54,7 +54,7 @@ RippleCalc::rippleCalculate( auto const sendMax = [&]() -> std::optional { if (saMaxAmountReq >= beast::zero || - saMaxAmountReq.getCurrency() != saDstAmountReq.getCurrency() || + !equalTokens(saMaxAmountReq.asset(), saDstAmountReq.asset()) || saMaxAmountReq.getIssuer() != uSrcAccountID) { return saMaxAmountReq; diff --git a/src/libxrpl/tx/paths/XRPEndpointStep.cpp b/src/libxrpl/tx/paths/XRPEndpointStep.cpp index 7452f57ecd..4b9b934daf 100644 --- a/src/libxrpl/tx/paths/XRPEndpointStep.cpp +++ b/src/libxrpl/tx/paths/XRPEndpointStep.cpp @@ -179,13 +179,25 @@ private: // because the trust line was created after the XRP was removed.) // Return how much the reserve should be reduced. // - // Note that reduced reserve only happens if the trust line does not + // Note that reduced reserve only happens if the trust line or MPT does not // currently exist. static std::int32_t computeReserveReduction(StrandContext const& ctx, AccountID const& acc) { - if (ctx.isFirst && !ctx.view.read(keylet::line(acc, ctx.strandDeliver))) - return -1; + if (ctx.isFirst) + { + return ctx.strandDeliver.visit( + [&](Issue const& issue) { + if (!ctx.view.exists(keylet::line(acc, issue))) + return -1; + return 0; + }, + [&](MPTIssue const& issue) { + if (!ctx.view.exists(keylet::mptoken(issue.getMptID(), acc))) + return -1; + return 0; + }); + } return 0; } @@ -283,9 +295,9 @@ XRPEndpointStep::validFwd(PaymentSandbox& sb, ApplyView& afView, Eithe return {false, EitherAmount(XRPAmount(beast::zero))}; } - XRPL_ASSERT(in.native, "xrpl::XRPEndpointStep::validFwd : input is XRP"); + XRPL_ASSERT(in.holds(), "xrpl::XRPEndpointStep::validFwd : input is XRP"); - auto const& xrpIn = in.xrp; + auto const& xrpIn = in.get(); auto const balance = static_cast(this)->xrpLiquid(sb); if (!isLast_ && balance < xrpIn) @@ -336,7 +348,7 @@ XRPEndpointStep::check(StrandContext const& ctx) const return ter; auto const issuesIndex = isLast_ ? 0 : 1; - if (!ctx.seenDirectIssues[issuesIndex].insert(xrpIssue()).second) + if (!ctx.seenDirectAssets[issuesIndex].insert(xrpIssue()).second) { JLOG(j_.debug()) << "XRPEndpointStep: loop detected: Index: " << ctx.strandSize << ' ' << *this; diff --git a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp index 9074122cdf..bec17b010a 100644 --- a/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp +++ b/src/libxrpl/tx/transactors/bridge/XChainBridge.cpp @@ -642,7 +642,7 @@ finalizeClaimHelper( saveNumberRoundMode const _{Number::setround(round_mode)}; STAmount const den{rewardAccounts.size()}; - return divide(rewardPool, den, rewardPool.issue()); + return divide(rewardPool, den, rewardPool.asset()); }(); STAmount distributed = rewardPool.zeroed(); for (auto const& rewardAccount : rewardAccounts) @@ -1167,7 +1167,7 @@ attestationPreflight(PreflightContext const& ctx) if (att->sendingAmount.signum() <= 0) return temXCHAIN_BAD_PROOF; auto const expectedIssue = bridgeSpec.issue(STXChainBridge::srcChain(att->wasLockingChainSend)); - if (att->sendingAmount.issue() != expectedIssue) + if (att->sendingAmount.asset() != expectedIssue) return temXCHAIN_BAD_PROOF; return tesSUCCESS; @@ -1578,8 +1578,8 @@ XChainClaim::preflight(PreflightContext const& ctx) auto const amount = ctx.tx[sfAmount]; if (amount.signum() <= 0 || - (amount.issue() != bridgeSpec.lockingChainIssue() && - amount.issue() != bridgeSpec.issuingChainIssue())) + (amount.asset() != bridgeSpec.lockingChainIssue() && + amount.asset() != bridgeSpec.issuingChainIssue())) { return temBAD_AMOUNT; } @@ -1628,12 +1628,12 @@ XChainClaim::preclaim(PreclaimContext const& ctx) if (isLockingChain) { - if (bridgeSpec.lockingChainIssue() != thisChainAmount.issue()) + if (bridgeSpec.lockingChainIssue() != thisChainAmount.asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; } else { - if (bridgeSpec.issuingChainIssue() != thisChainAmount.issue()) + if (bridgeSpec.issuingChainIssue() != thisChainAmount.asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; } } @@ -1820,8 +1820,8 @@ XChainCommit::preflight(PreflightContext const& ctx) if (amount.signum() <= 0 || !isLegalNet(amount)) return temBAD_AMOUNT; - if (amount.issue() != bridgeSpec.lockingChainIssue() && - amount.issue() != bridgeSpec.issuingChainIssue()) + if (amount.asset() != bridgeSpec.lockingChainIssue() && + amount.asset() != bridgeSpec.issuingChainIssue()) return temBAD_ISSUER; return tesSUCCESS; @@ -1866,12 +1866,12 @@ XChainCommit::preclaim(PreclaimContext const& ctx) if (isLockingChain) { - if (bridgeSpec.lockingChainIssue() != ctx.tx[sfAmount].issue()) + if (bridgeSpec.lockingChainIssue() != ctx.tx[sfAmount].asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; } else { - if (bridgeSpec.issuingChainIssue() != ctx.tx[sfAmount].issue()) + if (bridgeSpec.issuingChainIssue() != ctx.tx[sfAmount].asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; } @@ -2083,7 +2083,7 @@ XChainCreateAccountCommit::preflight(PreflightContext const& ctx) if (reward.signum() < 0 || !reward.native()) return temBAD_AMOUNT; - if (reward.issue() != amount.issue()) + if (reward.asset() != amount.asset()) return temBAD_AMOUNT; return tesSUCCESS; @@ -2115,7 +2115,7 @@ XChainCreateAccountCommit::preclaim(PreclaimContext const& ctx) if (amount < *minCreateAmount) return tecXCHAIN_INSUFF_CREATE_AMOUNT; - if (minCreateAmount->issue() != amount.issue()) + if (minCreateAmount->asset() != amount.asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; AccountID const thisDoor = (*sleBridge)[sfAccount]; @@ -2143,7 +2143,7 @@ XChainCreateAccountCommit::preclaim(PreclaimContext const& ctx) } STXChainBridge::ChainType const dstChain = STXChainBridge::otherChain(srcChain); - if (bridgeSpec.issue(srcChain) != ctx.tx[sfAmount].issue()) + if (bridgeSpec.issue(srcChain) != ctx.tx[sfAmount].asset()) return tecXCHAIN_BAD_TRANSFER_ISSUE; if (!isXRP(bridgeSpec.issue(dstChain))) diff --git a/src/libxrpl/tx/transactors/check/CheckCash.cpp b/src/libxrpl/tx/transactors/check/CheckCash.cpp index fa908c3aa3..14fbc80f15 100644 --- a/src/libxrpl/tx/transactors/check/CheckCash.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCash.cpp @@ -1,18 +1,30 @@ #include #include #include +#include #include #include #include #include -#include #include #include +#include #include namespace xrpl { +bool +CheckCash::checkExtraFeatures(xrpl::PreflightContext const& ctx) +{ + auto const optAmount = ctx.tx[~sfAmount]; + auto const optDeliverMin = ctx.tx[~sfDeliverMin]; + + return ctx.rules.enabled(featureMPTokensV2) || + (!(optAmount && optAmount->holds()) && + !(optDeliverMin && optDeliverMin->holds())); +} + NotTEC CheckCash::preflight(PreflightContext const& ctx) { @@ -35,7 +47,7 @@ CheckCash::preflight(PreflightContext const& ctx) return temBAD_AMOUNT; } - if (badCurrency() == value.getCurrency()) + if (badAsset() == value.asset()) { JLOG(ctx.j.warn()) << "Malformed transaction: Bad currency."; return temBAD_CURRENCY; @@ -106,8 +118,7 @@ CheckCash::preclaim(PreclaimContext const& ctx) }(ctx.tx)}; STAmount const sendMax = sleCheck->at(sfSendMax); - Currency const currency{value.getCurrency()}; - if (currency != sendMax.getCurrency()) + if (!equalTokens(value.asset(), sendMax.asset())) { JLOG(ctx.j.warn()) << "Check cash does not match check currency."; return temMALFORMED; @@ -127,8 +138,13 @@ CheckCash::preclaim(PreclaimContext const& ctx) // Make sure the check owner holds at least value. If they have // less than value the check cannot be cashed. { - STAmount availableFunds{ - accountFunds(ctx.view, sleCheck->at(sfAccount), value, fhZERO_IF_FROZEN, ctx.j)}; + STAmount availableFunds{accountFunds( + ctx.view, + sleCheck->at(sfAccount), + value, + fhZERO_IF_FROZEN, + ahZERO_IF_UNAUTHORIZED, + ctx.j)}; // Note that src will have one reserve's worth of additional XRP // once the check is cashed, since the check's reserve will no @@ -147,51 +163,94 @@ CheckCash::preclaim(PreclaimContext const& ctx) // An issuer can always accept their own currency. if (!value.native() && (value.getIssuer() != dstId)) { - auto const sleIssuer = ctx.view.read(keylet::account(issuerId)); - if (!sleIssuer) - { - JLOG(ctx.j.warn()) - << "Can't receive IOUs from non-existent issuer: " << to_string(issuerId); - return tecNO_ISSUER; - } + return value.asset().visit( + [&](Issue const& issue) -> TER { + Currency const currency{issue.currency}; + auto const sleTrustLine = + ctx.view.read(keylet::line(dstId, issuerId, currency)); - if ((sleIssuer->at(sfFlags) & lsfRequireAuth) != 0u) - { - auto const sleTrustLine = ctx.view.read(keylet::line(dstId, issuerId, currency)); + auto const sleIssuer = ctx.view.read(keylet::account(issuerId)); + if (!sleIssuer) + { + JLOG(ctx.j.warn()) << "Can't receive IOUs from " + "non-existent issuer: " + << to_string(issuerId); + return tecNO_ISSUER; + } - if (!sleTrustLine) - { - // We can only create a trust line if the issuer does not - // have lsfRequireAuth set. - return tecNO_AUTH; - } + if ((sleIssuer->at(sfFlags) & lsfRequireAuth) != 0u) + { + if (!sleTrustLine) + { + // We can only create a trust line if the issuer + // does not have lsfRequireAuth set. + return tecNO_AUTH; + } - // Entries have a canonical representation, determined by a - // lexicographical "greater than" comparison employing strict - // weak ordering. Determine which entry we need to access. - bool const canonical_gt(dstId > issuerId); + // Entries have a canonical representation, + // determined by a lexicographical "greater than" + // comparison employing strict weak ordering. + // Determine which entry we need to access. + bool const canonical_gt(dstId > issuerId); - bool const is_authorized( - (sleTrustLine->at(sfFlags) & (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); + bool const is_authorized( + (sleTrustLine->at(sfFlags) & + (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); - if (!is_authorized) - { - JLOG(ctx.j.warn()) << "Can't receive IOUs from issuer without auth."; - return tecNO_AUTH; - } - } + if (!is_authorized) + { + JLOG(ctx.j.warn()) << "Can't receive IOUs from " + "issuer without auth."; + return tecNO_AUTH; + } + } - // The trustline from source to issuer does not need to - // be checked for freezing, since we already verified that the - // source has sufficient non-frozen funds available. + // The trustline from source to issuer does not need to + // be checked for freezing, since we already verified + // that the source has sufficient non-frozen funds + // available. - // However, the trustline from destination to issuer may not - // be frozen. - if (isFrozen(ctx.view, dstId, currency, issuerId)) - { - JLOG(ctx.j.warn()) << "Cashing a check to a frozen trustline."; - return tecFROZEN; - } + // However, the trustline from destination to issuer may + // not be frozen. + if (isFrozen(ctx.view, dstId, currency, issuerId)) + { + JLOG(ctx.j.warn()) << "Cashing a check to a frozen trustline."; + return tecFROZEN; + } + + return tesSUCCESS; + }, + [&](MPTIssue const& issue) -> TER { + auto const sleIssuer = ctx.view.read(keylet::account(issuerId)); + if (!sleIssuer) + { + JLOG(ctx.j.warn()) << "Can't receive MPTs from " + "non-existent issuer: " + << to_string(issuerId); + return tecNO_ISSUER; + } + + if (auto const err = requireAuth(ctx.view, issue, dstId, AuthType::WeakAuth); + !isTesSuccess(err)) + { + JLOG(ctx.j.warn()) << "Cashing a check to a MPT requiring auth."; + return err; + } + + if (isFrozen(ctx.view, dstId, issue)) + { + JLOG(ctx.j.warn()) << "Cashing a check to a frozen MPT."; + return tecLOCKED; + } + + if (auto const err = canTrade(ctx.view, value.asset()); !isTesSuccess(err)) + { + JLOG(ctx.j.warn()) << "MPT DEX is not allowed."; + return err; + } + + return tesSUCCESS; + }); } } return tesSUCCESS; @@ -287,94 +346,152 @@ CheckCash::doApply() // maximum possible currency because there might be a gateway // transfer rate to account for. Since the transfer rate cannot // exceed 200%, we use 1/2 maxValue as our limit. + auto const maxDeliverMin = [&]() { + return optDeliverMin->asset().visit( + [&](Issue const&) { + return STAmount( + optDeliverMin->asset(), STAmount::cMaxValue / 2, STAmount::cMaxOffset); + }, + [&](MPTIssue const&) { + return STAmount(optDeliverMin->asset(), maxMPTokenAmount / 2); + }); + }; STAmount const flowDeliver{ - optDeliverMin - ? STAmount( - optDeliverMin->issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset) - : ctx_.tx.getFieldAmount(sfAmount)}; + optDeliverMin ? maxDeliverMin() : ctx_.tx.getFieldAmount(sfAmount)}; - // If a trust line does not exist yet create one. - Issue const& trustLineIssue = flowDeliver.issue(); - AccountID const issuer = flowDeliver.getIssuer(); - AccountID const truster = issuer == account_ ? srcId : account_; - Keylet const trustLineKey = keylet::line(truster, trustLineIssue); - bool const destLow = issuer > account_; + // Check reserve. Return destination account SLE if enough reserve, + // otherwise return nullptr. + auto checkReserve = [&]() -> std::shared_ptr { + auto sleDst = psb.peek(keylet::account(account_)); - if (!psb.exists(trustLineKey)) - { - // 1. Can the check casher meet the reserve for the trust line? - // 2. Create trust line between destination (this) account - // and the issuer. - // 3. Apply correct noRipple settings on trust line. Use... - // a. this (destination) account and - // b. issuing account (not sending account). - - auto const sleDst = psb.peek(keylet::account(account_)); - - // Can the account cover the trust line's reserve? + // Can the account cover the trust line's or MPT reserve? if (std::uint32_t const ownerCount = {sleDst->at(sfOwnerCount)}; preFeeBalance_ < psb.fees().accountReserve(ownerCount + 1)) { JLOG(j_.trace()) << "Trust line does not exist. " - "Insufficent reserve to create line."; + "Insufficient reserve to create line."; - return tecNO_LINE_INSUF_RESERVE; + return nullptr; } + return sleDst; + }; - Currency const currency = flowDeliver.getCurrency(); - STAmount initialBalance(flowDeliver.issue()); - initialBalance.setIssuer(noAccount()); + std::optional trustLineKey; + STAmount savedLimit; + bool destLow = false; + AccountID const& deliverIssuer = flowDeliver.getIssuer(); + auto const err = flowDeliver.asset().visit( + [&](Issue const& issue) -> std::optional { + // If a trust line does not exist yet create one. + Issue const& trustLineIssue = issue; + AccountID const truster = deliverIssuer == account_ ? srcId : account_; + trustLineKey = keylet::line(truster, trustLineIssue); + destLow = deliverIssuer > account_; - if (TER const ter = trustCreate( - psb, // payment sandbox - destLow, // is dest low? - issuer, // source - account_, // destination - trustLineKey.key, // ledger index - sleDst, // Account to add to - false, // authorize account - (sleDst->getFlags() & lsfDefaultRipple) == 0, // - false, // freeze trust line - false, // deep freeze trust line - initialBalance, // zero initial balance - Issue(currency, account_), // limit of zero - 0, // quality in - 0, // quality out - viewJ); // journal - !isTesSuccess(ter)) + if (!psb.exists(*trustLineKey)) + { + // 1. Can the check casher meet the reserve for the + // trust line? + // 2. Create trust line between destination (this) + // account + // and the issuer. + // 3. Apply correct noRipple settings on trust line. + // Use... + // a. this (destination) account and + // b. issuing account (not sending account). + + auto const sleDst = checkReserve(); + if (sleDst == nullptr) + return tecNO_LINE_INSUF_RESERVE; + + Currency const& currency = issue.currency; + STAmount initialBalance(flowDeliver.asset()); + initialBalance.get().account = noAccount(); + + if (TER const ter = trustCreate( + psb, // payment sandbox + destLow, // is dest low? + deliverIssuer, // source + account_, // destination + trustLineKey->key, // ledger index + sleDst, // Account to add to + false, // authorize account + (sleDst->getFlags() & lsfDefaultRipple) == 0, // + false, // freeze trust line + false, // deep freeze trust line + initialBalance, // zero initial balance + Issue(currency, account_), // limit of zero + 0, // quality in + 0, // quality out + viewJ); // journal + !isTesSuccess(ter)) + { + return ter; + } + + psb.update(sleDst); + + // Note that we _don't_ need to be careful about + // destroying the trust line if the check cashing + // fails. The transaction machinery will + // automatically clean it up. + } + + // Since the destination is signing the check, they + // clearly want the funds even if their new total funds + // would exceed the limit on their trust line. So we + // tweak the trust line limits before calling flow and + // then restore the trust line limits afterwards. + auto const sleTrustLine = psb.peek(*trustLineKey); + if (!sleTrustLine) + return tecNO_LINE; + + SF_AMOUNT const& tweakedLimit = destLow ? sfLowLimit : sfHighLimit; + savedLimit = sleTrustLine->at(tweakedLimit); + + // Set the trust line limit to the highest possible + // value while flow runs. + STAmount const bigAmount( + trustLineIssue, STAmount::cMaxValue, STAmount::cMaxOffset); + sleTrustLine->at(tweakedLimit) = bigAmount; + + return std::nullopt; + }, + [&](MPTIssue const& issue) -> std::optional { + if (account_ != deliverIssuer) + { + auto const& mptID = issue.getMptID(); + // Create MPT if it doesn't exist + auto const mptokenKey = keylet::mptoken(mptID, account_); + if (!psb.exists(mptokenKey)) + { + auto sleDst = checkReserve(); + if (sleDst == nullptr) + return tecINSUFFICIENT_RESERVE; + + if (auto const err = checkCreateMPT(psb, mptID, account_, j_); + !isTesSuccess(err)) + { + return err; + } + } + } + + return std::nullopt; + }); + if (err) + return *err; + // Make sure the tweaked limits are restored when we leave + // scope. + scope_exit const fixup([&psb, &trustLineKey, destLow, &savedLimit]() { + if (trustLineKey) { - return ter; + SF_AMOUNT const& tweakedLimit = destLow ? sfLowLimit : sfHighLimit; + if (auto const sleTrustLine = psb.peek(*trustLineKey)) + sleTrustLine->at(tweakedLimit) = savedLimit; } - - psb.update(sleDst); - - // Note that we _don't_ need to be careful about destroying - // the trust line if the check cashing fails. The transaction - // machinery will automatically clean it up. - } - - // Since the destination is signing the check, they clearly want - // the funds even if their new total funds would exceed the limit - // on their trust line. So we tweak the trust line limits before - // calling flow and then restore the trust line limits afterwards. - auto const sleTrustLine = psb.peek(trustLineKey); - if (!sleTrustLine) - return tecNO_LINE; - - SF_AMOUNT const& tweakedLimit = destLow ? sfLowLimit : sfHighLimit; - STAmount const savedLimit = sleTrustLine->at(tweakedLimit); - - // Make sure the tweaked limits are restored when we leave scope. - scope_exit const fixup([&psb, &trustLineKey, &tweakedLimit, &savedLimit]() { - if (auto const sleTrustLine = psb.peek(trustLineKey)) - sleTrustLine->at(tweakedLimit) = savedLimit; }); - // Set the trust line limit to the highest possible value - // while flow runs. - STAmount const bigAmount(trustLineIssue, STAmount::cMaxValue, STAmount::cMaxOffset); - sleTrustLine->at(tweakedLimit) = bigAmount; - // Let flow() do the heavy lifting on a check for an IOU. auto const result = flow( psb, @@ -405,6 +522,7 @@ CheckCash::doApply() JLOG(ctx_.journal.warn()) << "flow did not produce DeliverMin."; return tecPATH_PARTIAL; } + ctx_.deliver(result.actualAmountOut); } // Set the delivered amount metadata in all cases, not just diff --git a/src/libxrpl/tx/transactors/check/CheckCreate.cpp b/src/libxrpl/tx/transactors/check/CheckCreate.cpp index fde3373691..70dddd7338 100644 --- a/src/libxrpl/tx/transactors/check/CheckCreate.cpp +++ b/src/libxrpl/tx/transactors/check/CheckCreate.cpp @@ -1,6 +1,7 @@ #include #include #include +#include #include #include #include @@ -10,6 +11,12 @@ namespace xrpl { +bool +CheckCreate::checkExtraFeatures(xrpl::PreflightContext const& ctx) +{ + return ctx.rules.enabled(featureMPTokensV2) || !ctx.tx[sfSendMax].holds(); +} + NotTEC CheckCreate::preflight(PreflightContext const& ctx) { @@ -29,7 +36,7 @@ CheckCreate::preflight(PreflightContext const& ctx) return temBAD_AMOUNT; } - if (badCurrency() == sendMax.getCurrency()) + if (badAsset() == sendMax.asset()) { JLOG(ctx.j.warn()) << "Malformed transaction: Bad currency."; return temBAD_CURRENCY; @@ -52,6 +59,7 @@ TER CheckCreate::preclaim(PreclaimContext const& ctx) { AccountID const dstId{ctx.tx[sfDestination]}; + AccountID const srcId{ctx.tx[sfAccount]}; auto const sleDst = ctx.view.read(keylet::account(dstId)); if (!sleDst) { @@ -86,39 +94,56 @@ CheckCreate::preclaim(PreclaimContext const& ctx) { // The currency may not be globally frozen AccountID const& issuerId{sendMax.getIssuer()}; - if (isGlobalFrozen(ctx.view, issuerId)) + if (isGlobalFrozen(ctx.view, sendMax.asset())) { JLOG(ctx.j.warn()) << "Creating a check for frozen asset"; - return tecFROZEN; - } - // If this account has a trustline for the currency, that - // trustline may not be frozen. - // - // Note that we DO allow create check for a currency that the - // account does not yet have a trustline to. - AccountID const srcId{ctx.tx.getAccountID(sfAccount)}; - if (issuerId != srcId) - { - // Check if the issuer froze the line - auto const sleTrust = - ctx.view.read(keylet::line(srcId, issuerId, sendMax.getCurrency())); - if (sleTrust && sleTrust->isFlag((issuerId > srcId) ? lsfHighFreeze : lsfLowFreeze)) - { - JLOG(ctx.j.warn()) << "Creating a check for frozen trustline."; - return tecFROZEN; - } - } - if (issuerId != dstId) - { - // Check if dst froze the line. - auto const sleTrust = - ctx.view.read(keylet::line(issuerId, dstId, sendMax.getCurrency())); - if (sleTrust && sleTrust->isFlag((dstId > issuerId) ? lsfHighFreeze : lsfLowFreeze)) - { - JLOG(ctx.j.warn()) << "Creating a check for destination frozen trustline."; - return tecFROZEN; - } + return sendMax.asset().holds() ? tecLOCKED : tecFROZEN; } + auto const err = sendMax.asset().visit( + [&](Issue const& issue) -> std::optional { + // If this account has a trustline for the currency, + // that trustline may not be frozen. + // + // Note that we DO allow create check for a currency + // that the account does not yet have a trustline to. + if (issuerId != srcId) + { + // Check if the issuer froze the line + auto const sleTrust = + ctx.view.read(keylet::line(srcId, issuerId, issue.currency)); + if (sleTrust && + sleTrust->isFlag((issuerId > srcId) ? lsfHighFreeze : lsfLowFreeze)) + { + JLOG(ctx.j.warn()) << "Creating a check for frozen trustline."; + return tecFROZEN; + } + } + if (issuerId != dstId) + { + // Check if dst froze the line. + auto const sleTrust = + ctx.view.read(keylet::line(issuerId, dstId, issue.currency)); + if (sleTrust && + sleTrust->isFlag((dstId > issuerId) ? lsfHighFreeze : lsfLowFreeze)) + { + JLOG(ctx.j.warn()) << "Creating a check for " + "destination frozen trustline."; + return tecFROZEN; + } + } + + return std::nullopt; + }, + [&](MPTIssue const& issue) -> std::optional { + if (srcId != issuerId && isFrozen(ctx.view, srcId, issue)) + return tecLOCKED; + if (dstId != issuerId && isFrozen(ctx.view, dstId, issue)) + return tecLOCKED; + + return std::nullopt; + }); + if (err) + return *err; } } if (hasExpired(ctx.view, ctx.tx[~sfExpiration])) @@ -126,7 +151,8 @@ CheckCreate::preclaim(PreclaimContext const& ctx) JLOG(ctx.j.warn()) << "Creating a check that has already expired."; return tecEXPIRED; } - return tesSUCCESS; + + return canTrade(ctx.view, ctx.tx[sfSendMax].asset()); } TER diff --git a/src/libxrpl/tx/transactors/dex/AMMBid.cpp b/src/libxrpl/tx/transactors/dex/AMMBid.cpp index 805b5073e4..8efc36537a 100644 --- a/src/libxrpl/tx/transactors/dex/AMMBid.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMBid.cpp @@ -13,14 +13,20 @@ namespace xrpl { bool AMMBid::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + if (!ctx.rules.enabled(featureMPTokensV2) && + (ctx.tx[sfAsset].holds() || ctx.tx[sfAsset2].holds())) + return false; + + return true; } NotTEC AMMBid::preflight(PreflightContext const& ctx) { - if (auto const res = - invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) + if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2])) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid asset pair."; return res; @@ -110,7 +116,7 @@ AMMBid::preclaim(PreclaimContext const& ctx) if (bidMin) { - if (bidMin->issue() != lpTokens.issue()) + if (bidMin->asset() != lpTokens.asset()) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid LPToken."; return temBAD_AMM_TOKENS; @@ -125,7 +131,7 @@ AMMBid::preclaim(PreclaimContext const& ctx) auto const bidMax = ctx.tx[~sfBidMax]; if (bidMax) { - if (bidMax->issue() != lpTokens.issue()) + if (bidMax->asset() != lpTokens.asset()) { JLOG(ctx.j.debug()) << "AMM Bid: Invalid LPToken."; return temBAD_AMM_TOKENS; @@ -200,7 +206,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour { auctionSlot.makeFieldAbsent(sfDiscountedFee); } - auctionSlot.setFieldAmount(sfPrice, toSTAmount(lpTokens.issue(), minPrice)); + auctionSlot.setFieldAmount(sfPrice, toSTAmount(lpTokens.asset(), minPrice)); if (ctx_.tx.isFieldPresent(sfAuthAccounts)) { auctionSlot.setFieldArray(sfAuthAccounts, ctx_.tx.getFieldArray(sfAuthAccounts)); @@ -211,7 +217,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour } // Burn the remaining bid amount auto const saBurn = - adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.issue(), burn), IsDeposit::No); + adjustLPTokens(lptAMMBalance, toSTAmount(lptAMMBalance.asset(), burn), IsDeposit::No); if (saBurn >= lptAMMBalance) { // This error case should never occur. @@ -221,7 +227,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour return tecINTERNAL; // LCOV_EXCL_STOP } - auto res = redeemIOU(sb, account_, saBurn, lpTokens.issue(), ctx_.journal); + auto res = redeemIOU(sb, account_, saBurn, lpTokens.get(), ctx_.journal); if (!isTesSuccess(res)) { JLOG(ctx_.journal.debug()) << "AMM Bid: failed to redeem."; @@ -321,7 +327,7 @@ applyBid(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::Jour sb, account_, auctionSlot[sfAccount], - toSTAmount(lpTokens.issue(), refund), + toSTAmount(lpTokens.asset(), refund), ctx_.journal); if (!isTesSuccess(res)) { diff --git a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp index fb0999bfb0..4b98711c19 100644 --- a/src/libxrpl/tx/transactors/dex/AMMClawback.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMClawback.cpp @@ -19,6 +19,19 @@ AMMClawback::getFlagsMask(PreflightContext const& ctx) return tfAMMClawbackMask; } +bool +AMMClawback::checkExtraFeatures(xrpl::PreflightContext const& ctx) +{ + if (!ctx.rules.enabled(featureAMMClawback)) + return false; + + std::optional const clawAmount = ctx.tx[~sfAmount]; + + return ctx.rules.enabled(featureMPTokensV2) || + (!(clawAmount && clawAmount->holds()) && !ctx.tx[sfAsset].holds() && + !ctx.tx[sfAsset2].holds()); +} + NotTEC AMMClawback::preflight(PreflightContext const& ctx) { @@ -32,31 +45,31 @@ AMMClawback::preflight(PreflightContext const& ctx) } std::optional const clawAmount = ctx.tx[~sfAmount]; - auto const asset = ctx.tx[sfAsset].get(); - auto const asset2 = ctx.tx[sfAsset2].get(); + auto const asset = ctx.tx[sfAsset]; + auto const asset2 = ctx.tx[sfAsset2]; if (isXRP(asset)) return temMALFORMED; auto const flags = ctx.tx.getFlags(); - if (((flags & tfClawTwoAssets) != 0u) && asset.account != asset2.account) + if (((flags & tfClawTwoAssets) != 0u) && asset.getIssuer() != asset2.getIssuer()) { JLOG(ctx.j.trace()) << "AMMClawback: tfClawTwoAssets can only be enabled when two " "assets in the AMM pool are both issued by the issuer"; return temINVALID_FLAG; } - if (asset.account != issuer) + if (asset.getIssuer() != issuer) { JLOG(ctx.j.trace()) << "AMMClawback: Asset's account does not " "match Account field."; return temMALFORMED; } - if (clawAmount && clawAmount->get() != asset) + if (clawAmount && clawAmount->asset() != asset) { - JLOG(ctx.j.trace()) << "AMMClawback: Amount's issuer/currency subfield " + JLOG(ctx.j.trace()) << "AMMClawback: Amount's asset subfield " "does not match Asset field"; return temBAD_AMOUNT; } @@ -70,8 +83,8 @@ AMMClawback::preflight(PreflightContext const& ctx) TER AMMClawback::preclaim(PreclaimContext const& ctx) { - auto const asset = ctx.tx[sfAsset].get(); - auto const asset2 = ctx.tx[sfAsset2].get(); + auto const asset = ctx.tx[sfAsset]; + auto const asset2 = ctx.tx[sfAsset2]; auto const sleIssuer = ctx.view.read(keylet::account(ctx.tx[sfAccount])); if (!sleIssuer) return terNO_ACCOUNT; // LCOV_EXCL_LINE @@ -87,11 +100,36 @@ AMMClawback::preclaim(PreclaimContext const& ctx) } std::uint32_t const issuerFlagsIn = sleIssuer->getFieldU32(sfFlags); + if (!ctx.view.rules().enabled(featureMPTokensV2)) + { + // If AllowTrustLineClawback is not set or NoFreeze is set, return no + // permission + if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlagsIn & lsfNoFreeze) != 0u)) + return tesSUCCESS; + } - // If AllowTrustLineClawback is not set or NoFreeze is set, return no - // permission - if (((issuerFlagsIn & lsfAllowTrustLineClawback) == 0u) || - ((issuerFlagsIn & lsfNoFreeze) != 0u)) + auto const checkClawAsset = [&](Asset const asset) -> bool { + return asset.visit( + [&](Issue const& issue) { + if (issue.native()) + return false; // LCOV_EXCL_LINE + + return ((issuerFlagsIn & lsfAllowTrustLineClawback) != 0u) && + ((issuerFlagsIn & lsfNoFreeze) == 0u); + }, + [&](MPTIssue const& issue) { + auto const sleIssuance = ctx.view.read(keylet::mptIssuance(issue.getMptID())); + + return sleIssuance && sleIssuance->isFlag(lsfMPTCanClawback) && + sleIssuance->getAccountID(sfIssuer) == ctx.tx[sfAccount]; + }); + }; + + if (!checkClawAsset(asset)) + return tecNO_PERMISSION; + + if (ctx.tx.isFlag(tfClawTwoAssets) && !checkClawAsset(asset2)) return tecNO_PERMISSION; return tesSUCCESS; @@ -115,8 +153,8 @@ AMMClawback::applyGuts(Sandbox& sb) std::optional const clawAmount = ctx_.tx[~sfAmount]; AccountID const issuer = ctx_.tx[sfAccount]; AccountID const holder = ctx_.tx[sfHolder]; - Issue const asset = ctx_.tx[sfAsset].get(); - Issue const asset2 = ctx_.tx[sfAsset2].get(); + Asset const asset = ctx_.tx[sfAsset]; + Asset const asset2 = ctx_.tx[sfAsset2]; auto ammSle = sb.peek(keylet::amm(asset, asset2)); if (!ammSle) @@ -138,8 +176,15 @@ AMMClawback::applyGuts(Sandbox& sb) !res) return res.error(); // LCOV_EXCL_LINE } - auto const expected = - ammHolds(sb, *ammSle, asset, asset2, FreezeHandling::fhIGNORE_FREEZE, ctx_.journal); + + auto const expected = ammHolds( + sb, + *ammSle, + asset, + asset2, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + ctx_.journal); if (!expected) return expected.error(); // LCOV_EXCL_LINE @@ -173,6 +218,7 @@ AMMClawback::applyGuts(Sandbox& sb) holdLPtokens, 0, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, WithdrawAll::Yes, preFeeBalance_, ctx_.journal); @@ -204,7 +250,12 @@ AMMClawback::applyGuts(Sandbox& sb) << to_string(newLPTokenBalance.iou()) << " old balance: " << to_string(lptAMMBalance.iou()); - auto const ter = directSendNoFee(sb, holder, issuer, amountWithdraw, true, j_); + auto sendAmount = [&](STAmount const& saAmount) -> TER { + bool const checkIssuer = saAmount.holds(); + return directSendNoFee(sb, holder, issuer, saAmount, checkIssuer, j_); + }; + + auto const ter = sendAmount(amountWithdraw); if (!isTesSuccess(ter)) return ter; // LCOV_EXCL_LINE @@ -217,7 +268,7 @@ AMMClawback::applyGuts(Sandbox& sb) auto const flags = ctx_.tx.getFlags(); if ((flags & tfClawTwoAssets) != 0u) - return directSendNoFee(sb, holder, issuer, *amount2Withdraw, true, j_); + return sendAmount(*amount2Withdraw); return tesSUCCESS; } @@ -237,8 +288,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( auto frac = Number{amount} / amountBalance; auto amount2Withdraw = amount2Balance * frac; - auto const lpTokensWithdraw = toSTAmount(lptAMMBalance.issue(), lptAMMBalance * frac); - + auto const lpTokensWithdraw = toSTAmount(lptAMMBalance.asset(), lptAMMBalance * frac); if (lpTokensWithdraw > holdLPtokens) { // if lptoken balance less than what the issuer intended to clawback, @@ -256,6 +306,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( holdLPtokens, 0, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, WithdrawAll::Yes, preFeeBalance_, ctx_.journal); @@ -288,6 +339,7 @@ AMMClawback::equalWithdrawMatchingOneAmount( tokensAdj, 0, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, WithdrawAll::No, preFeeBalance_, ctx_.journal); @@ -302,11 +354,12 @@ AMMClawback::equalWithdrawMatchingOneAmount( holder, amountBalance, amount, - toSTAmount(amount2Balance.issue(), amount2Withdraw), + toSTAmount(amount2Balance.asset(), amount2Withdraw), lptAMMBalance, - toSTAmount(lptAMMBalance.issue(), lptAMMBalance * frac), + toSTAmount(lptAMMBalance.asset(), lptAMMBalance * frac), 0, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, WithdrawAll::No, preFeeBalance_, ctx_.journal); diff --git a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp index 6dee6dfd2a..53680f360a 100644 --- a/src/libxrpl/tx/transactors/dex/AMMCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMCreate.cpp @@ -4,18 +4,27 @@ #include #include #include +#include #include #include #include #include #include +#include namespace xrpl { bool AMMCreate::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + if (!ctx.rules.enabled(featureMPTokensV2) && + (ctx.tx[sfAmount].holds() || ctx.tx[sfAmount2].holds())) + return false; + + return true; } NotTEC @@ -24,9 +33,9 @@ AMMCreate::preflight(PreflightContext const& ctx) auto const amount = ctx.tx[sfAmount]; auto const amount2 = ctx.tx[sfAmount2]; - if (amount.issue() == amount2.issue()) + if (amount.asset() == amount2.asset()) { - JLOG(ctx.j.debug()) << "AMM Instance: tokens can not have the same currency/issuer."; + JLOG(ctx.j.debug()) << "AMM Instance: tokens can not have the same asset."; return temBAD_AMM_TOKENS; } @@ -66,44 +75,44 @@ AMMCreate::preclaim(PreclaimContext const& ctx) auto const amount2 = ctx.tx[sfAmount2]; // Check if AMM already exists for the token pair - if (auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); + if (auto const ammKeylet = keylet::amm(amount.asset(), amount2.asset()); ctx.view.read(ammKeylet)) { JLOG(ctx.j.debug()) << "AMM Instance: ltAMM already exists."; return tecDUPLICATE; } - if (auto const ter = requireAuth(ctx.view, amount.issue(), accountID); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, amount.asset(), accountID); !isTesSuccess(ter)) { - JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount.issue(); + JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount.asset(); return ter; } - if (auto const ter = requireAuth(ctx.view, amount2.issue(), accountID); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, amount2.asset(), accountID); !isTesSuccess(ter)) { - JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount2.issue(); + JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount2.asset(); return ter; } // Globally or individually frozen - if (isFrozen(ctx.view, accountID, amount.issue()) || - isFrozen(ctx.view, accountID, amount2.issue())) + if (isFrozen(ctx.view, accountID, amount.asset()) || + isFrozen(ctx.view, accountID, amount2.asset())) { JLOG(ctx.j.debug()) << "AMM Instance: involves frozen asset."; return tecFROZEN; } - auto noDefaultRipple = [](ReadView const& view, Issue const& issue) { - if (isXRP(issue)) + auto noDefaultRipple = [](ReadView const& view, Asset const& asset) { + if (asset.holds() || isXRP(asset)) return false; - if (auto const issuerAccount = view.read(keylet::account(issue.account))) + if (auto const issuerAccount = view.read(keylet::account(asset.getIssuer()))) return (issuerAccount->getFlags() & lsfDefaultRipple) == 0; return false; }; - if (noDefaultRipple(ctx.view, amount.issue()) || noDefaultRipple(ctx.view, amount2.issue())) + if (noDefaultRipple(ctx.view, amount.asset()) || noDefaultRipple(ctx.view, amount2.asset())) { JLOG(ctx.j.debug()) << "AMM Instance: DefaultRipple not set"; return terNO_RIPPLE; @@ -118,13 +127,16 @@ AMMCreate::preclaim(PreclaimContext const& ctx) return tecINSUF_RESERVE_LINE; } - auto insufficientBalance = [&](STAmount const& asset) { - if (isXRP(asset)) - return xrpBalance < asset; - return accountID != asset.issue().account && - accountHolds( - ctx.view, accountID, asset.issue(), FreezeHandling::fhZERO_IF_FROZEN, ctx.j) < - asset; + auto insufficientBalance = [&](STAmount const& amount) { + if (isXRP(amount)) + return xrpBalance < amount; + return accountFunds( + ctx.view, + accountID, + amount, + FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahZERO_IF_UNAUTHORIZED, + ctx.j) < amount; }; if (insufficientBalance(amount) || insufficientBalance(amount2)) @@ -134,7 +146,7 @@ AMMCreate::preclaim(PreclaimContext const& ctx) } auto isLPToken = [&](STAmount const& amount) -> bool { - if (auto const sle = ctx.view.read(keylet::account(amount.issue().account))) + if (auto const sle = ctx.view.read(keylet::account(amount.asset().getIssuer()))) return sle->isFieldPresent(sfAMMID); return false; }; @@ -149,11 +161,18 @@ AMMCreate::preclaim(PreclaimContext const& ctx) if (ctx.view.rules().enabled(featureSingleAssetVault)) { if (auto const accountId = - pseudoAccountAddress(ctx.view, keylet::amm(amount.issue(), amount2.issue()).key); + pseudoAccountAddress(ctx.view, keylet::amm(amount.asset(), amount2.asset()).key); accountId == beast::zero) return terADDRESS_COLLISION; } + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_CREATE, amount.asset(), accountID); + !isTesSuccess(ter)) + return ter; + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_CREATE, amount2.asset(), accountID); + !isTesSuccess(ter)) + return ter; + // If featureAMMClawback is enabled, allow AMMCreate without checking // if the issuer has clawback enabled if (ctx.view.rules().enabled(featureAMMClawback)) @@ -161,20 +180,34 @@ AMMCreate::preclaim(PreclaimContext const& ctx) // Disallow AMM if the issuer has clawback enabled when featureAMMClawback // is not enabled - auto clawbackDisabled = [&](Issue const& issue) -> TER { - if (isXRP(issue)) - return tesSUCCESS; - auto const sle = ctx.view.read(keylet::account(issue.account)); - if (!sle) - return tecINTERNAL; // LCOV_EXCL_LINE - if (sle->getFlags() & lsfAllowTrustLineClawback) - return tecNO_PERMISSION; - return tesSUCCESS; + auto clawbackDisabled = [&](Asset const& asset) -> TER { + return asset.visit( + [&](MPTIssue const& issue) -> TER { + auto const sle = ctx.view.read(keylet::mptIssuance(issue.getMptID())); + if (!sle) + return tecINTERNAL; // LCOV_EXCL_LINE + if (sle->isFlag(lsfMPTCanClawback)) + return tecNO_PERMISSION; + return tesSUCCESS; + }, + [&](Issue const& issue) -> TER { + if (isXRP(issue)) + return tesSUCCESS; + auto const sle = ctx.view.read(keylet::account(issue.account)); + if (!sle) + return tecINTERNAL; // LCOV_EXCL_LINE + if (sle->isFlag(lsfAllowTrustLineClawback)) + return tecNO_PERMISSION; + return tesSUCCESS; + }); }; - if (auto const ter = clawbackDisabled(amount.issue()); !isTesSuccess(ter)) + if (auto const ter = clawbackDisabled(amount.asset()); !isTesSuccess(ter)) return ter; - return clawbackDisabled(amount2.issue()); + if (auto const ter = clawbackDisabled(amount2.asset()); !isTesSuccess(ter)) + return ter; + + return tesSUCCESS; } static std::pair @@ -183,7 +216,7 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J auto const amount = ctx_.tx[sfAmount]; auto const amount2 = ctx_.tx[sfAmount2]; - auto const ammKeylet = keylet::amm(amount.issue(), amount2.issue()); + auto const ammKeylet = keylet::amm(amount.asset(), amount2.asset()); // Mitigate same account exists possibility auto const maybeAccount = createPseudoAccount(sb, ammKeylet.key, sfAMMID); @@ -197,7 +230,7 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J auto const accountId = (*account)[sfAccount]; // LP Token already exists. (should not happen) - auto const lptIss = ammLPTIssue(amount.issue().currency, amount2.issue().currency, accountId); + auto const lptIss = ammLPTIssue(amount.asset(), amount2.asset(), accountId); if (sb.read(keylet::line(accountId, lptIss))) { JLOG(j_.error()) << "AMM Instance: LP Token already exists."; @@ -217,9 +250,9 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J auto ammSle = std::make_shared(ammKeylet); ammSle->setAccountID(sfAccount, accountId); ammSle->setFieldAmount(sfLPTokenBalance, lpTokens); - auto const& [issue1, issue2] = std::minmax(amount.issue(), amount2.issue()); - ammSle->setFieldIssue(sfAsset, STIssue{sfAsset, issue1}); - ammSle->setFieldIssue(sfAsset2, STIssue{sfAsset2, issue2}); + auto const& [asset1, asset2] = std::minmax(amount.asset(), amount2.asset()); + ammSle->setFieldIssue(sfAsset, STIssue{sfAsset, asset1}); + ammSle->setFieldIssue(sfAsset2, STIssue{sfAsset2, asset2}); // AMM creator gets the auction slot and the voting slot. initializeFeeAuctionVote(ctx_.view(), ammSle, account_, lptIss, ctx_.tx[sfTradingFee]); @@ -239,28 +272,59 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J return {res, false}; } - auto sendAndTrustSet = [&](STAmount const& amount) -> TER { - if (auto const res = - accountSend(sb, account_, accountId, amount, ctx_.journal, WaiveTransferFee::Yes)) - return res; - // Set AMM flag on AMM trustline - if (!isXRP(amount)) - { - SLE::pointer const sleRippleState = sb.peek(keylet::line(accountId, amount.issue())); - if (!sleRippleState) - { - return tecINTERNAL; // LCOV_EXCL_LINE - } + auto sendAndInitTrustOrMPT = [&](STAmount const& amount) -> TER { + // Authorize MPT + return amount.asset().visit( + [&](MPTIssue const& issue) -> TER { + // Authorize MPT + auto const& mptIssue = issue; + auto const& mptID = mptIssue.getMptID(); + std::uint32_t flags = lsfMPTAMM; + if (auto const err = + requireAuth(ctx_.view(), mptIssue, accountId, AuthType::WeakAuth); + !isTesSuccess(err)) + { + if (err == tecNO_AUTH) + { + flags |= lsfMPTAuthorized; + } + else + { + return err; + } + } - auto const flags = sleRippleState->getFlags(); - sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode); - sb.update(sleRippleState); - } - return tesSUCCESS; + if (auto const err = createMPToken(sb, mptID, accountId, flags); !isTesSuccess(err)) + return err; + // Don't adjust AMM owner count. + // It's irrelevant for pseudo-account like AMM. + return accountSend( + sb, account_, accountId, amount, ctx_.journal, WaiveTransferFee::Yes); + }, + // Set AMM flag on AMM trustline + [&](Issue const& issue) -> TER { + if (auto const res = accountSend( + sb, account_, accountId, amount, ctx_.journal, WaiveTransferFee::Yes)) + return res; + // Set AMM flag on AMM trustline + if (!isXRP(amount)) + { + SLE::pointer const sleRippleState = sb.peek(keylet::line(accountId, issue)); + if (!sleRippleState) + { + return tecINTERNAL; // LCOV_EXCL_LINE + } + + auto const flags = sleRippleState->getFlags(); + sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode); + sb.update(sleRippleState); + } + return tesSUCCESS; + }); }; // Send asset1. - res = sendAndTrustSet(amount); + res = sendAndInitTrustOrMPT(amount); if (!isTesSuccess(res)) { JLOG(j_.debug()) << "AMM Instance: failed to send " << amount; @@ -268,7 +332,7 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J } // Send asset2. - res = sendAndTrustSet(amount2); + res = sendAndInitTrustOrMPT(amount2); if (!isTesSuccess(res)) { JLOG(j_.debug()) << "AMM Instance: failed to send " << amount2; @@ -277,14 +341,14 @@ applyCreate(ApplyContext& ctx_, Sandbox& sb, AccountID const& account_, beast::J JLOG(j_.debug()) << "AMM Instance: success " << accountId << " " << ammKeylet.key << " " << lpTokens << " " << amount << " " << amount2; - auto addOrderBook = [&](Issue const& issueIn, Issue const& issueOut, std::uint64_t uRate) { - Book const book{issueIn, issueOut, std::nullopt}; + auto addOrderBook = [&](Asset const& assetIn, Asset const& assetOut, std::uint64_t uRate) { + Book const book{assetIn, assetOut, std::nullopt}; auto const dir = keylet::quality(keylet::book(book), uRate); if (auto const bookExisted = static_cast(sb.read(dir)); !bookExisted) ctx_.registry.get().getOrderBookDB().addOrderBook(book); }; - addOrderBook(amount.issue(), amount2.issue(), getRate(amount2, amount)); - addOrderBook(amount2.issue(), amount.issue(), getRate(amount, amount2)); + addOrderBook(amount.asset(), amount2.asset(), getRate(amount2, amount)); + addOrderBook(amount2.asset(), amount.asset(), getRate(amount, amount2)); return {res, isTesSuccess(res)}; } diff --git a/src/libxrpl/tx/transactors/dex/AMMDelete.cpp b/src/libxrpl/tx/transactors/dex/AMMDelete.cpp index 41e88e6a07..1033f22722 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDelete.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDelete.cpp @@ -10,7 +10,11 @@ namespace xrpl { bool AMMDelete::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + return ctx.rules.enabled(featureMPTokensV2) || + (!ctx.tx[sfAsset].holds() && !ctx.tx[sfAsset2].holds()); } NotTEC @@ -43,8 +47,7 @@ AMMDelete::doApply() // as we go on processing transactions. Sandbox sb(&ctx_.view()); - auto const ter = - deleteAMMAccount(sb, ctx_.tx[sfAsset].get(), ctx_.tx[sfAsset2].get(), j_); + auto const ter = deleteAMMAccount(sb, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_); if (isTesSuccess(ter) || ter == tecINCOMPLETE) sb.apply(ctx_.rawView()); diff --git a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp index 9a2955901b..4fc2c14de8 100644 --- a/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMDeposit.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -13,7 +14,15 @@ namespace xrpl { bool AMMDeposit::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + auto const amount = ctx.tx[~sfAmount]; + auto const amount2 = ctx.tx[~sfAmount2]; + + return ctx.rules.enabled(featureMPTokensV2) || + (!ctx.tx[sfAsset].holds() && !ctx.tx[sfAsset2].holds() && + !(amount && amount->holds()) && !(amount2 && amount2->holds())); } std::uint32_t @@ -26,7 +35,6 @@ NotTEC AMMDeposit::preflight(PreflightContext const& ctx) { auto const flags = ctx.tx.getFlags(); - auto const amount = ctx.tx[~sfAmount]; auto const amount2 = ctx.tx[~sfAmount2]; auto const ePrice = ctx.tx[~sfEPrice]; @@ -78,18 +86,18 @@ AMMDeposit::preflight(PreflightContext const& ctx) return temMALFORMED; } - auto const asset = ctx.tx[sfAsset].get(); - auto const asset2 = ctx.tx[sfAsset2].get(); + auto const asset = ctx.tx[sfAsset]; + auto const asset2 = ctx.tx[sfAsset2]; if (auto const res = invalidAMMAssetPair(asset, asset2)) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid asset pair."; return res; } - if (amount && amount2 && amount->issue() == amount2->issue()) + if (amount && amount2 && amount->asset() == amount2->asset()) { - JLOG(ctx.j.debug()) << "AMM Deposit: invalid tokens, same issue." << amount->issue() << " " - << amount2->issue(); + JLOG(ctx.j.debug()) << "AMM Deposit: invalid tokens, same issue." << amount->asset() << " " + << amount2->asset(); return temBAD_AMM_TOKENS; } @@ -119,11 +127,16 @@ AMMDeposit::preflight(PreflightContext const& ctx) } } - // must be amount issue if (amount && ePrice) { - if (auto const res = invalidAMMAmount( - *ePrice, std::make_optional(std::make_pair(amount->issue(), amount->issue())))) + auto assets = [&]() -> std::optional> { + // don't check ePrice issue + if (ctx.rules.enabled(featureMPTokensV2)) + return std::nullopt; + // must be amount issue + return std::make_optional(std::make_pair(amount->asset(), amount->asset())); + }(); + if (auto const res = invalidAMMAmount(*ePrice, assets)) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid EPrice"; return res; @@ -152,7 +165,13 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) } auto const expected = ammHolds( - ctx.view, *ammSle, std::nullopt, std::nullopt, FreezeHandling::fhIGNORE_FREEZE, ctx.j); + ctx.view, + *ammSle, + std::nullopt, + std::nullopt, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + ctx.j); if (!expected) return expected.error(); // LCOV_EXCL_LINE auto const [amountBalance, amount2Balance, lptAMMBalance] = *expected; @@ -190,7 +209,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) auto balance = [&](auto const& deposit) -> TER { if (isXRP(deposit)) { - auto const lpIssue = (*ammSle)[sfLPTokenBalance].issue(); + auto const lpIssue = (*ammSle)[sfLPTokenBalance].get(); // Adjust the reserve if LP doesn't have LPToken trustline auto const sle = ctx.view.read(keylet::line(accountID, lpIssue.account, lpIssue.currency)); @@ -200,10 +219,13 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return tecUNFUNDED_AMM; return tecINSUF_RESERVE_LINE; } - return (accountID == deposit.issue().account || - accountHolds( - ctx.view, accountID, deposit.issue(), FreezeHandling::fhIGNORE_FREEZE, ctx.j) >= - deposit) + return accountFunds( + ctx.view, + accountID, + deposit, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + ctx.j) >= deposit ? TER(tesSUCCESS) : tecUNFUNDED_AMM; }; @@ -212,8 +234,11 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) { // Check if either of the assets is frozen, AMMDeposit is not allowed // if either asset is frozen - auto checkAsset = [&](Issue const& asset) -> TER { - if (auto const ter = requireAuth(ctx.view, asset, accountID)) + auto checkAsset = [&](Asset const& asset) -> TER { + // WeakAuth - don't need to check if MPT object exists as might be + // depositing into non-MPT pool. It'll fail on send if MPT doesn't + // exist. + if (auto const ter = requireAuth(ctx.view, asset, accountID, AuthType::WeakAuth)) { JLOG(ctx.j.debug()) << "AMM Deposit: account is not authorized, " << asset; return ter; @@ -222,7 +247,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) if (isFrozen(ctx.view, accountID, asset)) { JLOG(ctx.j.debug()) << "AMM Deposit: account or currency is frozen, " - << to_string(accountID) << " " << to_string(asset.currency); + << to_string(accountID) << " " << to_string(asset); return tecFROZEN; } @@ -230,10 +255,10 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) return tesSUCCESS; }; - if (auto const ter = checkAsset(ctx.tx[sfAsset].get())) + if (auto const ter = checkAsset(ctx.tx[sfAsset])) return ter; - if (auto const ter = checkAsset(ctx.tx[sfAsset2].get())) + if (auto const ter = checkAsset(ctx.tx[sfAsset2])) return ter; } @@ -246,27 +271,27 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) { // This normally should not happen. // Account is not authorized to hold the assets it's depositing, - // or it doesn't even have a trust line for them - if (auto const ter = requireAuth(ctx.view, amount->issue(), accountID)) + // or it doesn't even have a trust line or MPT for them. + if (auto const ter = requireAuth(ctx.view, amount->asset(), accountID)) { // LCOV_EXCL_START JLOG(ctx.j.debug()) - << "AMM Deposit: account is not authorized, " << amount->issue(); + << "AMM Deposit: account is not authorized, " << amount->asset(); return ter; // LCOV_EXCL_STOP } // AMM account or currency frozen - if (isFrozen(ctx.view, ammAccountID, amount->issue())) + if (isFrozen(ctx.view, ammAccountID, amount->asset())) { JLOG(ctx.j.debug()) << "AMM Deposit: AMM account or currency is frozen, " << to_string(accountID); return tecFROZEN; } // Account frozen - if (isIndividualFrozen(ctx.view, accountID, amount->issue())) + if (isIndividualFrozen(ctx.view, accountID, amount->asset())) { JLOG(ctx.j.debug()) << "AMM Deposit: account is frozen, " << to_string(accountID) - << " " << to_string(amount->issue().currency); + << " " << to_string(amount->asset()); return tecFROZEN; } if (checkBalance) @@ -301,7 +326,7 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) // Equal deposit lp tokens if (auto const lpTokens = ctx.tx[~sfLPTokenOut]; - lpTokens && lpTokens->issue() != lptAMMBalance.issue()) + lpTokens && lpTokens->asset() != lptAMMBalance.asset()) { JLOG(ctx.j.debug()) << "AMM Deposit: invalid LPTokens."; return temBAD_AMM_TOKENS; @@ -320,6 +345,13 @@ AMMDeposit::preclaim(PreclaimContext const& ctx) } } + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_DEPOSIT, ctx.tx[sfAsset], accountID); + !isTesSuccess(ter)) + return ter; + if (auto const ter = checkMPTTxAllowed(ctx.view, ttAMM_DEPOSIT, ctx.tx[sfAsset2], accountID); + !isTesSuccess(ter)) + return ter; + return tesSUCCESS; } @@ -338,9 +370,10 @@ AMMDeposit::applyGuts(Sandbox& sb) auto const expected = ammHolds( sb, *ammSle, - amount ? amount->issue() : std::optional{}, - amount2 ? amount2->issue() : std::optional{}, + amount ? amount->asset() : std::optional{}, + amount2 ? amount2->asset() : std::optional{}, FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahZERO_IF_UNAUTHORIZED, ctx_.journal); if (!expected) return {expected.error(), false}; // LCOV_EXCL_LINE @@ -400,7 +433,7 @@ AMMDeposit::applyGuts(Sandbox& sb) if (subTxType & tfTwoAssetIfEmpty) { return equalDepositInEmptyState( - sb, ammAccountID, *amount, *amount2, lptAMMBalance.issue(), tfee); + sb, ammAccountID, *amount, *amount2, lptAMMBalance.asset(), tfee); } // should not happen. // LCOV_EXCL_START @@ -418,7 +451,7 @@ AMMDeposit::applyGuts(Sandbox& sb) // LP depositing into AMM empty state gets the auction slot // and the voting if (lptAMMBalance == beast::zero) - initializeFeeAuctionVote(sb, ammSle, account_, lptAMMBalance.issue(), tfee); + initializeFeeAuctionVote(sb, ammSle, account_, lptAMMBalance.asset(), tfee); sb.update(ammSle); } @@ -461,19 +494,19 @@ AMMDeposit::deposit( return temBAD_AMOUNT; if (isXRP(depositAmount)) { - auto const& lpIssue = lpTokensDeposit.issue(); + auto const& lpIssue = lpTokensDeposit.get(); // Adjust the reserve if LP doesn't have LPToken trustline auto const sle = view.read(keylet::line(account_, lpIssue.account, lpIssue.currency)); if (xrpLiquid(view, account_, !sle, j_) >= depositAmount) return tesSUCCESS; } else if ( - account_ == depositAmount.issue().account || - accountHolds( + accountFunds( view, account_, - depositAmount.issue(), + depositAmount, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, ctx_.journal) >= depositAmount) { return tesSUCCESS; @@ -588,7 +621,7 @@ AMMDeposit::equalDepositTokens( auto const tokensAdj = adjustLPTokensOut(view.rules(), lptAMMBalance, lpTokensDeposit); if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}}; - auto const frac = divide(tokensAdj, lptAMMBalance, lptAMMBalance.issue()); + auto const frac = divide(tokensAdj, lptAMMBalance, lptAMMBalance.asset()); // amounts factor in the adjusted tokens auto const amountDeposit = getRoundedAsset(view.rules(), amountBalance, frac, IsDeposit::Yes); @@ -934,7 +967,7 @@ AMMDeposit::equalDepositInEmptyState( AccountID const& ammAccount, STAmount const& amount, STAmount const& amount2, - Issue const& lptIssue, + Asset const& lptIssue, std::uint16_t tfee) { return deposit( diff --git a/src/libxrpl/tx/transactors/dex/AMMVote.cpp b/src/libxrpl/tx/transactors/dex/AMMVote.cpp index e1b3afcd08..ed75cf5d90 100644 --- a/src/libxrpl/tx/transactors/dex/AMMVote.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMVote.cpp @@ -10,14 +10,17 @@ namespace xrpl { bool AMMVote::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + return ctx.rules.enabled(featureMPTokensV2) || + (!ctx.tx[sfAsset].holds() && !ctx.tx[sfAsset2].holds()); } NotTEC AMMVote::preflight(PreflightContext const& ctx) { - if (auto const res = - invalidAMMAssetPair(ctx.tx[sfAsset].get(), ctx.tx[sfAsset2].get())) + if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2])) { JLOG(ctx.j.debug()) << "AMM Vote: invalid asset pair."; return res; diff --git a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp index 0c6419f842..f4f27309b5 100644 --- a/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp +++ b/src/libxrpl/tx/transactors/dex/AMMWithdraw.cpp @@ -2,16 +2,27 @@ #include #include #include +#include +#include #include #include #include +#include namespace xrpl { bool AMMWithdraw::checkExtraFeatures(PreflightContext const& ctx) { - return ammEnabled(ctx.rules); + if (!ammEnabled(ctx.rules)) + return false; + + auto const amount = ctx.tx[~sfAmount]; + auto const amount2 = ctx.tx[~sfAmount2]; + + return ctx.rules.enabled(featureMPTokensV2) || + (!ctx.tx[sfAsset].holds() && !ctx.tx[sfAsset2].holds() && + !(amount && amount->holds()) && !(amount2 && amount2->holds())); } std::uint32_t @@ -78,18 +89,18 @@ AMMWithdraw::preflight(PreflightContext const& ctx) return temMALFORMED; } - auto const asset = ctx.tx[sfAsset].get(); - auto const asset2 = ctx.tx[sfAsset2].get(); + auto const asset = ctx.tx[sfAsset]; + auto const asset2 = ctx.tx[sfAsset2]; if (auto const res = invalidAMMAssetPair(asset, asset2)) { JLOG(ctx.j.debug()) << "AMM Withdraw: Invalid asset pair."; return res; } - if (amount && amount2 && amount->issue() == amount2->issue()) + if (amount && amount2 && amount->asset() == amount2->asset()) { - JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens, same issue." << amount->issue() << " " - << amount2->issue(); + JLOG(ctx.j.debug()) << "AMM Withdraw: invalid tokens, same issue." << amount->asset() << " " + << amount2->asset(); return temBAD_AMM_TOKENS; } @@ -162,9 +173,10 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) auto const expected = ammHolds( ctx.view, *ammSle, - amount ? amount->issue() : std::optional{}, - amount2 ? amount2->issue() : std::optional{}, + amount ? amount->asset() : std::optional{}, + amount2 ? amount2->asset() : std::optional{}, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, ctx.j); if (!expected) return expected.error(); @@ -191,26 +203,33 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) << "AMM Withdraw: withdrawing more than the balance, " << *amount; return tecAMM_BALANCE; } - if (auto const ter = requireAuth(ctx.view, amount->issue(), accountID)) + // WeakAuth - MPToken is created if it doesn't exist. + if (auto const ter = + requireAuth(ctx.view, amount->asset(), accountID, AuthType::WeakAuth)) { JLOG(ctx.j.debug()) - << "AMM Withdraw: account is not authorized, " << amount->issue(); + << "AMM Withdraw: account is not authorized, " << amount->asset(); return ter; } // AMM account or currency frozen - if (isFrozen(ctx.view, ammAccountID, amount->issue())) + if (isFrozen(ctx.view, ammAccountID, amount->asset())) { JLOG(ctx.j.debug()) << "AMM Withdraw: AMM account or currency is frozen, " << to_string(accountID); return tecFROZEN; } // Account frozen - if (isIndividualFrozen(ctx.view, accountID, amount->issue())) + if (isIndividualFrozen(ctx.view, accountID, amount->asset())) { JLOG(ctx.j.debug()) << "AMM Withdraw: account is frozen, " << to_string(accountID) - << " " << to_string(amount->issue().currency); + << " " << to_string(amount->asset()); return tecFROZEN; } + + if (auto const ter = + checkMPTTxAllowed(ctx.view, ttAMM_WITHDRAW, amount->asset(), accountID); + !isTesSuccess(ter)) + return ter; } return tesSUCCESS; }; @@ -230,7 +249,7 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) return tecAMM_BALANCE; } - if (lpTokensWithdraw && lpTokensWithdraw->issue() != lpTokens.issue()) + if (lpTokensWithdraw && lpTokensWithdraw->asset() != lpTokens.asset()) { JLOG(ctx.j.debug()) << "AMM Withdraw: invalid LPTokens."; return temBAD_AMM_TOKENS; @@ -242,7 +261,7 @@ AMMWithdraw::preclaim(PreclaimContext const& ctx) return tecAMM_INVALID_TOKENS; } - if (auto const ePrice = ctx.tx[~sfEPrice]; ePrice && ePrice->issue() != lpTokens.issue()) + if (auto const ePrice = ctx.tx[~sfEPrice]; ePrice && ePrice->asset() != lpTokens.asset()) { JLOG(ctx.j.debug()) << "AMM Withdraw: invalid EPrice."; return temBAD_AMM_TOKENS; @@ -289,9 +308,10 @@ AMMWithdraw::applyGuts(Sandbox& sb) auto const expected = ammHolds( sb, *ammSle, - amount ? amount->issue() : std::optional{}, - amount2 ? amount2->issue() : std::optional{}, + amount ? amount->asset() : std::optional{}, + amount2 ? amount2->asset() : std::optional{}, FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahZERO_IF_UNAUTHORIZED, ctx_.journal); if (!expected) return {expected.error(), false}; @@ -363,12 +383,7 @@ AMMWithdraw::applyGuts(Sandbox& sb) return {result, false}; auto const res = deleteAMMAccountIfEmpty( - sb, - ammSle, - newLPTokenBalance, - ctx_.tx[sfAsset].get(), - ctx_.tx[sfAsset2].get(), - j_); + sb, ammSle, newLPTokenBalance, ctx_.tx[sfAsset], ctx_.tx[sfAsset2], j_); // LCOV_EXCL_START if (!res.second) return {res.first, false}; @@ -421,6 +436,7 @@ AMMWithdraw::withdraw( lpTokensWithdraw, tfee, FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahZERO_IF_UNAUTHORIZED, isWithdrawAll(ctx_.tx), preFeeBalance_, j_); @@ -440,13 +456,14 @@ AMMWithdraw::withdraw( STAmount const& lpTokensWithdraw, std::uint16_t tfee, FreezeHandling freezeHandling, + AuthHandling authHandling, WithdrawAll withdrawAll, XRPAmount const& priorBalance, beast::Journal const& journal) { auto const lpTokens = ammLPHolds(view, ammSle, account, journal); - auto const expected = - ammHolds(view, ammSle, amountWithdraw.issue(), std::nullopt, freezeHandling, journal); + auto const expected = ammHolds( + view, ammSle, amountWithdraw.asset(), std::nullopt, freezeHandling, authHandling, journal); // LCOV_EXCL_START if (!expected) return {expected.error(), STAmount{}, STAmount{}, STAmount{}}; @@ -525,33 +542,102 @@ AMMWithdraw::withdraw( return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}}; } - // Check the reserve in case a trustline has to be created - bool const enabledFixAMMv1_2 = view.rules().enabled(fixAMMv1_2); - auto sufficientReserve = [&](Issue const& issue) -> TER { - if (!enabledFixAMMv1_2 || isXRP(issue)) - return tesSUCCESS; - if (!view.exists(keylet::line(account, issue))) + // Updated pool state must be valid - either all balances are zero + // or all balances are non-zero. + if (view.rules().enabled(featureMPTokensV2)) + { + bool const newBalanceZero = (curBalance - amountWithdrawActual) == beast::zero; + bool const newBalance2Zero = + (curBalance2 - amount2WithdrawActual.value_or(curBalance2.asset())) == beast::zero; + bool const newLPTokensZero = (lpTokensAMMBalance - lpTokensWithdrawActual) == beast::zero; + // newBalance2Zero can be zero if that side of the pool is frozen. + // ignore newBalance2Zero if one-sided withdrawal. + bool const valid = [&]() { + if (!amount2WithdrawActual) + return newBalanceZero == newLPTokensZero; + return newBalanceZero == newBalance2Zero && newBalance2Zero == newLPTokensZero; + }(); + if (!valid) { - auto const sleAccount = view.read(keylet::account(account)); + JLOG(journal.debug()) << "AMM Withdraw: some balances are zero" + << " curBalance: " << curBalance << " " << amountWithdrawActual + << " curBalance2: " << curBalance2 << " " + << (amount2WithdrawActual ? *amount2WithdrawActual : STAmount{}) + << " lpTokensBalance: " << lpTokensWithdraw << " lptBalance " + << lpTokensAMMBalance; + return {tecAMM_BALANCE, STAmount{}, STAmount{}, STAmount{}}; + } + } + + // Check the reserve in case a trustline or MPT has to be created + bool const enabledFixAMMv1_2 = view.rules().enabled(fixAMMv1_2); + // If seated after a call to sufficientReserve() then MPToken must be + // authorized + std::optional mptokenKey; + auto sufficientReserve = [&](Asset const& asset) -> TER { + mptokenKey = std::nullopt; + if (!enabledFixAMMv1_2 || isXRP(asset)) + return tesSUCCESS; + bool const isIssue = asset.holds(); + bool const assetNotExists = [&] { + if (isIssue) + return !view.exists(keylet::line(account, asset.get())); + auto const issuanceKey = keylet::mptIssuance(asset.get()); + mptokenKey = keylet::mptoken(issuanceKey.key, account); + if (!view.exists(*mptokenKey)) + return true; + mptokenKey = std::nullopt; + return false; + }(); + if (assetNotExists) + { + auto sleAccount = view.peek(keylet::account(account)); if (!sleAccount) return tecINTERNAL; // LCOV_EXCL_LINE - auto const balance = (*sleAccount)[sfBalance].xrp(); + STAmount const balance = (*sleAccount)[sfBalance]; std::uint32_t const ownerCount = sleAccount->at(sfOwnerCount); - // See also TrustSet::doApply() + // See also TrustSet::doApply() and MPTokenAuthorize::authorize() XRPAmount const reserve( (ownerCount < 2) ? XRPAmount(beast::zero) : view.fees().accountReserve(ownerCount + 1)); - if (std::max(priorBalance, balance) < reserve) + auto const balance_ = isIssue ? std::max(priorBalance, balance.xrp()) : priorBalance; + if (balance_ < reserve) return tecINSUFFICIENT_RESERVE; + + // Update owner count. + if (!isIssue) + adjustOwnerCount(view, sleAccount, 1, journal); } return tesSUCCESS; }; - if (auto const err = sufficientReserve(amountWithdrawActual.issue())) + // Create MPToken if it doesn't exist + auto createMPToken = [&](Asset const& asset) -> TER { + // If mptoken is seated then must authorize + if (mptokenKey && account != asset.getIssuer()) + { + auto const& mptIssue = asset.get(); + if (auto const err = requireAuth(view, mptIssue, account, AuthType::WeakAuth); + !isTesSuccess(err)) + return err; + + if (auto const err = checkCreateMPT(view, mptIssue, account, journal); + !isTesSuccess(err)) + { + return err; + } + } + return tesSUCCESS; + }; + + if (auto const err = sufficientReserve(amountWithdrawActual.asset())) return {err, STAmount{}, STAmount{}, STAmount{}}; + if (auto const res = createMPToken(amountWithdrawActual.asset()); !isTesSuccess(res)) + return {res, STAmount{}, STAmount{}, STAmount{}}; + // Withdraw amountWithdraw auto res = accountSend( view, ammAccount, account, amountWithdrawActual, journal, WaiveTransferFee::Yes); @@ -566,9 +652,12 @@ AMMWithdraw::withdraw( // Withdraw amount2Withdraw if (amount2WithdrawActual) { - if (auto const err = sufficientReserve(amount2WithdrawActual->issue()); !isTesSuccess(err)) + if (auto const err = sufficientReserve(amount2WithdrawActual->asset()); !isTesSuccess(err)) return {err, STAmount{}, STAmount{}, STAmount{}}; + if (auto const res = createMPToken(amount2WithdrawActual->asset()); !isTesSuccess(res)) + return {res, STAmount{}, STAmount{}, STAmount{}}; + res = accountSend( view, ammAccount, account, *amount2WithdrawActual, journal, WaiveTransferFee::Yes); if (!isTesSuccess(res)) @@ -581,7 +670,8 @@ AMMWithdraw::withdraw( } // Withdraw LP tokens - res = redeemIOU(view, account, lpTokensWithdrawActual, lpTokensWithdrawActual.issue(), journal); + res = redeemIOU( + view, account, lpTokensWithdrawActual, lpTokensWithdrawActual.get(), journal); if (!isTesSuccess(res)) { // LCOV_EXCL_START @@ -637,6 +727,7 @@ AMMWithdraw::equalWithdrawTokens( lpTokensWithdraw, tfee, FreezeHandling::fhZERO_IF_FROZEN, + AuthHandling::ahZERO_IF_UNAUTHORIZED, isWithdrawAll(ctx_.tx), preFeeBalance_, ctx_.journal); @@ -648,15 +739,15 @@ AMMWithdraw::deleteAMMAccountIfEmpty( Sandbox& sb, std::shared_ptr const ammSle, STAmount const& lpTokenBalance, - Issue const& issue1, - Issue const& issue2, + Asset const& asset1, + Asset const& asset2, beast::Journal const& journal) { TER ter; bool updateBalance = true; if (lpTokenBalance == beast::zero) { - ter = deleteAMMAccount(sb, issue1, issue2, journal); + ter = deleteAMMAccount(sb, asset1, asset2, journal); if (!isTesSuccess(ter) && ter != tecINCOMPLETE) return {ter, false}; // LCOV_EXCL_LINE @@ -687,6 +778,7 @@ AMMWithdraw::equalWithdrawTokens( STAmount const& lpTokensWithdraw, std::uint16_t tfee, FreezeHandling freezeHandling, + AuthHandling authHandling, WithdrawAll withdrawAll, XRPAmount const& priorBalance, beast::Journal const& journal) @@ -708,6 +800,7 @@ AMMWithdraw::equalWithdrawTokens( lpTokensWithdraw, tfee, freezeHandling, + authHandling, WithdrawAll::Yes, priorBalance, journal); @@ -742,6 +835,7 @@ AMMWithdraw::equalWithdrawTokens( tokensAdj, tfee, freezeHandling, + authHandling, withdrawAll, priorBalance, journal); @@ -793,13 +887,12 @@ AMMWithdraw::equalWithdrawLimit( std::uint16_t tfee) { auto frac = Number{amount} / amountBalance; - auto amount2Withdraw = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No); auto tokensAdj = getRoundedLPTokens(view.rules(), lptAMMBalance, frac, IsDeposit::No); if (view.rules().enabled(fixAMMv1_3) && tokensAdj == beast::zero) return {tecAMM_INVALID_TOKENS, STAmount{}}; // factor in the adjusted tokens frac = adjustFracByTokens(view.rules(), lptAMMBalance, tokensAdj, frac); - amount2Withdraw = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No); + auto const amount2Withdraw = getRoundedAsset(view.rules(), amount2Balance, frac, IsDeposit::No); if (amount2Withdraw <= amount2) { return withdraw( diff --git a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp index 71343ca8ab..2568806f51 100644 --- a/src/libxrpl/tx/transactors/dex/OfferCreate.cpp +++ b/src/libxrpl/tx/transactors/dex/OfferCreate.cpp @@ -1,9 +1,9 @@ #include -#include #include #include #include #include +#include #include #include #include @@ -11,7 +11,6 @@ #include #include #include -#include #include #include @@ -30,7 +29,11 @@ OfferCreate::makeTxConsequences(PreflightContext const& ctx) bool OfferCreate::checkExtraFeatures(PreflightContext const& ctx) { - return !ctx.tx.isFieldPresent(sfDomainID) || ctx.rules.enabled(featurePermissionedDEX); + if (ctx.tx.isFieldPresent(sfDomainID) && !ctx.rules.enabled(featurePermissionedDEX)) + return false; + + return ctx.rules.enabled(featureMPTokensV2) || + (!ctx.tx[sfTakerPays].holds() && !ctx.tx[sfTakerGets].holds()); } std::uint32_t @@ -97,18 +100,18 @@ OfferCreate::preflight(PreflightContext const& ctx) } auto const& uPaysIssuerID = saTakerPays.getIssuer(); - auto const& uPaysCurrency = saTakerPays.getCurrency(); + auto const& uPaysAsset = saTakerPays.asset(); auto const& uGetsIssuerID = saTakerGets.getIssuer(); - auto const& uGetsCurrency = saTakerGets.getCurrency(); + auto const& uGetsAsset = saTakerGets.asset(); - if (uPaysCurrency == uGetsCurrency && uPaysIssuerID == uGetsIssuerID) + if (uPaysAsset == uGetsAsset) { JLOG(j.debug()) << "Malformed offer: redundant (IOU for IOU)"; return temREDUNDANT; } // We don't allow a non-native currency to use the currency code XRP. - if (badCurrency() == uPaysCurrency || badCurrency() == uGetsCurrency) + if (badAsset() == uPaysAsset || badAsset() == uGetsAsset) { JLOG(j.debug()) << "Malformed offer: bad currency"; return temBAD_CURRENCY; @@ -131,10 +134,7 @@ OfferCreate::preclaim(PreclaimContext const& ctx) auto saTakerPays = ctx.tx[sfTakerPays]; auto saTakerGets = ctx.tx[sfTakerGets]; - auto const& uPaysIssuerID = saTakerPays.getIssuer(); - auto const& uPaysCurrency = saTakerPays.getCurrency(); - - auto const& uGetsIssuerID = saTakerGets.getIssuer(); + auto const& uPaysAsset = saTakerPays.asset(); auto const cancelSequence = ctx.tx[~sfOfferSequence]; @@ -146,13 +146,17 @@ OfferCreate::preclaim(PreclaimContext const& ctx) auto viewJ = ctx.registry.get().getJournal("View"); - if (isGlobalFrozen(ctx.view, uPaysIssuerID) || isGlobalFrozen(ctx.view, uGetsIssuerID)) + if (isGlobalFrozen(ctx.view, saTakerPays.asset()) || + isGlobalFrozen(ctx.view, saTakerGets.asset())) { JLOG(ctx.j.debug()) << "Offer involves frozen asset"; return tecFROZEN; } - if (accountFunds(ctx.view, id, saTakerGets, fhZERO_IF_FROZEN, viewJ) <= beast::zero) + // Allow unfunded MPT for issuer (OutstandingAmount >= MaximumAmount) + if ((!saTakerGets.holds() || saTakerGets.getIssuer() != id) && + accountFunds(ctx.view, id, saTakerGets, fhZERO_IF_FROZEN, ahZERO_IF_UNAUTHORIZED, viewJ) <= + beast::zero) { JLOG(ctx.j.debug()) << "delay: Offers must be at least partially funded."; return tecUNFUNDED_OFFER; @@ -177,8 +181,7 @@ OfferCreate::preclaim(PreclaimContext const& ctx) // Make sure that we are authorized to hold what the taker will pay us. if (!saTakerPays.native()) { - auto result = - checkAcceptAsset(ctx.view, ctx.flags, id, ctx.j, Issue(uPaysCurrency, uPaysIssuerID)); + auto result = checkAcceptAsset(ctx.view, ctx.flags, id, ctx.j, uPaysAsset); if (!isTesSuccess(result)) return result; } @@ -191,6 +194,11 @@ OfferCreate::preclaim(PreclaimContext const& ctx) return tecNO_PERMISSION; } + if (auto const ter = canTrade(ctx.view, saTakerPays.asset()); !isTesSuccess(ter)) + return ter; + if (auto const ter = canTrade(ctx.view, saTakerGets.asset()); !isTesSuccess(ter)) + return ter; + return tesSUCCESS; } @@ -200,17 +208,17 @@ OfferCreate::checkAcceptAsset( ApplyFlags const flags, AccountID const id, beast::Journal const j, - Issue const& issue) + Asset const& asset) { // Only valid for custom currencies - XRPL_ASSERT(!isXRP(issue.currency), "xrpl::OfferCreate::checkAcceptAsset : input is not XRP"); + XRPL_ASSERT(!isXRP(asset), "xrpl::OfferCreate::checkAcceptAsset : input is not XRP"); - auto const issuerAccount = view.read(keylet::account(issue.account)); + auto const issuerAccount = view.read(keylet::account(asset.getIssuer())); if (!issuerAccount) { JLOG(j.debug()) << "delay: can't receive IOUs from non-existent issuer: " - << to_string(issue.account); + << to_string(asset.getIssuer()); return ((flags & tapRETRY) != 0u) ? TER{terNO_ACCOUNT} : TER{tecNO_ISSUER}; } @@ -218,51 +226,63 @@ OfferCreate::checkAcceptAsset( // An account cannot create a trustline to itself, so no line can exist // to be frozen. Additionally, an issuer can always accept its own // issuance. - if (issue.account == id) + if (asset.getIssuer() == id) return tesSUCCESS; - if (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u) - { - auto const trustLine = view.read(keylet::line(id, issue.account, issue.currency)); + return asset.visit( + [&](Issue const& issue) -> TER { + auto const& issuer = issue.getIssuer(); + if (((*issuerAccount)[sfFlags] & lsfRequireAuth) != 0u) + { + auto const trustLine = view.read(keylet::line(id, issuer, issue.currency)); - if (!trustLine) - { - return ((flags & tapRETRY) != 0u) ? TER{terNO_LINE} : TER{tecNO_LINE}; - } + if (!trustLine) + { + return ((flags & tapRETRY) != 0u) ? TER{terNO_LINE} : TER{tecNO_LINE}; + } - // Entries have a canonical representation, determined by a - // lexicographical "greater than" comparison employing strict weak - // ordering. Determine which entry we need to access. - bool const canonical_gt(id > issue.account); + // Entries have a canonical representation, determined by a + // lexicographical "greater than" comparison employing + // strict weak ordering. Determine which entry we need to + // access. + bool const canonical_gt(id > issuer); - bool const is_authorized( - ((*trustLine)[sfFlags] & (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); + bool const is_authorized( + ((*trustLine)[sfFlags] & (canonical_gt ? lsfLowAuth : lsfHighAuth)) != 0u); - if (!is_authorized) - { - JLOG(j.debug()) << "delay: can't receive IOUs from issuer without auth."; + if (!is_authorized) + { + JLOG(j.debug()) << "delay: can't receive IOUs from " + "issuer without auth."; - return ((flags & tapRETRY) != 0u) ? TER{terNO_AUTH} : TER{tecNO_AUTH}; - } - } + return ((flags & tapRETRY) != 0u) ? TER{terNO_AUTH} : TER{tecNO_AUTH}; + } + } - auto const trustLine = view.read(keylet::line(id, issue.account, issue.currency)); + auto const trustLine = view.read(keylet::line(id, issue.account, issue.currency)); - if (!trustLine) - { - return tesSUCCESS; - } + if (!trustLine) + { + return tesSUCCESS; + } - // There's no difference which side enacted deep freeze, accepting - // tokens shouldn't be possible. - bool const deepFrozen = ((*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze)) != 0u; + // There's no difference which side enacted deep freeze, accepting + // tokens shouldn't be possible. + bool const deepFrozen = + ((*trustLine)[sfFlags] & (lsfLowDeepFreeze | lsfHighDeepFreeze)) != 0u; - if (deepFrozen) - { - return tecFROZEN; - } + if (deepFrozen) + { + return tecFROZEN; + } - return tesSUCCESS; + return tesSUCCESS; + }, + [&](MPTIssue const& issue) -> TER { + // WeakAuth - don't check if MPToken exists since it's created + // if needed. + return requireAuth(view, issue, id, AuthType::WeakAuth); + }); } std::pair @@ -280,9 +300,12 @@ OfferCreate::flowCross( // We check this in preclaim, but when selling XRP charged fees can // cause a user's available balance to go to 0 (by causing it to dip // below the reserve) so we check this case again. - STAmount const inStartBalance = - accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); - if (inStartBalance <= beast::zero) + STAmount const inStartBalance = accountFunds( + psb, account_, takerAmount.in, fhZERO_IF_FROZEN, ahZERO_IF_UNAUTHORIZED, j_); + // Allow unfunded MPT issuer + auto const disallowUnfunded = + !inStartBalance.holds() || inStartBalance.getIssuer() != account_; + if (disallowUnfunded && inStartBalance <= beast::zero) { // The account balance can't cover even part of the offer. JLOG(j_.debug()) << "Not crossing: taker is unfunded."; @@ -296,11 +319,11 @@ OfferCreate::flowCross( STAmount sendMax = takerAmount.in; if (!sendMax.native() && (account_ != sendMax.getIssuer())) { - gatewayXferRate = transferRate(psb, sendMax.getIssuer()); + gatewayXferRate = transferRate(psb, sendMax); if (gatewayXferRate.value != QUALITY_ONE) { sendMax = - multiplyRound(takerAmount.in, gatewayXferRate, takerAmount.in.issue(), true); + multiplyRound(takerAmount.in, gatewayXferRate, takerAmount.in.asset(), true); } } @@ -331,6 +354,7 @@ OfferCreate::flowCross( } // Special handling for the tfSell flag. STAmount deliver = takerAmount.out; + auto const& deliverAsset = deliver.asset(); OfferCrossing offerCrossing = OfferCrossing::yes; if ((txFlags & tfSell) != 0u) { @@ -338,19 +362,23 @@ OfferCreate::flowCross( // We are selling, so we will accept *more* than the offer // specified. Since we don't know how much they might offer, // we allow delivery of the largest possible amount. - if (deliver.native()) - { - deliver = STAmount{STAmount::cMaxNative}; - } - else - { - // We can't use the maximum possible currency here because - // there might be a gateway transfer rate to account for. - // Since the transfer rate cannot exceed 200%, we use 1/2 - // maxValue for our limit. - deliver = STAmount{ - takerAmount.out.issue(), STAmount::cMaxValue / 2, STAmount::cMaxOffset}; - } + deliver.asset().visit( + [&](Issue const& issue) { + if (issue.native()) + { + deliver = STAmount{STAmount::cMaxNative}; + } + // We can't use the maximum possible currency here because + // there might be a gateway transfer rate to account for. + // Since the transfer rate cannot exceed 200%, we use 1/2 + // maxValue for our limit. + else + { + deliver = + STAmount{deliverAsset, STAmount::cMaxValue / 2, STAmount::cMaxOffset}; + } + }, + [&](MPTIssue const&) { deliver = STAmount{deliverAsset, maxMPTokenAmount / 2}; }); } // Call the payment engine's flow() to do the actual work. @@ -382,10 +410,10 @@ OfferCreate::flowCross( auto afterCross = takerAmount; // If !tesSUCCESS offer unchanged if (isTesSuccess(result.result())) { - STAmount const takerInBalance = - accountFunds(psb, account_, takerAmount.in, fhZERO_IF_FROZEN, j_); + STAmount const takerInBalance = accountFunds( + psb, account_, takerAmount.in, fhZERO_IF_FROZEN, ahZERO_IF_UNAUTHORIZED, j_); - if (takerInBalance <= beast::zero) + if (disallowUnfunded && takerInBalance <= beast::zero) { // If offer crossing exhausted the account's funds don't // create the offer. @@ -410,7 +438,7 @@ OfferCreate::flowCross( if (gatewayXferRate.value != QUALITY_ONE) { nonGatewayAmountIn = divideRound( - result.actualAmountIn, gatewayXferRate, takerAmount.in.issue(), true); + result.actualAmountIn, gatewayXferRate, takerAmount.in.asset(), true); } afterCross.in -= nonGatewayAmountIn; @@ -425,7 +453,7 @@ OfferCreate::flowCross( } afterCross.out = - divRoundStrict(afterCross.in, rate, takerAmount.out.issue(), false); + divRoundStrict(afterCross.in, rate, takerAmount.out.asset(), false); } else { @@ -438,7 +466,7 @@ OfferCreate::flowCross( "xrpl::OfferCreate::flowCross : minimum offer"); if (afterCross.out < beast::zero) afterCross.out.clear(); - afterCross.in = mulRound(afterCross.out, rate, takerAmount.in.issue(), true); + afterCross.in = mulRound(afterCross.out, rate, takerAmount.in.asset(), true); } } } @@ -458,7 +486,9 @@ OfferCreate::format_amount(STAmount const& amount) { std::string txt = amount.getText(); txt += "/"; - txt += to_string(amount.issue().currency); + amount.asset().visit( + [&](Issue const& issue) { txt += to_string(issue.currency); }, + [&](MPTIssue const& issue) { txt += to_string(issue); }); return txt; } @@ -478,7 +508,7 @@ OfferCreate::applyHybrid( sleOffer->setFlag(lsfHybrid); // if offer is hybrid, need to also place into open offer dir - Book const book{saTakerPays.issue(), saTakerGets.issue(), std::nullopt}; + Book const book{saTakerPays.asset(), saTakerGets.asset(), std::nullopt}; auto dir = keylet::quality(keylet::book(book), getRate(saTakerGets, saTakerPays)); bool const bookExists = sb.exists(dir); @@ -574,13 +604,15 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) auto const& uGetsIssuerID = saTakerGets.getIssuer(); std::uint8_t uTickSize = Quality::maxTickSize; - if (!isXRP(uPaysIssuerID)) + // Not XRP or MPT + if (!saTakerPays.integral()) { auto const sle = sb.read(keylet::account(uPaysIssuerID)); if (sle && sle->isFieldPresent(sfTickSize)) uTickSize = std::min(uTickSize, (*sle)[sfTickSize]); } - if (!isXRP(uGetsIssuerID)) + // Not XRP or MPT + if (!saTakerGets.integral()) { auto const sle = sb.read(keylet::account(uGetsIssuerID)); if (sle && sle->isFieldPresent(sfTickSize)) @@ -596,12 +628,13 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) if (bSell) { // this is a sell, round taker pays - saTakerPays = multiply(saTakerGets, rate, saTakerPays.issue()); + if (!saTakerPays.holds()) + saTakerPays = multiply(saTakerGets, rate, saTakerPays.asset()); } - else + else if (!saTakerGets.holds()) { // this is a buy, round taker gets - saTakerGets = divide(saTakerPays, rate, saTakerGets.issue()); + saTakerGets = divide(saTakerPays, rate, saTakerGets.asset()); } if (!saTakerGets || !saTakerPays) { @@ -615,8 +648,8 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // We reverse pays and gets because during crossing we are taking. Amounts const takerAmount(saTakerGets, saTakerPays); - JLOG(j_.debug()) << "Attempting cross: " << to_string(takerAmount.in.issue()) << " -> " - << to_string(takerAmount.out.issue()); + JLOG(j_.debug()) << "Attempting cross: " << to_string(takerAmount.in.asset()) << " -> " + << to_string(takerAmount.out.asset()); if (auto stream = j_.trace()) { @@ -660,10 +693,10 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) } XRPL_ASSERT( - saTakerGets.issue() == place_offer.in.issue(), + saTakerGets.asset() == place_offer.in.asset(), "xrpl::OfferCreate::applyGuts : taker gets issue match"); XRPL_ASSERT( - saTakerPays.issue() == place_offer.out.issue(), + saTakerPays.asset() == place_offer.out.asset(), "xrpl::OfferCreate::applyGuts : taker pays issue match"); if (takerAmount != place_offer) @@ -775,11 +808,11 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) // Update owner count. adjustOwnerCount(sb, sleCreator, 1, viewJ); - JLOG(j_.trace()) << "adding to book: " << to_string(saTakerPays.issue()) << " : " - << to_string(saTakerGets.issue()) + JLOG(j_.trace()) << "adding to book: " << to_string(saTakerPays.asset()) << " : " + << to_string(saTakerGets.asset()) << (domainID ? (" : " + to_string(*domainID)) : ""); - Book const book{saTakerPays.issue(), saTakerGets.issue(), domainID}; + Book const book{saTakerPays.asset(), saTakerGets.asset(), domainID}; // Add offer to order book, using the original rate // before any crossing occurred. @@ -796,10 +829,18 @@ OfferCreate::applyGuts(Sandbox& sb, Sandbox& sbCancel) bool const bookExisted = static_cast(sb.peek(dir)); auto setBookDir = [&](SLE::ref sle, std::optional const& maybeDomain) { - sle->setFieldH160(sfTakerPaysCurrency, saTakerPays.issue().currency); - sle->setFieldH160(sfTakerPaysIssuer, saTakerPays.issue().account); - sle->setFieldH160(sfTakerGetsCurrency, saTakerGets.issue().currency); - sle->setFieldH160(sfTakerGetsIssuer, saTakerGets.issue().account); + saTakerPays.asset().visit( + [&](Issue const& issue) { + sle->setFieldH160(sfTakerPaysCurrency, issue.currency); + sle->setFieldH160(sfTakerPaysIssuer, issue.account); + }, + [&](MPTIssue const& issue) { sle->setFieldH192(sfTakerPaysMPT, issue.getMptID()); }); + saTakerGets.asset().visit( + [&](Issue const& issue) { + sle->setFieldH160(sfTakerGetsCurrency, issue.currency); + sle->setFieldH160(sfTakerGetsIssuer, issue.account); + }, + [&](MPTIssue const& issue) { sle->setFieldH192(sfTakerGetsMPT, issue.getMptID()); }); sle->setFieldU64(sfExchangeRate, uRate); if (maybeDomain) sle->setFieldH256(sfDomainID, *maybeDomain); diff --git a/src/libxrpl/tx/transactors/escrow/Escrow.cpp b/src/libxrpl/tx/transactors/escrow/Escrow.cpp new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp index cd024a076d..faa862b424 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCancel.cpp @@ -32,13 +32,13 @@ escrowCancelPreclaimHelper( AccountID const& account, STAmount const& amount) { - AccountID const issuer = amount.getIssuer(); + AccountID const& issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecINTERNAL if (issuer == account) return tecINTERNAL; // LCOV_EXCL_LINE // If the issuer has requireAuth set, check if the account is authorized - if (auto const ter = requireAuth(ctx.view, amount.issue(), account); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, amount.get(), account); !isTesSuccess(ter)) return ter; return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp index a14b3abf37..789ca8ab1a 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowCreate.cpp @@ -72,7 +72,7 @@ escrowCreatePreflightHelper(PreflightContext const& ctx) if (amount.native() || amount <= beast::zero) return temBAD_AMOUNT; - if (badCurrency() == amount.getCurrency()) + if (badCurrency() == amount.get().currency) return temBAD_CURRENCY; return tesSUCCESS; @@ -163,7 +163,8 @@ escrowCreatePreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID const issuer = amount.getIssuer(); + Issue const& issue = amount.get(); + AccountID const& issuer = amount.getIssuer(); // If the issuer is the same as the account, return tecNO_PERMISSION if (issuer == account) return tecNO_PERMISSION; @@ -176,7 +177,7 @@ escrowCreatePreclaimHelper( return tecNO_PERMISSION; // If the account does not have a trustline to the issuer, return tecNO_LINE - auto const sleRippleState = ctx.view.read(keylet::line(account, issuer, amount.getCurrency())); + auto const sleRippleState = ctx.view.read(keylet::line(account, issuer, issue.currency)); if (!sleRippleState) return tecNO_LINE; @@ -191,23 +192,23 @@ escrowCreatePreclaimHelper( return tecNO_PERMISSION; // LCOV_EXCL_LINE // If the issuer has requireAuth set, check if the account is authorized - if (auto const ter = requireAuth(ctx.view, amount.issue(), account); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, issue, account); !isTesSuccess(ter)) return ter; // If the issuer has requireAuth set, check if the destination is authorized - if (auto const ter = requireAuth(ctx.view, amount.issue(), dest); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, issue, dest); !isTesSuccess(ter)) return ter; // If the issuer has frozen the account, return tecFROZEN - if (isFrozen(ctx.view, account, amount.issue())) + if (isFrozen(ctx.view, account, issue)) return tecFROZEN; // If the issuer has frozen the destination, return tecFROZEN - if (isFrozen(ctx.view, dest, amount.issue())) + if (isFrozen(ctx.view, dest, issue)) return tecFROZEN; STAmount const spendableAmount = - accountHolds(ctx.view, account, amount.getCurrency(), issuer, fhIGNORE_FREEZE, ctx.j); + accountHolds(ctx.view, account, issue.currency, issuer, fhIGNORE_FREEZE, ctx.j); // If the balance is less than or equal to 0, return tecINSUFFICIENT_FUNDS if (spendableAmount <= beast::zero) diff --git a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp index 5c28fa5dd3..8714bab5ff 100644 --- a/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp +++ b/src/libxrpl/tx/transactors/escrow/EscrowFinish.cpp @@ -126,17 +126,17 @@ escrowFinishPreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID const issuer = amount.getIssuer(); + AccountID const& issuer = amount.getIssuer(); // If the issuer is the same as the account, return tesSUCCESS if (issuer == dest) return tesSUCCESS; // If the issuer has requireAuth set, check if the destination is authorized - if (auto const ter = requireAuth(ctx.view, amount.issue(), dest); !isTesSuccess(ter)) + if (auto const ter = requireAuth(ctx.view, amount.get(), dest); !isTesSuccess(ter)) return ter; // If the issuer has deep frozen the destination, return tecFROZEN - if (isDeepFrozen(ctx.view, dest, amount.getCurrency(), amount.getIssuer())) + if (isDeepFrozen(ctx.view, dest, amount.get().currency, amount.getIssuer())) return tecFROZEN; return tesSUCCESS; @@ -149,7 +149,7 @@ escrowFinishPreclaimHelper( AccountID const& dest, STAmount const& amount) { - AccountID const issuer = amount.getIssuer(); + AccountID const& issuer = amount.getIssuer(); // If the issuer is the same as the dest, return tesSUCCESS if (issuer == dest) return tesSUCCESS; diff --git a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp index 627b16794b..c7493a71cd 100644 --- a/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp +++ b/src/libxrpl/tx/transactors/lending/LoanBrokerCoverClawback.cpp @@ -123,7 +123,7 @@ determineAsset( { // We want the asset to match the vault asset, so use the account as the // issuer - return Issue{amount.getCurrency(), account}; + return Issue{amount.get().currency, account}; } return Unexpected(tecWRONG_ASSET); diff --git a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp index fda79c93b6..95955bd0bd 100644 --- a/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp +++ b/src/libxrpl/tx/transactors/nft/NFTokenAcceptOffer.cpp @@ -83,7 +83,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) return tecNFTOKEN_BUY_SELL_MISMATCH; // The two offers being brokered must be for the same asset: - if ((*bo)[sfAmount].issue() != (*so)[sfAmount].issue()) + if ((*bo)[sfAmount].asset() != (*so)[sfAmount].asset()) return tecNFTOKEN_BUY_SELL_MISMATCH; // The two offers may not form a loop. A broker may not sell the @@ -116,7 +116,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) // cut, if any). if (auto const brokerFee = ctx.tx[~sfNFTokenBrokerFee]) { - if (brokerFee->issue() != (*bo)[sfAmount].issue()) + if (brokerFee->asset() != (*bo)[sfAmount].asset()) return tecNFTOKEN_BUY_SELL_MISMATCH; if (brokerFee >= (*bo)[sfAmount]) @@ -289,7 +289,7 @@ NFTokenAcceptOffer::preclaim(PreclaimContext const& ctx) if (ctx.view.rules().enabled(fixEnforceNFTokenTrustline) && (nft::getFlags(tokenID) & nft::flagCreateTrustLines) == 0 && nftMinter != amount.getIssuer() && - !ctx.view.read(keylet::line(nftMinter, amount.issue()))) + !ctx.view.read(keylet::line(nftMinter, amount.get()))) return tecNO_LINE; // Check that the issuer is allowed to receive IOUs. diff --git a/src/libxrpl/tx/transactors/payment/Payment.cpp b/src/libxrpl/tx/transactors/payment/Payment.cpp index e3ceddeae3..8b80491278 100644 --- a/src/libxrpl/tx/transactors/payment/Payment.cpp +++ b/src/libxrpl/tx/transactors/payment/Payment.cpp @@ -39,16 +39,17 @@ getMaxSourceAmount( { return *sendMax; } - if (dstAmount.native() || dstAmount.holds()) - { - return dstAmount; - } - - return STAmount( - Issue{dstAmount.get().currency, account}, - dstAmount.mantissa(), - dstAmount.exponent(), - dstAmount < beast::zero); + return dstAmount.asset().visit( + [&](MPTIssue const& issue) { return dstAmount; }, + [&](Issue const& issue) { + if (issue.native()) + return dstAmount; + return STAmount( + Issue{issue.currency, account}, + dstAmount.mantissa(), + dstAmount.exponent(), + dstAmount < beast::zero); + }); } bool @@ -68,9 +69,14 @@ Payment::getFlagsMask(PreflightContext const& ctx) auto& tx = ctx.tx; STAmount const dstAmount(tx.getFieldAmount(sfAmount)); - bool const mptDirect = dstAmount.holds(); + bool const isDstMPT = dstAmount.holds(); + bool const MPTokensV2 = ctx.rules.enabled(featureMPTokensV2); - return mptDirect ? tfMPTPaymentMask : tfPaymentMask; + constexpr std::uint32_t tfMPTPaymentMaskV1 = ~(tfUniversal | tfPartialPayment); + std::uint32_t const paymentMask = + (isDstMPT && !MPTokensV2) ? tfMPTPaymentMaskV1 : tfPaymentMask; + + return paymentMask; } NotTEC @@ -80,14 +86,15 @@ Payment::preflight(PreflightContext const& ctx) auto& j = ctx.j; STAmount const dstAmount(tx.getFieldAmount(sfAmount)); - bool const mptDirect = dstAmount.holds(); + bool const isDstMPT = dstAmount.holds(); + bool const MPTokensV2 = ctx.rules.enabled(featureMPTokensV2); - if (mptDirect && !ctx.rules.enabled(featureMPTokensV1)) + if (!ctx.rules.enabled(featureMPTokensV1) && isDstMPT) return temDISABLED; std::uint32_t const txFlags = tx.getFlags(); - if (mptDirect && ctx.tx.isFieldPresent(sfPaths)) + if (!MPTokensV2 && isDstMPT && ctx.tx.isFieldPresent(sfPaths)) return temMALFORMED; bool const partialPaymentAllowed = (txFlags & tfPartialPayment) != 0u; @@ -101,8 +108,9 @@ Payment::preflight(PreflightContext const& ctx) auto const account = tx.getAccountID(sfAccount); STAmount const maxSourceAmount = getMaxSourceAmount(account, dstAmount, tx[~sfSendMax]); - if ((mptDirect && dstAmount.asset() != maxSourceAmount.asset()) || - (!mptDirect && maxSourceAmount.holds())) + if (!MPTokensV2 && + ((isDstMPT && dstAmount.asset() != maxSourceAmount.asset()) || + (!isDstMPT && maxSourceAmount.holds()))) { JLOG(j.trace()) << "Malformed transaction: inconsistent issues: " << dstAmount.getFullText() << " " << maxSourceAmount.getFullText() << " " @@ -137,7 +145,12 @@ Payment::preflight(PreflightContext const& ctx) JLOG(j.trace()) << "Malformed transaction: bad dst amount: " << dstAmount.getFullText(); return temBAD_AMOUNT; } - if (badCurrency() == srcAsset || badCurrency() == dstAsset) + auto bad = [&](auto const& asset) { + if (ctx.rules.enabled(featureMPTokensV2)) + return badAsset() == asset; + return badCurrency() == asset; + }; + if (bad(srcAsset) || bad(dstAsset)) { JLOG(j.trace()) << "Malformed transaction: Bad currency."; return temBAD_CURRENCY; @@ -158,7 +171,7 @@ Payment::preflight(PreflightContext const& ctx) << "SendMax specified for XRP to XRP."; return temBAD_SEND_XRP_MAX; } - if ((xrpDirect || mptDirect) && hasPaths) + if ((xrpDirect || (!MPTokensV2 && isDstMPT)) && hasPaths) { // XRP is sent without paths. JLOG(j.trace()) << "Malformed transaction: " @@ -172,14 +185,14 @@ Payment::preflight(PreflightContext const& ctx) << "Partial payment specified for XRP to XRP."; return temBAD_SEND_XRP_PARTIAL; } - if ((xrpDirect || mptDirect) && limitQuality) + if ((xrpDirect || (!MPTokensV2 && isDstMPT)) && limitQuality) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " << "Limit quality specified for XRP to XRP or MPT to MPT."; return temBAD_SEND_XRP_LIMIT; } - if ((xrpDirect || mptDirect) && !defaultPathsAllowed) + if ((xrpDirect || (!MPTokensV2 && isDstMPT)) && !defaultPathsAllowed) { // Consistent but redundant transaction. JLOG(j.trace()) << "Malformed transaction: " @@ -372,7 +385,7 @@ Payment::doApply() AccountID const dstAccountID(ctx_.tx.getAccountID(sfDestination)); STAmount const dstAmount(ctx_.tx.getFieldAmount(sfAmount)); - bool const mptDirect = dstAmount.holds(); + bool const isDstMPT = dstAmount.holds(); STAmount const maxSourceAmount = getMaxSourceAmount(account_, dstAmount, sendMax); JLOG(j_.trace()) << "maxSourceAmount=" << maxSourceAmount.getFullText() @@ -399,7 +412,10 @@ Payment::doApply() view().update(sleDst); } - bool const ripple = (hasPaths || sendMax || !dstAmount.native()) && !mptDirect; + bool const MPTokensV2 = view().rules().enabled(featureMPTokensV2); + + // Direct MPT payment is handled by payment engine if MPTokensV2 is enabled + bool const ripple = (hasPaths || sendMax || !dstAmount.native()) && (!isDstMPT || MPTokensV2); if (ripple) { @@ -466,7 +482,7 @@ Payment::doApply() terResult = tecPATH_DRY; return terResult; } - if (mptDirect) + if (isDstMPT) { JLOG(j_.trace()) << " dstAmount=" << dstAmount.getFullText(); auto const& mptIssue = dstAmount.get(); diff --git a/src/libxrpl/tx/transactors/token/Clawback.cpp b/src/libxrpl/tx/transactors/token/Clawback.cpp index d7304e5cf1..18c631b5f2 100644 --- a/src/libxrpl/tx/transactors/token/Clawback.cpp +++ b/src/libxrpl/tx/transactors/token/Clawback.cpp @@ -95,7 +95,7 @@ preclaimHelper( return tecNO_PERMISSION; auto const sleRippleState = - ctx.view.read(keylet::line(holder, issuer, clawAmount.getCurrency())); + ctx.view.read(keylet::line(holder, issuer, clawAmount.get().currency)); if (!sleRippleState) return tecNO_LINE; @@ -118,7 +118,8 @@ preclaimHelper( // We can't directly check the balance of trustline because // the available balance of a trustline is prone to new changes (eg. // XLS-34). So we must use `accountHolds`. - if (accountHolds(ctx.view, holder, clawAmount.getCurrency(), issuer, fhIGNORE_FREEZE, ctx.j) <= + if (accountHolds( + ctx.view, holder, clawAmount.get().currency, issuer, fhIGNORE_FREEZE, ctx.j) <= beast::zero) return tecINSUFFICIENT_FUNDS; @@ -199,7 +200,7 @@ applyHelper(ApplyContext& ctx) AccountID const holder = clawAmount.getIssuer(); // cannot be reference // Replace the `issuer` field with issuer's account - clawAmount.setIssuer(issuer); + clawAmount.get().account = issuer; if (holder == issuer) return tecINTERNAL; // LCOV_EXCL_LINE @@ -207,7 +208,7 @@ applyHelper(ApplyContext& ctx) STAmount const spendableAmount = accountHolds( ctx.view(), holder, - clawAmount.getCurrency(), + clawAmount.get().currency, clawAmount.getIssuer(), fhIGNORE_FREEZE, ctx.journal); diff --git a/src/libxrpl/tx/transactors/token/TrustSet.cpp b/src/libxrpl/tx/transactors/token/TrustSet.cpp index 801645d1c0..13c444af8b 100644 --- a/src/libxrpl/tx/transactors/token/TrustSet.cpp +++ b/src/libxrpl/tx/transactors/token/TrustSet.cpp @@ -82,7 +82,7 @@ TrustSet::preflight(PreflightContext const& ctx) return temBAD_LIMIT; } - if (badCurrency() == saLimitAmount.getCurrency()) + if (badCurrency() == saLimitAmount.get().currency) { JLOG(j.trace()) << "Malformed transaction: specifies XRP as IOU"; return temBAD_CURRENCY; @@ -135,7 +135,8 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) auto const saLimitAmount = tx.getFieldAmount(sfLimitAmount); auto const sleRippleState = view.read( - keylet::line(tx[sfAccount], saLimitAmount.getIssuer(), saLimitAmount.getCurrency())); + keylet::line( + tx[sfAccount], saLimitAmount.getIssuer(), saLimitAmount.get().currency)); // if the trustline does not exist, granular permissions are // not allowed to create trustline @@ -159,7 +160,7 @@ TrustSet::checkPermission(ReadView const& view, STTx const& tx) : sleRippleState->getFieldAmount(sfLowLimit); STAmount saLimitAllow = saLimitAmount; - saLimitAllow.setIssuer(tx[sfAccount]); + saLimitAllow.get().account = tx[sfAccount]; if (curLimit != saLimitAllow) return terNO_DELEGATE_PERMISSION; @@ -188,7 +189,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) auto const saLimitAmount = ctx.tx[sfLimitAmount]; - auto const currency = saLimitAmount.getCurrency(); + auto const currency = saLimitAmount.get().currency; auto const uDstAccountID = saLimitAmount.getIssuer(); if (id == uDstAccountID) @@ -241,7 +242,7 @@ TrustSet::preclaim(PreclaimContext const& ctx) { return tecAMM_EMPTY; } - if (lpTokens.getCurrency() != saLimitAmount.getCurrency()) + if (lpTokens.get().currency != saLimitAmount.get().currency) { return tecNO_PERMISSION; } @@ -317,7 +318,7 @@ TrustSet::doApply() bool const bQualityIn(ctx_.tx.isFieldPresent(sfQualityIn)); bool const bQualityOut(ctx_.tx.isFieldPresent(sfQualityOut)); - Currency const currency(saLimitAmount.getCurrency()); + Currency const currency(saLimitAmount.get().currency); AccountID const uDstAccountID(saLimitAmount.getIssuer()); // true, if current is high account. @@ -377,7 +378,7 @@ TrustSet::doApply() } STAmount saLimitAllow = saLimitAmount; - saLimitAllow.setIssuer(account_); + saLimitAllow.get().account = account_; SLE::pointer const sleRippleState = view().peek(keylet::line(account_, uDstAccountID, currency)); diff --git a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp index 9904c4183d..095b44e072 100644 --- a/src/libxrpl/tx/transactors/vault/VaultClawback.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultClawback.cpp @@ -163,44 +163,43 @@ VaultClawback::preclaim(PreclaimContext const& ctx) return tecNO_PERMISSION; } - return std::visit( - [&](TIss const& issue) -> TER { - if constexpr (std::is_same_v) - { - auto const mptIssue = ctx.view.read(keylet::mptIssuance(issue.getMptID())); - if (mptIssue == nullptr) - return tecOBJECT_NOT_FOUND; + return vaultAsset.visit( + [&](MPTIssue const& issue) -> TER { + auto const mptIssue = ctx.view.read(keylet::mptIssuance(issue.getMptID())); + if (mptIssue == nullptr) + return tecOBJECT_NOT_FOUND; - std::uint32_t const issueFlags = mptIssue->getFieldU32(sfFlags); - if (!(issueFlags & lsfMPTCanClawback)) - { - JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " - "MPT vault asset."; - return tecNO_PERMISSION; - } - } - else if constexpr (std::is_same_v) + std::uint32_t const issueFlags = mptIssue->getFieldU32(sfFlags); + if ((issueFlags & lsfMPTCanClawback) == 0u) { - auto const issuerSle = ctx.view.read(keylet::account(account)); - if (!issuerSle) - { - // LCOV_EXCL_START - JLOG(ctx.j.error()) << "VaultClawback: missing submitter account."; - return tefINTERNAL; - // LCOV_EXCL_STOP - } - - std::uint32_t const issuerFlags = issuerSle->getFieldU32(sfFlags); - if (!(issuerFlags & lsfAllowTrustLineClawback) || (issuerFlags & lsfNoFreeze)) - { - JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " - "IOU vault asset."; - return tecNO_PERMISSION; - } + JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " + "MPT vault asset."; + return tecNO_PERMISSION; } + return tesSUCCESS; }, - vaultAsset.value()); + [&](Issue const&) -> TER { + auto const issuerSle = ctx.view.read(keylet::account(account)); + if (!issuerSle) + { + // LCOV_EXCL_START + JLOG(ctx.j.error()) << "VaultClawback: missing submitter account."; + return tefINTERNAL; + // LCOV_EXCL_STOP + } + + std::uint32_t const issuerFlags = issuerSle->getFieldU32(sfFlags); + if (((issuerFlags & lsfAllowTrustLineClawback) == 0u) || + ((issuerFlags & lsfNoFreeze) != 0u)) + { + JLOG(ctx.j.debug()) << "VaultClawback: cannot clawback " + "IOU vault asset."; + return tecNO_PERMISSION; + } + + return tesSUCCESS; + }); } // Invalid asset diff --git a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp index f6b8c98788..b3d2864380 100644 --- a/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp +++ b/src/libxrpl/tx/transactors/vault/VaultWithdraw.cpp @@ -128,7 +128,7 @@ VaultWithdraw::preclaim(PreclaimContext const& ctx) // Cannot return shares to the vault, if the underlying asset was frozen for // the submitter - if (auto const ret = checkFrozen(ctx.view, account, vaultShare)) + if (auto const ret = checkFrozen(ctx.view, account, Asset{vaultShare})) return ret; return tesSUCCESS; diff --git a/src/test/app/AMMCalc_test.cpp b/src/test/app/AMMCalc_test.cpp index 021cf4bf46..029a3121fe 100644 --- a/src/test/app/AMMCalc_test.cpp +++ b/src/test/app/AMMCalc_test.cpp @@ -3,6 +3,7 @@ #include #include +#include #include namespace xrpl { @@ -164,9 +165,7 @@ class AMMCalc_test : public beast::unit_test::suite static std::string toString(STAmount const& a) { - std::stringstream str; - str << a.getText() << "/" << to_string(a.issue().currency); - return str.str(); + return (boost::format("%s/%s") % a.getText() % to_string(a.get().currency)).str(); } static STAmount @@ -175,8 +174,8 @@ class AMMCalc_test : public beast::unit_test::suite if (a == b) return amt; if (amt.native()) - return toSTAmount(mulRatio(amt.xrp(), a, b, round), amt.issue()); - return toSTAmount(mulRatio(amt.iou(), a, b, round), amt.issue()); + return toSTAmount(mulRatio(amt.xrp(), a, b, round), amt.asset()); + return toSTAmount(mulRatio(amt.iou(), a, b, round), amt.asset()); } static void @@ -191,9 +190,9 @@ class AMMCalc_test : public beast::unit_test::suite STAmount sin{}; int limitingStep = vp.size(); STAmount limitStepOut{}; - auto transferRate = [&](auto const& amt) { - auto const currency = to_string(amt.issue().currency); - return rates.find(currency) != rates.end() ? rates.at(currency) : QUALITY_ONE; + auto transferRate = [&](STAmount const& amt) { + auto const currency = to_string(amt.get().currency); + return rates.contains(currency) ? rates.at(currency) : QUALITY_ONE; }; // swap out reverse sin = sout; @@ -254,9 +253,9 @@ class AMMCalc_test : public beast::unit_test::suite STAmount sout{}; int limitingStep = 0; STAmount limitStepIn{}; - auto transferRate = [&](auto const& amt) { - auto const currency = to_string(amt.issue().currency); - return rates.find(currency) != rates.end() ? rates.at(currency) : QUALITY_ONE; + auto transferRate = [&](STAmount const& amt) { + auto const currency = to_string(amt.get().currency); + return rates.contains(currency) ? rates.at(currency) : QUALITY_ONE; }; // Swap in forward for (auto it = vp.begin(); it != vp.end(); ++it) diff --git a/src/test/app/AMMClawbackMPT_test.cpp b/src/test/app/AMMClawbackMPT_test.cpp new file mode 100644 index 0000000000..2708218df9 --- /dev/null +++ b/src/test/app/AMMClawbackMPT_test.cpp @@ -0,0 +1,1821 @@ +#include +#include +#include + +#include +#include + +namespace xrpl { +namespace test { +class AMMClawbackMPT_test : public beast::unit_test::suite +{ + void + testInvalidRequest(FeatureBitset features) + { + testcase("test invalid request"); + using namespace jtx; + + for (auto const& feature : {features, features - featureSingleAssetVault}) + { + Env env(*this, feature); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + auto const USD = gw["USD"]; + env.trust(USD(10000), alice); + env(pay(gw, alice, USD(100))); + env.close(); + + AMM amm(env, gw, BTC(100), USD(100)); + + // holder does not exist + env(amm::ammClawback(gw, Account("unknown"), USD, BTC, std::nullopt), + ter(terNO_ACCOUNT)); + + // can not clawback from self. + env(amm::ammClawback(gw, gw, USD, BTC, std::nullopt), ter(temMALFORMED)); + + // provided Asset does not match issuer gw + { + env(amm::ammClawback( + gw, alice, Issue{gw["USD"].currency, alice.id()}, BTC, std::nullopt), + ter(temMALFORMED)); + env(amm::ammClawback(gw, alice, MPTIssue{makeMptID(1, alice)}, USD, std::nullopt), + ter(temMALFORMED)); + } + + // Amount does not match asset + { + env(amm::ammClawback( + gw, alice, USD, BTC, STAmount{Issue{gw["USD"].currency, alice.id()}, 1}), + ter(temBAD_AMOUNT)); + env(amm::ammClawback( + gw, alice, BTC, USD, STAmount{MPTIssue{makeMptID(1, alice)}, 10}), + ter(temBAD_AMOUNT)); + } + + // Amount is not greater than 0 + { + env(amm::ammClawback(gw, alice, BTC, USD, BTC(-1)), ter(temBAD_AMOUNT)); + env(amm::ammClawback(gw, alice, BTC, USD, BTC(0)), ter(temBAD_AMOUNT)); + } + + // clawback from account not holding lptoken + env(amm::ammClawback(gw, bob, BTC, USD, BTC(1000)), ter(tecAMM_BALANCE)); + + // can not perform regular claw from amm pool + { + Issue const usd(USD.currency, amm.ammAccount()); + auto amount = amountFromString(usd, "10"); + auto const err = + feature[featureSingleAssetVault] ? tecPSEUDO_ACCOUNT : tecAMM_ACCOUNT; + env(claw(gw, amount), ter(err)); + } + + // AMM does not exist + { + // withdraw all tokens will delete the AMM + amm.withdrawAll(gw); + BEAST_EXPECT(!amm.ammExists()); + env.close(); + env(amm::ammClawback(gw, alice, USD, BTC, std::nullopt), ter(terNO_AMM)); + } + } + + // tfMPTCanClawback is not enabled + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 40'000}); + + auto const USD = gw["USD"]; + env.trust(USD(10000), alice); + env(pay(gw, alice, USD(10000))); + env.close(); + + AMM amm(env, gw, BTC(100), USD(100)); + env.close(); + amm.deposit(alice, 1'000); + env.close(); + + // can not clawback when tfMPTCanClawback is not enabled + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), ter(tecNO_PERMISSION)); + } + + // can not claw with tfClawTwoAssets if the assets are not issued by the + // same issuer + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, gw2, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(10000), alice); + env(pay(gw, alice, USD(10000))); + env.close(); + + // todo: check tfMPTCanTransfer in xrpl.org + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM const amm(env, alice, BTC(100), USD(100)); + env.close(); + + { + // Return temINVALID_FLAG because the issuer set + // tfClawTwoAssets, but the issuer only issues USD in the pool. + // The issuer is not allowed to set tfClawTwoAssets flag if he + // did not issue both assets in the pool. + env(amm::ammClawback(gw, alice, USD, BTC, std::nullopt), + txflags(tfClawTwoAssets), + ter(temINVALID_FLAG)); + } + } + + // Test if the issuer did not set asfAllowTrustLineClawback, but the MPT + // is set tfMPTCanClawback, the issuer can claw MPT. + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(10000), gw, alice); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM const amm(env, alice, BTC(100), XRP(100)); + env.close(); + + // If asfAllowTrustLineClawback is not set, the issuer can + // still claw MPT because the MPT's tfMPTCanClawback is set. + env(amm::ammClawback(gw, alice, BTC, XRP, std::nullopt)); + } + } + + void + testFeatureDisabled(FeatureBitset features) + { + testcase("test feature disabled."); + using namespace jtx; + Env env{*this, features}; + Account const gw("gateway"), alice("alice"); + env.fund(XRP(30'000), gw, alice); + env.close(); + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 10'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM const amm(env, alice, XRP(1'000), BTC(1'000)); + + // disable featureAMMClawback + env.disableFeature(featureAMMClawback); + env(amm::ammClawback(gw, alice, BTC, XRP, std::nullopt), ter(temDISABLED)); + + // enable featureAMMClawback and disable featureMPTokensV2 + env.enableFeature(featureAMMClawback); + env.disableFeature(featureMPTokensV2); + env(amm::ammClawback(gw, alice, BTC, XRP, BTC(100)), ter(temDISABLED)); + + // enable featureMPTokensV2 + env.enableFeature(featureMPTokensV2); + env(amm::ammClawback(gw, alice, BTC, XRP, BTC(200))); + } + + void + testAMMClawbackAmount(FeatureBitset features) + { + testcase("test AMMClawback specific amount"); + using namespace jtx; + + // AMMClawback from MPT/IOU issued by different issuers + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, gw2, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM const amm(env, alice, BTC(1000000000), USD(2000)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'000000), USD(2000), IOUAmount{1414'213'562373095, -9})); + + // can not set tfClawTwoAssets because the assets are not issued by + // the same issuer. + env(amm::ammClawback(gw2, alice, BTC, USD, BTC(1000)), + txflags(tfClawTwoAssets), + ter(temINVALID_FLAG)); + + auto aliceUSD = env.balance(alice, USD); + auto aliceBTC = env.balance(alice, BTC); + // gw clawback 1000 USD from alice + env(amm::ammClawback(gw, alice, USD, BTC, USD(1000))); + env.close(); + + BEAST_EXPECT( + amm.expectBalances(BTC(500'000000), USD(1000), IOUAmount{707'106'7811865475, -10})); + // USD is clawed back, + env.require(balance(alice, aliceUSD)); + // a proportional amount of BTC is returned to alice + env.require(balance(alice, aliceBTC + BTC(500'000000))); + aliceBTC = env.balance(alice, BTC); + + // gw2 clawback 250'000000 BTC from alice + env(amm::ammClawback(gw2, alice, BTC, USD, BTC(250'000000))); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(250'000000), USD(500), IOUAmount{353'553'3905932737, -10})); + env.require(balance(alice, aliceUSD + USD(500))); + env.require(balance(alice, aliceBTC)); + aliceUSD = env.balance(alice, USD); + + // gw2 clawback 500'000000 BTC which exceeds the balance, + // this will clawback all and the amm will be deleted. + env(amm::ammClawback(gw2, alice, BTC, USD, BTC(500'000000))); + env.close(); + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceUSD + USD(500))); + env.require(balance(alice, aliceBTC)); + } + + // AMMClawback from MPT/XRP pool + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(1000000000), XRP(2000)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'000000), XRP(2000), IOUAmount{1'414'213'562'373095, -6})); + + amm.deposit(bob, BTC(2'000'000000), XRP(4000)); + BEAST_EXPECT(amm.expectBalances( + BTC(3'000'000000), XRP(6000), IOUAmount{4'242'640'687'119285, -6})); + + auto aliceXRP = env.balance(alice, XRP); + auto aliceBTC = env.balance(alice, BTC); + auto bobXRP = env.balance(bob, XRP); + auto bobBTC = env.balance(bob, BTC); + + // can not claw XRP + env(amm::ammClawback(gw, alice, XRP, BTC, XRP(1000)), ter(temMALFORMED)); + // can not set tfClawTwoAssets + env(amm::ammClawback(gw, alice, BTC, XRP, BTC(1000)), + txflags(tfClawTwoAssets), + ter(temINVALID_FLAG)); + + // gw clawback 500 BTC from alice + env(amm::ammClawback(gw, alice, BTC, XRP, BTC(500))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(2'999'999501), + STAmount{XRP, UINT64_C(5'999'999001)}, + IOUAmount{4'242'639'980'012504, -6})); + env.require(balance(alice, aliceXRP + drops(999))); + env.require(balance(alice, aliceBTC)); + env.require(balance(bob, bobXRP)); + env.require(balance(bob, bobBTC)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'414'212'855'266314, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2'828'427'124'74619, -5})); + aliceXRP = env.balance(alice, XRP); + + // gw clawback 1000'000000 BTC from bob + env(amm::ammClawback(gw, bob, BTC, XRP, BTC(1'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'999'999501), + STAmount{XRP, UINT64_C(3'999'999002)}, + IOUAmount{2828426418'110813, -6})); + env.require(balance(alice, aliceXRP)); + env.require(balance(alice, aliceBTC)); + env.require(balance(bob, bobXRP + XRPAmount(1999999999))); + env.require(balance(bob, bobBTC)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'414'212'855'266314, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1'414'213'562'844499, -6})); + bobXRP = env.balance(bob, XRP); + + // gw clawback 1000'000000 BTC from alice, which exceeds her balance + // will clawback all her balance + env(amm::ammClawback(gw, alice, BTC, XRP, BTC(1'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'000001), XRPAmount(2'000'000002), IOUAmount{1'414'213'562'844499, -6})); + env.require(balance(alice, aliceXRP + STAmount{XRP, UINT64_C(1'999'999000)})); + env.require(balance(alice, aliceBTC)); + env.require(balance(bob, bobXRP)); + env.require(balance(bob, bobBTC)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{1'414'213'562'844499, -6})); + aliceXRP = env.balance(alice, XRP); + + // gw clawback from bob, which exceeds his balance + env(amm::ammClawback(gw, bob, BTC, XRP, BTC(2'000'000000))); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceXRP)); + env.require(balance(alice, aliceBTC)); + env.require(balance(bob, bobXRP + XRPAmount(2000000002))); + env.require(balance(bob, bobBTC)); + } + + // AMMClawback from MPT/MPT pool, different issuers + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, gw2, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice, bob}, + .pay = 30'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(2'000'000000), ETH(3'000'000000)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(2'000'000000), ETH(3'000'000000), IOUAmount{2'449'489'742'783178, -6})); + + amm.deposit(bob, BTC(4'000'000000), ETH(6'000'000000)); + BEAST_EXPECT(amm.expectBalances( + BTC(6'000'000000), ETH(9'000'000000), IOUAmount{7'348'469'228'349534, -6})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceETH = env.balance(alice, ETH); + auto bobBTC = env.balance(bob, BTC); + auto bobETH = env.balance(bob, ETH); + + // gw clawback BTC from alice + env(amm::ammClawback(gw, alice, BTC, ETH, BTC(1'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(5'000'000000), ETH(7'500'000000), IOUAmount{6'123'724'356'957944, -6})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH + ETH(1'500'000000))); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'224'744'871'391588, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{4'898'979'485'566356, -6})); + aliceETH = env.balance(alice, ETH); + + // gw2 clawback ETH from bob + env(amm::ammClawback(gw2, bob, ETH, BTC, ETH(3'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(3'000'000000), ETH(4'500'000000), IOUAmount{3'674'234'614'174766, -6})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC + BTC(2'000'000000))); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'224'744'871'391588, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2'449'489'742'783178, -6})); + bobBTC = env.balance(bob, BTC); + + // gw2 clawback ETH from alice, which exceeds her balance + env(amm::ammClawback(gw2, alice, ETH, BTC, ETH(4'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(2'000'000001), ETH(3'000'000001), IOUAmount{2'449'489'742'783178, -6})); + env.require(balance(alice, aliceBTC + BTC(999'999999))); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + aliceBTC = env.balance(alice, BTC); + + // gw clawback BTC from bob, which exceeds his balance + env(amm::ammClawback(gw, bob, BTC, ETH, BTC(3'000'000000))); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH + ETH(3'000'000001))); + } + } + + void + testAMMClawbackAll(FeatureBitset features) + { + testcase("test AMMClawback all"); + using namespace jtx; + + // AMMClawback all from MPT/IOU issued by different issuers + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, gw2, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(200000), bob); + env(pay(gw, bob, USD(60000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(2000000000), USD(2000)); + env.close(); + BEAST_EXPECT(amm.expectBalances(BTC(2'000'000000), USD(2000), IOUAmount(2000000))); + + // gw clawback all BTC from alice + amm.deposit(bob, BTC(1'000'000000), USD(2000)); + env.close(); + BEAST_EXPECT(amm.expectBalances(BTC(3'000'000000), USD(3000), IOUAmount(3000000))); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + auto bobBTC = env.balance(bob, BTC); + auto bobUSD = env.balance(bob, USD); + + // gw2 clawback all BTC from alice + env(amm::ammClawback(gw2, alice, BTC, USD, std::nullopt)); + env.close(); + BEAST_EXPECT(amm.expectBalances(BTC(1'000'000000), USD(1000), IOUAmount(1000000))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(2000))); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobUSD)); + aliceUSD = env.balance(alice, USD); + + // gw clawback all USD from bob + env(amm::ammClawback(gw, bob, USD, BTC, std::nullopt)); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + env.require(balance(bob, bobBTC + BTC(1'000'000000))); + env.require(balance(bob, bobUSD)); + } + + // AMMClawback all from MPT/XRP pool + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(5000), XRP(10'000)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(5'000), XRP(10'000), IOUAmount{7'071'067'811865475, -9})); + + amm.deposit(bob, BTC(10'000), XRP(20'000)); + BEAST_EXPECT( + amm.expectBalances(BTC(15'000), XRP(30'000), IOUAmount{21'213'203'43559642, -8})); + + auto aliceXRP = env.balance(alice, XRP); + auto aliceBTC = env.balance(alice, BTC); + auto bobXRP = env.balance(bob, XRP); + auto bobBTC = env.balance(bob, BTC); + + // gw clawback all BTC from alice + env(amm::ammClawback(gw, alice, BTC, XRP, std::nullopt)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(10'000), XRP(20'000), IOUAmount{14'142'135'62373094, -8})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceXRP + XRP(10'000))); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobXRP)); + aliceXRP = env.balance(alice, XRP); + + // gw clawback all BTC from bob + env(amm::ammClawback(gw, bob, BTC, XRP, std::nullopt)); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceXRP)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobXRP + XRP(20'000))); + } + + // AMMClawback all from MPT/MPT pool, different issuers + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, gw2, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice, bob}, + .pay = 30'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(20'000), ETH(50'000)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(20'000), ETH(50'000), IOUAmount{31'622'77660168379, -11})); + + amm.deposit(bob, BTC(40'000), ETH(100'000)); + BEAST_EXPECT( + amm.expectBalances(BTC(60'000), ETH(150'000), IOUAmount{94'868'32980505137, -11})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceETH = env.balance(alice, ETH); + auto bobBTC = env.balance(bob, BTC); + auto bobETH = env.balance(bob, ETH); + + // gw clawback all BTC from bob + env(amm::ammClawback(gw, bob, BTC, ETH, std::nullopt)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(20'000), ETH(50'000), IOUAmount{31'622'77660168379, -11})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH + ETH(100'000))); + bobETH = env.balance(bob, ETH); + + // gw2 clawback all ETH from alice + env(amm::ammClawback(gw2, alice, ETH, BTC, std::nullopt)); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC + BTC(20'000))); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + } + } + + void + testAMMClawbackAmountSameIssuer(FeatureBitset features) + { + testcase("test AMMClawback specific amount, assets have the same issuer"); + using namespace jtx; + + // AMMClawback from MPT/IOU issued by the same issuer + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(100000), bob); + env(pay(gw, bob, USD(40000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(1'000'000000), USD(2000)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'000000), USD(2000), IOUAmount{1414'213'562373095, -9})); + + amm.deposit(bob, BTC(500'000000), USD(1000)); + BEAST_EXPECT(amm.expectBalances( + BTC(1'500'000000), + STAmount{USD, UINT64_C(2'999'999999999999), -12}, + IOUAmount{2'121'320'343559642, -9})); + + auto aliceUSD = env.balance(alice, USD); + auto aliceBTC = env.balance(alice, BTC); + auto bobUSD = env.balance(bob, USD); + auto bobBTC = env.balance(bob, BTC); + + // gw clawback 500 USD from alice. + env(amm::ammClawback(gw, alice, USD, BTC, USD(500))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1250'000001), USD(2500), IOUAmount{1'767'766'952966369, -9})); + env.require(balance(alice, aliceUSD)); + env.require(balance(alice, aliceBTC + BTC(249'999999))); + env.require(balance(bob, bobUSD)); + env.require(balance(bob, bobBTC)); + aliceBTC = env.balance(alice, BTC); + // gw clawback 250'000000 BTC and 500 USD from bob + // with tfClawTwoAssets + env(amm::ammClawback(gw, bob, BTC, USD, BTC(250'000000)), txflags(tfClawTwoAssets)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'000002), + STAmount{USD, UINT64_C(2000'0000004), -7}, + IOUAmount{1'414'213'562655938, -9})); + env.require(balance(alice, aliceUSD)); + env.require(balance(alice, aliceBTC)); + env.require(balance(bob, bobUSD)); + env.require(balance(bob, bobBTC)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'060'660'171779822, -9})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{353'553'390876116, -9})); + + // gw clawback USD from alice exceeding her balance + env(amm::ammClawback(gw, alice, USD, BTC, USD(5'000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(250'000001), + STAmount{USD, UINT64_C(500'0000004), -7}, + IOUAmount{353'553'390876116, -9})); + env.require(balance(alice, aliceUSD)); + env.require(balance(alice, aliceBTC + BTC(750'000001))); + env.require(balance(bob, bobUSD)); + env.require(balance(bob, bobBTC)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{353'553'390876116, -9})); + aliceBTC = env.balance(alice, BTC); + + // gw clawback BTC from bob which exceeds his balance with + // tfClawTwoAssets + env(amm::ammClawback(gw, bob, BTC, USD, BTC(300'000000)), txflags(tfClawTwoAssets)); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceUSD)); + env.require(balance(alice, aliceBTC)); + // USD is also clawed back from bob because of tfClawTwoAssets, + // bob's USD balance will not change + env.require(balance(bob, bobUSD)); + env.require(balance(bob, bobBTC)); + } + + // AMMClawback from MPT/MPT issued by the same issuer + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 30'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(2'000'000000), ETH(3'000'000000)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(2'000'000000), ETH(3'000'000000), IOUAmount{2'449'489'742'783178, -6})); + + amm.deposit(bob, BTC(4'000'000000), ETH(6'000'000000)); + BEAST_EXPECT(amm.expectBalances( + BTC(6'000'000000), ETH(9'000'000000), IOUAmount{7'348'469'228'349534, -6})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceETH = env.balance(alice, ETH); + auto bobBTC = env.balance(bob, BTC); + auto bobETH = env.balance(bob, ETH); + + // gw clawback BTC from alice + env(amm::ammClawback(gw, alice, BTC, ETH, BTC(1'000'000000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(5'000'000000), ETH(7'500'000000), IOUAmount{6'123'724'356'957944, -6})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH + ETH(1'500'000000))); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'224'744'871'391588, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{4'898'979'485'566356, -6})); + aliceETH = env.balance(alice, ETH); + + // gw clawback ETH and BTC from bob with tfClawTwoAssets + env(amm::ammClawback(gw, bob, ETH, BTC, ETH(3'000'000000)), txflags(tfClawTwoAssets)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(3'000'000000), ETH(4'500'000000), IOUAmount{3'674'234'614'174766, -6})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1'224'744'871'391588, -6})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2'449'489'742'783178, -6})); + + // gw clawback BTC from alice, which exceeds her balance with + // tfClawTwoAssets + env(amm::ammClawback(gw, alice, BTC, ETH, BTC(3'000'000000)), txflags(tfClawTwoAssets)); + env.close(); + BEAST_EXPECT(amm.expectBalances( + BTC(2'000'000001), ETH(3'000'000001), IOUAmount{2'449'489'742'783178, -6})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount{2'449'489'742'783178, -6})); + + // gw clawback ETH from bob, which is the same as his balance + env(amm::ammClawback(gw, bob, ETH, BTC, ETH(3'000'000001))); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC + BTC(2'000'000001))); + env.require(balance(bob, bobETH)); + } + } + + void + testAMMClawbackAllSameIssuer(FeatureBitset features) + { + testcase("test AMMClawback all, assets have the same issuer"); + using namespace jtx; + + // AMMClawback all from MPT/IOU issued by the same issuer + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(200000), bob); + env(pay(gw, bob, USD(60000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(2'000'000000), USD(8'000)); + env.close(); + BEAST_EXPECT(amm.expectBalances(BTC(2'000'000000), USD(8'000), IOUAmount(4'000'000))); + + amm.deposit(bob, BTC(1'000'000000), USD(4'000)); + env.close(); + BEAST_EXPECT(amm.expectBalances(BTC(3'000'000000), USD(12'000), IOUAmount(6'000'000))); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + auto bobBTC = env.balance(bob, BTC); + auto bobUSD = env.balance(bob, USD); + + // gw clawback all BTC and USD from alice + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), txflags(tfClawTwoAssets)); + env.close(); + + BEAST_EXPECT(amm.expectBalances(BTC(1'000'000000), USD(4'000), IOUAmount(2'000'000))); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(2'000'000))); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobUSD)); + + // gw clawback all USD from bob + env(amm::ammClawback(gw, bob, USD, BTC, std::nullopt)); + env.close(); + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + env.require(balance(bob, bobBTC + BTC(1'000'000000))); + env.require(balance(bob, bobUSD)); + } + + // AMMClawback all from MPT/MPT issued by the same issuer + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 30'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, BTC(20'000), ETH(10'000)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(20'000), ETH(10'000), IOUAmount{14'142'13562373095, -11})); + + amm.deposit(bob, BTC(40'000), ETH(20'000)); + BEAST_EXPECT( + amm.expectBalances(BTC(60'000), ETH(30'000), IOUAmount{42'426'40687119285, -11})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceETH = env.balance(alice, ETH); + auto bobBTC = env.balance(bob, BTC); + auto bobETH = env.balance(bob, ETH); + + // gw clawback all ETH from bob + env(amm::ammClawback(gw, bob, ETH, BTC, std::nullopt)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(20'000), ETH(10'000), IOUAmount{14'142'13562373095, -11})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC + BTC(40'000))); + env.require(balance(bob, bobETH)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{14'142'13562373095, -11})); + BEAST_EXPECT(amm.expectLPTokens(bob, IOUAmount(0))); + bobBTC = env.balance(bob, BTC); + + // gw clawback all ETH and BTC from alice with tfClawTwoAssets + env(amm::ammClawback(gw, alice, ETH, BTC, std::nullopt), txflags(tfClawTwoAssets)); + env.close(); + + // amm is empty and deleted + BEAST_EXPECT(!amm.ammExists()); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(bob, bobBTC)); + env.require(balance(bob, bobETH)); + } + } + + void + testAMMClawbackIssuesEachOther(FeatureBitset features) + { + testcase("test AMMClawback when issuing token for each other"); + using namespace jtx; + + // AMMClawback from MPT/IOU issued by each other + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + env.fund(XRP(1000000), gw, gw2, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), gw2); + env(pay(gw, gw2, USD(5000))); + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(5000))); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice, gw}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, gw, USD(1000), BTC(2000)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(USD(1000), BTC(2000), IOUAmount{1414'213562373095, -12})); + + amm.deposit(gw2, USD(2000), BTC(4000)); + BEAST_EXPECT( + amm.expectBalances(USD(3000), BTC(6000), IOUAmount{4242'640687119285, -12})); + + amm.deposit(alice, USD(3000), BTC(6000)); + BEAST_EXPECT( + amm.expectBalances(USD(6000), BTC(12000), IOUAmount{8485'281374238570, -12})); + + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414'213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{2828'427124746190, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242'640687119285, -12})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + auto gwBTC = env.balance(gw, BTC); + auto gw2USD = env.balance(gw2, USD); + + // gw claws back 1000 USD from gw2. + env(amm::ammClawback(gw, gw2, USD, BTC, USD(1000))); + env.close(); + BEAST_EXPECT( + amm.expectBalances(USD(5000), BTC(10000), IOUAmount{7071'067811865474, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{1414'213562373095, -12})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414'213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242'640687119285, -12})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + env.require(balance(gw, gwBTC)); + env.require(balance(gw2, gw2USD)); + + // gw2 claws back 1000 BTC from gw. + env(amm::ammClawback(gw2, gw, BTC, USD, BTC(1000)), ter(tesSUCCESS)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(USD(4500), BTC(9001), IOUAmount{6363'961030678927, -12})); + + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{707'1067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414'213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{4242'640687119285, -12})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + env.require(balance(gw, gwBTC)); + env.require(balance(gw2, gw2USD)); + + // gw2 claws back 4000 BTC from alice + env(amm::ammClawback(gw2, alice, BTC, USD, BTC(4000))); + env.close(); + BEAST_EXPECT(amm.expectBalances( + STAmount{USD, UINT64_C(2500'222197533607), -12}, + BTC(5001), + IOUAmount{3535'84814069829, -11})); + + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount{707'1067811865480, -13})); + BEAST_EXPECT(amm.expectLPTokens(gw2, IOUAmount{1414'213562373094, -12})); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount{1414'527797138648, -12})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + STAmount{USD, UINT64_C(1999'777802466393), -12})); + env.require(balance(gw, gwBTC)); + env.require(balance(gw2, gw2USD)); + } + + // AMMClawback from MPT/MPT issued by each other + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, gw2, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env(fset(gw2, asfAllowTrustLineClawback)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {gw2, alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {gw, alice}, + .pay = 30'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, gw, BTC(10'000), ETH(50'000)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(10'000), ETH(50'000), IOUAmount{22'360'67977499789, -11})); + + amm.deposit(gw2, BTC(20'000), ETH(100'000)); + BEAST_EXPECT( + amm.expectBalances(BTC(30'000), ETH(150'000), IOUAmount{67'082'03932499367, -11})); + + amm.deposit(alice, BTC(40'000), ETH(200'000)); + BEAST_EXPECT( + amm.expectBalances(BTC(70'000), ETH(350'000), IOUAmount{156'524'7584249852, -10})); + + auto aliceBTC = env.balance(alice, BTC); + auto aliceETH = env.balance(alice, ETH); + auto gw2BTC = env.balance(gw2, BTC); + auto gwETH = env.balance(gw, ETH); + + // gw claws back 1000 BTC from gw2. + env(amm::ammClawback(gw, gw2, BTC, ETH, BTC(1000))); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(69'001), ETH(345'001), IOUAmount{154'288'6904474855, -10})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(gw, gwETH)); + env.require(balance(gw2, gw2BTC)); + + // gw2 claws back all ETH from gw + env(amm::ammClawback(gw2, gw, ETH, BTC, std::nullopt)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(59'001), ETH(295'001), IOUAmount{131'928'0106724876, -10})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH)); + env.require(balance(gw, gwETH)); + env.require(balance(gw2, gw2BTC)); + + // gw claws back all BTC from alice + env(amm::ammClawback(gw, alice, BTC, ETH, std::nullopt)); + env.close(); + BEAST_EXPECT( + amm.expectBalances(BTC(19'001), ETH(95'001), IOUAmount{42'485'29157249607, -11})); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceETH + ETH(200'000))); + env.require(balance(gw, gwETH)); + env.require(balance(gw2, gw2BTC)); + } + } + + void + testAssetFrozenOrLocked(FeatureBitset features) + { + testcase("test AMMClawback when asset is frozen or locked"); + using namespace jtx; + + // test AMMClawback when MPT globally locked or IOU globally frozen + { + Env env{*this, features}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(1'000'000), gw, alice); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + auto const USD = gw["USD"]; + env.trust(USD(1'000'000), alice); + env(pay(gw, alice, USD(500'000))); + + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanClawback | tfMPTCanLock | MPTDEXFlags}); + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000)); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'000), BTC(10'000), IOUAmount(10'000))); + env.close(); + + auto aliceBTC = env.balance(alice, MPT(BTC)); + auto aliceUSD = env.balance(alice, USD); + + // globally locked and claw back 1000 BTC. + // this should be successful + BTC.set({.flags = tfMPTLock}); + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(1'000))); + BEAST_EXPECT(ammAlice.expectBalances(USD(9'000), BTC(9'000), IOUAmount(9'000))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(1'000))); + aliceUSD = env.balance(alice, USD); + + // unlock and claw back 2000 BTC + BTC.set({.flags = tfMPTUnlock}); + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(2'000))); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(USD, UINT64_C(7'000'000000000001), -12), BTC(7'001), IOUAmount(7'000))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(2'000))); + aliceUSD = env.balance(alice, USD); + + // globally freeze trustline and claw back 1000 USD. + // this should be successful + env(trust(gw, alice["USD"](0), tfSetFreeze)); + env.close(); + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(1'000))); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(USD, UINT64_C(6000'000000000002), -12), + BTC(6'001), + IOUAmount(6'000'000000000001, -12))); + env.require(balance(alice, aliceBTC + BTC(1'000))); + env.require(balance(alice, aliceUSD)); + aliceBTC = env.balance(alice, MPT(BTC)); + + // globally unfreeze trustline and claw back 2000 USD + // and 2000 BTC with tfClawTwoAssets + env(fset(gw, asfGlobalFreeze)); + env.close(); + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(2'000)), txflags(tfClawTwoAssets)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(USD, UINT64_C(4'000'000000000002), -12), + BTC(4'001), + IOUAmount(4'000'000000000001, -12))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + } + + // test AMMClawback when MPT individually locked or IOU individually + // frozen + { + Env env{*this, features}; + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(1'000'000), gw, alice); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + auto const USD = gw["USD"]; + env.trust(USD(1'000'000), alice); + env(pay(gw, alice, USD(500'000))); + + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanClawback | tfMPTCanLock | MPTDEXFlags}); + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000)); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'000), BTC(10'000), IOUAmount(10'000))); + env.close(); + + auto aliceBTC = env.balance(alice, MPT(BTC)); + auto aliceUSD = env.balance(alice, USD); + + // individually locked and claw back 2000 BTC from alice + BTC.set({.holder = alice, .flags = tfMPTLock}); + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(2'000))); + BEAST_EXPECT(ammAlice.expectBalances(USD(8'000), BTC(8'000), IOUAmount(8'000))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(2'000))); + aliceUSD = env.balance(alice, USD); + + // individually freeze trustline and claw back 1000 USD from alice + env(trust(gw, alice["USD"](0), tfSetFreeze)); + env.close(); + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(1'000))); + BEAST_EXPECT(ammAlice.expectBalances(USD(7'000), BTC(7'000), IOUAmount(7'000))); + env.require(balance(alice, aliceBTC + BTC(1'000))); + env.require(balance(alice, aliceUSD)); + aliceBTC = env.balance(alice, MPT(BTC)); + + // unlock MPT and claw back 3000 BTC from alice + BTC.set({.holder = alice, .flags = tfMPTUnlock}); + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(3'000))); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(4000'000000000001), -12}, BTC(4'001), IOUAmount(4'000))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(3'000))); + aliceUSD = env.balance(alice, USD); + + // unlock trustline and claw back 1000 USD from alice + env(trust(gw, alice["USD"](0), tfClearFreeze)); + env.close(); + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(1'000))); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount(USD, UINT64_C(3'000'000000000002), -12), + BTC(3'001), + IOUAmount(3000'000000000001, -12))); + env.require(balance(alice, aliceBTC + BTC(1'000))); + env.require(balance(alice, aliceUSD)); + } + } + + void + testSingleDepositAndClawback(FeatureBitset features) + { + testcase("test single depoit and clawback"); + using namespace jtx; + + // MPT/XRP + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(1000000000), gw, alice); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + // gw creates AMM pool of BTC/XRP. + AMM amm(env, gw, XRP(100), BTC(400), ter(tesSUCCESS)); + env.close(); + BEAST_EXPECT(amm.expectBalances(XRP(100), BTC(400), IOUAmount(200000))); + amm.deposit(alice, BTC(400)); + env.close(); + BEAST_EXPECT(amm.expectBalances(XRP(100), BTC(800), IOUAmount{282842'712474619, -9})); + + auto aliceBTC = env.balance(alice, MPT(BTC)); + auto aliceXRP = env.balance(alice, XRP); + + // gw clawback 100 BTC from alice + env(amm::ammClawback(gw, alice, MPT(BTC), XRP, BTC(100))); + BEAST_EXPECT(amm.expectBalances( + XRPAmount(87500001), BTC(701), IOUAmount{247'487'3734152917, -10})); + + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceXRP + XRPAmount(12'499999))); + } + + // MPT/IOU + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(1000000000), gw, alice); + env.close(); + + // gw sets asfAllowTrustLineClawback. + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + env.require(flags(gw, asfAllowTrustLineClawback)); + + // gw issues 1000 USD to Alice. + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(1000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + // gw creates AMM pool of BTC/USD. + AMM amm(env, gw, USD(100), BTC(400), ter(tesSUCCESS)); + env.close(); + BEAST_EXPECT(amm.expectBalances(USD(100), BTC(400), IOUAmount(200))); + amm.deposit(alice, BTC(400)); + env.close(); + BEAST_EXPECT(amm.expectBalances(USD(100), BTC(800), IOUAmount{282'842712474619, -12})); + + auto aliceBTC = env.balance(alice, MPT(BTC)); + auto aliceUSD = env.balance(alice, USD); + + // gw clawback 100 BTC from alice + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(100))); + BEAST_EXPECT(amm.expectBalances( + STAmount{USD, UINT64_C(87'50000000000003), -14}, + BTC(701), + IOUAmount{247'4873734152917, -13})); + + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(12.5))); + aliceUSD = env.balance(alice, USD); + + // gw clawback 30 USD from alice with tfClawTwoAssets, which exceeds + // her balance + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(30)), txflags(tfClawTwoAssets)); + BEAST_EXPECT(amm.expectBalances( + STAmount{USD, UINT64_C(70'71067811865476), -14}, BTC(567), IOUAmount(200))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount(200))); + } + + // MPT/MPT + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(1000000000), gw, alice); + env.close(); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + // gw creates AMM pool of BTC/USD. + AMM amm(env, gw, USD(100), BTC(400), ter(tesSUCCESS)); + env.close(); + BEAST_EXPECT(amm.expectBalances(USD(100), BTC(400), IOUAmount(200))); + amm.deposit(alice, BTC(400)); + env.close(); + BEAST_EXPECT(amm.expectBalances(USD(100), BTC(800), IOUAmount{282'842712474619, -12})); + + auto aliceBTC = env.balance(alice, MPT(BTC)); + auto aliceUSD = env.balance(alice, USD); + + // gw clawback 100 BTC from alice + env(amm::ammClawback(gw, alice, MPT(BTC), USD, BTC(100))); + BEAST_EXPECT(amm.expectBalances(USD(88), BTC(701), IOUAmount{247'4873734152917, -13})); + + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD + USD(12))); + aliceUSD = env.balance(alice, USD); + + // gw clawback 30 USD from alice with tfClawTwoAssets, which exceeds + // her balance + env(amm::ammClawback(gw, alice, USD, MPT(BTC), USD(30)), txflags(tfClawTwoAssets)); + BEAST_EXPECT(amm.expectBalances(USD(72), BTC(567), IOUAmount(200))); + env.require(balance(alice, aliceBTC)); + env.require(balance(alice, aliceUSD)); + BEAST_EXPECT(amm.expectLPTokens(alice, IOUAmount(0))); + BEAST_EXPECT(amm.expectLPTokens(gw, IOUAmount(200))); + } + } + + void + testLastHolderLPTokenBalance(FeatureBitset features) + { + testcase( + "test last holder's lptoken balance not equal to AMM's lptoken " + "balance before clawback"); + using namespace jtx; + std::string logs; + + // MPT/IOU + { + Env env(*this, features, std::make_unique(&logs)); + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(100000), bob); + env(pay(gw, bob, USD(40000))); + env.close(); + + MPT const EUR = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, USD(2), EUR(1)); + amm.deposit(alice, IOUAmount{1'576123487565916, -15}); + amm.deposit(bob, IOUAmount{1'000}); + amm.withdraw(alice, IOUAmount{1'576123487565916, -15}); + amm.withdrawAll(bob); + + auto const lpToken = + getAccountLines(env, alice, amm.lptIssue())[jss::lines][0u][jss::balance] + .asString(); + auto const lpTokenBalance = + amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); + if (features[featureSingleAssetVault] || features[featureLendingProtocol]) + { + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.4142135623741"); + } + else + { + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.414213562374"); + } + + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + BEAST_EXPECT(res && res.value()); + + if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt)); + BEAST_EXPECT(!amm.ammExists()); + } + else if ( + features[fixAMMv1_3] && + (features[featureSingleAssetVault] || features[featureLendingProtocol])) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt)); + // Without the Rounding feature and with new Number a dust pool + // amount remains + BEAST_EXPECT(amm.ammExists()); + } + else if (!features[featureSingleAssetVault] && !features[featureLendingProtocol]) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), ter(tecINTERNAL)); + BEAST_EXPECT(amm.ammExists()); + } + else + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), ter(tecAMM_BALANCE)); + BEAST_EXPECT(amm.ammExists()); + } + } + + // MPT/MPT + { + Env env(*this, features, std::make_unique(&logs)); + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + MPT const EUR = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM amm(env, alice, USD(2), EUR(1)); + amm.deposit(alice, IOUAmount{1'576123487565916, -15}); + amm.deposit(bob, IOUAmount{1'000}); + amm.withdraw(alice, IOUAmount{1'576123487565916, -15}); + amm.withdrawAll(bob); + + auto const lpToken = + getAccountLines(env, alice, amm.lptIssue())[jss::lines][0u][jss::balance] + .asString(); + auto const lpTokenBalance = + amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); + if (!features[featureSingleAssetVault] && !features[featureLendingProtocol]) + { + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.414213562374"); + } + else + { + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.4142135623741"); + } + + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + BEAST_EXPECT(res && res.value()); + + if (features[fixAMMv1_3] && features[fixAMMClawbackRounding]) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt)); + BEAST_EXPECT(!amm.ammExists()); + } + else if ( + features[fixAMMv1_3] && + (features[featureSingleAssetVault] || features[featureLendingProtocol])) + { + // Without the Rounding feature and with new Number a dust pool + // amount remains + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt)); + BEAST_EXPECT(amm.ammExists()); + } + else if (!features[featureSingleAssetVault] && !features[featureLendingProtocol]) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), ter(tecINTERNAL)); + BEAST_EXPECT(amm.ammExists()); + } + else if (features[featureMPTokensV2]) + { + env(amm::ammClawback(gw, alice, USD, EUR, std::nullopt), ter(tecAMM_BALANCE)); + BEAST_EXPECT(amm.ammExists()); + } + } + } + + void + testClawAssetCheck(FeatureBitset features) + { + testcase("claw asset check for MPT and IOU"); + using namespace jtx; + + // IOU/MPT, MPT not clawable + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(1000))); + env.close(); + + MPT const BTC = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 40'000}); + + AMM const amm(env, alice, USD(200), BTC(100)); + // Asset BTC is not clawable without tfMPTCanClawback. + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), ter(tecNO_PERMISSION)); + + // Although USD is clawable with asfAllowTrustLineClawback. + // When tfClawTwoAssets is set, we will claw Asser2 as well. + // But Asset2 is not clawable. tfMPTCanClawback was not set for BTC. + env(amm::ammClawback(gw, alice, USD, BTC, std::nullopt), + txflags(tfClawTwoAssets), + ter(tecNO_PERMISSION)); + + // Can only claw the other asset + env(amm::ammClawback(gw, alice, USD, BTC, std::nullopt)); + } + + // IOU/MPT, IOU not clawable + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, alice); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(1000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + // Asset USD is not clawable without asfAllowTrustLineClawback. + AMM const amm(env, alice, USD(200), BTC(100)); + env(amm::ammClawback(gw, alice, USD, BTC, std::nullopt), ter(tecNO_PERMISSION)); + + // Although BTC is clawable with tfMPTCanClawback. + // When tfClawTwoAssets is set, we will claw Asset2 as well. + // But Asset2 is not clawable. asfAllowTrustLineClawback was not set + // by the issuer. + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), + txflags(tfClawTwoAssets), + ter(tecNO_PERMISSION)); + + // Can only claw the other asset + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt)); + } + + // IOU/MPT both clawable + { + Env env(*this, features); + Account const gw{"gateway"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; + env.fund(XRP(100000), gw, gw2, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(1000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw2, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + + AMM const amm(env, alice, USD(200), BTC(100)); + + // the account trying to claw MPT is not its issuer + // will return temMALFORMED in preflight. + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), ter(temMALFORMED)); + } + + // only issuer can claw. IOU/MPT mix + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + Account const gw("gateway"), alice("alice"), bob("bob"); + env.fund(XRP(30'000), alice, bob, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = bob, + .holders = {alice}, + .limit = 1'000'000}); + env(pay(gw, alice, USD(50000))); + env(pay(bob, alice, BTC(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10100)); + // BTC's issuer is bob, alice can not clawback + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), ter(temMALFORMED)); + }; + testHelper2TokensMix(test); + } + + // set tfClawTwoAssets, but the two assets are from different issuer. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + Account const gw("gateway"), alice("alice"), bob("bob"); + env.fund(XRP(30'000), alice, bob, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = bob, + .holders = {alice}, + .limit = 1'000'000}); + env(pay(gw, alice, USD(50000))); + env(pay(bob, alice, BTC(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10100)); + // BTC's issuer is bob. But with tfClawTwoAssets, we will claw + // both. It will fail because the other asset USD's issuer is + // gw. + env(amm::ammClawback(bob, alice, BTC, USD, std::nullopt), + txflags(tfClawTwoAssets), + ter(temINVALID_FLAG)); + }; + testHelper2TokensMix(test); + } + } + + void + run() override + { + FeatureBitset const all{jtx::testable_amendments() | fixAMMClawbackRounding}; + + testInvalidRequest(all); + testFeatureDisabled(all); + testAMMClawbackAmount(all); + testAMMClawbackAll(all); + testAMMClawbackAmountSameIssuer(all); + testAMMClawbackAllSameIssuer(all); + testAMMClawbackIssuesEachOther(all); + testAssetFrozenOrLocked(all); + testSingleDepositAndClawback(all); + testLastHolderLPTokenBalance(all); + testLastHolderLPTokenBalance(all - fixAMMv1_3 - fixAMMClawbackRounding); + testLastHolderLPTokenBalance( + all - fixAMMv1_3 - fixAMMClawbackRounding - featureSingleAssetVault - + featureLendingProtocol); + testLastHolderLPTokenBalance(all - fixAMMClawbackRounding); + testClawAssetCheck(all); + } +}; + +BEAST_DEFINE_TESTSUITE(AMMClawbackMPT, app, xrpl); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/AMMClawback_test.cpp b/src/test/app/AMMClawback_test.cpp index a0def59c92..3160354445 100644 --- a/src/test/app/AMMClawback_test.cpp +++ b/src/test/app/AMMClawback_test.cpp @@ -43,7 +43,7 @@ class AMMClawback_test : public beast::unit_test::suite // return terNO_AMM error. { Env env(*this); - Account gw{"gateway"}; + Account const gw{"gateway"}; Account const alice{"alice"}; env.fund(XRP(100000), gw, alice); env.close(); @@ -674,8 +674,8 @@ class AMMClawback_test : public beast::unit_test::suite Env env(*this, features); Account const gw{"gateway"}; Account const gw2{"gateway2"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000000), gw, gw2, alice, bob); env.close(); @@ -1085,8 +1085,8 @@ class AMMClawback_test : public beast::unit_test::suite Account const gw{"gateway"}; Account const gw2{"gateway2"}; Account const alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(1000000), gw, gw2, alice, bob, carol); env.close(); @@ -1289,8 +1289,8 @@ class AMMClawback_test : public beast::unit_test::suite { Env env(*this, features); Account const gw{"gateway"}; - Account alice{"alice"}; - Account bob{"bob"}; + Account const alice{"alice"}; + Account const bob{"bob"}; env.fund(XRP(1000000), gw, alice, bob); env.close(); @@ -1402,8 +1402,8 @@ class AMMClawback_test : public beast::unit_test::suite Env env(*this, features); Account const gw{"gateway"}; Account const alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(1000000), gw, alice, bob, carol); env.close(); @@ -1537,7 +1537,7 @@ class AMMClawback_test : public beast::unit_test::suite Account const gw{"gateway"}; Account const gw2{"gateway2"}; Account const alice{"alice"}; - Account bob{"bob"}; + Account const bob{"bob"}; env.fund(XRP(1000000), gw, gw2, alice, bob); env.close(); @@ -1630,8 +1630,8 @@ class AMMClawback_test : public beast::unit_test::suite // each other. Env env(*this, features); Account const gw{"gateway"}; - Account gw2{"gateway2"}; - Account alice{"alice"}; + Account const gw2{"gateway2"}; + Account const alice{"alice"}; env.fund(XRP(1000000), gw, gw2, alice); env.close(); @@ -2012,8 +2012,8 @@ class AMMClawback_test : public beast::unit_test::suite Env env(*this, features); Account const gw{"gateway"}; Account const alice{"alice"}; - Account bob{"bob"}; - Account carol{"carol"}; + Account const bob{"bob"}; + Account const carol{"carol"}; env.fund(XRP(1000000), gw, alice, bob, carol); env.close(); @@ -2150,7 +2150,7 @@ class AMMClawback_test : public beast::unit_test::suite // to the holder. Env env(*this, features, std::make_unique(&logs)); Account const gw{"gateway"}; - Account alice{"alice"}; + Account const alice{"alice"}; env.fund(XRP(1000000000), gw, alice); env.close(); @@ -2212,21 +2212,22 @@ class AMMClawback_test : public beast::unit_test::suite using namespace jtx; std::string logs; - auto setupAccounts = [&](Env& env, Account& gw, Account& alice, Account& bob) { - env.fund(XRP(100000), gw, alice, bob); - env.close(); - env(fset(gw, asfAllowTrustLineClawback)); - env.close(); + auto setupAccounts = + [&](Env& env, Account const& gw, Account const& alice, Account const& bob) { + env.fund(XRP(100000), gw, alice, bob); + env.close(); + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); - auto const USD = gw["USD"]; - env.trust(USD(100000), alice); - env(pay(gw, alice, USD(50000))); - env.trust(USD(100000), bob); - env(pay(gw, bob, USD(40000))); - env.close(); + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(100000), bob); + env(pay(gw, bob, USD(40000))); + env.close(); - return USD; - }; + return USD; + }; auto getLPTokenBalances = [&](auto& env, auto const& amm, @@ -2242,7 +2243,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/XRP pool. AMMClawback almost last holder's USD balance { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); AMM amm(env, alice, XRP(2), USD(1)); @@ -2275,7 +2276,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/XRP pool. AMMClawback part of last holder's USD balance { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); AMM amm(env, alice, XRP(2), USD(1)); @@ -2317,7 +2318,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/XRP pool. AMMClawback all of last holder's USD balance { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); AMM amm(env, alice, XRP(2), USD(1)); @@ -2354,7 +2355,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/IOU pool, different issuers { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); Account const gw2{"gateway2"}; @@ -2394,7 +2395,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/IOU pool, same issuer { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); auto const EUR = gw["EUR"]; @@ -2433,7 +2434,7 @@ class AMMClawback_test : public beast::unit_test::suite // IOU/IOU pool, larger asset ratio { Env env(*this, features, std::make_unique(&logs)); - Account gw{"gateway"}, alice{"alice"}, bob{"bob"}; + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; auto const USD = setupAccounts(env, gw, alice, bob); auto const EUR = gw["EUR"]; diff --git a/src/test/app/AMMExtendedMPT_test.cpp b/src/test/app/AMMExtendedMPT_test.cpp new file mode 100644 index 0000000000..9ef71dec8c --- /dev/null +++ b/src/test/app/AMMExtendedMPT_test.cpp @@ -0,0 +1,3619 @@ +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +/** + * Tests of AMM MPT that use offers. + */ +struct AMMExtendedMPT_test : public jtx::AMMTest +{ +private: + void + testRmFundedOffer(FeatureBitset features) + { + testcase("Incorrect Removal of Funded Offers"); + + // We need at least two paths. One at good quality and one at bad + // quality. The bad quality path needs two offer books in a row. + // Each offer book should have two offers at the same quality, the + // offers should be completely consumed, and the payment should + // require both offers to be satisfied. The first offer must + // be "taker gets" XRP. Ensure that the payment engine does not remove + // the first "taker gets" xrp offer, because the offer is still + // funded and not used for the payment. + + using namespace jtx; + Env env{*this, features}; + + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 200'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 2'000'000'000'000'000, + .flags = MPTDEXFlags}); + + // Must be two offers at the same quality + // "taker gets" must be XRP + // (Different amounts so I can distinguish the offers) + env(offer(carol, BTC(49'000'000'000'000), XRP(49))); + env(offer(carol, BTC(51'000'000'000'000), XRP(51))); + + // Offers for the poor quality path + // Must be two offers at the same quality + env(offer(carol, XRP(50), ETH(50'000'000'000'000))); + env(offer(carol, XRP(50), ETH(50'000'000'000'000))); + + // Good quality path + AMM const ammCarol(env, carol, BTC(1'000'000'000'000'000), ETH(100'100'000'000'000'000)); + + PathSet const paths(Path(XRP, MPT(ETH)), Path(MPT(ETH))); + + env(pay(alice, bob, ETH(100'000'000'000'000)), + json(paths.json()), + sendmax(BTC(1'000'000'000'000'000)), + txflags(tfPartialPayment)); + + BEAST_EXPECT(ammCarol.expectBalances( + BTC(1'001'000'000'374'816), ETH(100'000'000'000'000'000), ammCarol.tokens())); + + env.require(balance(bob, ETH(200'100'000'000'000'000))); + BEAST_EXPECT(isOffer(env, carol, BTC(49'000'000'000'000), XRP(49))); + } + + void + testFillModes(FeatureBitset features) + { + testcase("Fill Modes"); + using namespace jtx; + + auto const startBalance = XRP(1'000'000); + + // Fill or Kill - unless we fully cross, just charge a fee and don't + // place the offer on the books. But also clean up expired offers + // that are discovered along the way. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const& BTC = MPT(ammAlice[1]); + auto const baseFee = env.current()->fees().base; + auto carolBTC = env.balance(carol, BTC); + auto carolXRP = env.balance(carol, XRP); + // Order that can't be filled + env(offer(carol, BTC(100), XRP(100)), txflags(tfFillOrKill), ter(tecKILLED)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), BTC(10'000), ammAlice.tokens())); + // fee = AMM + env.require(balance(carol, carolXRP - baseFee)); + env.require(balance(carol, carolBTC)); + + BEAST_EXPECT(expectOffers(env, carol, 0)); + carolXRP = env.balance(carol, XRP); + + // Order that can be filled + env(offer(carol, XRP(100), BTC(100)), txflags(tfFillOrKill), ter(tesSUCCESS)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'100), ammAlice.tokens())); + env.require(balance(carol, carolXRP + XRP(100) - baseFee)); + env.require(balance(carol, carolBTC - BTC(100))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + }, + {{XRP(10'100), AMMMPT(10'000)}}, + 0, + std::nullopt, + {features}); + + // Immediate or Cancel - cross as much as possible + // and add nothing on the books. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const& BTC = MPT(ammAlice[1]); + auto const baseFee = env.current()->fees().base; + auto carolBTC = env.balance(carol, BTC); + auto carolXRP = env.balance(carol, XRP); + env(offer(carol, XRP(200), BTC(200)), + txflags(tfImmediateOrCancel), + ter(tesSUCCESS)); + + // AMM generates a synthetic offer of 100BTC/100XRP + // to match the CLOB offer quality. + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'100), ammAlice.tokens())); + // +AMM - offer * fee + env.require(balance(carol, carolXRP + XRP(100) - baseFee)); + env.require(balance(carol, carolBTC - BTC(100))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + }, + {{XRP(10'100), AMMMPT(10'000)}}, + 0, + std::nullopt, + {features}); + + // tfPassive -- place the offer without crossing it. + testAMM( + [&](AMM& ammAlice, Env& env) { + // Carol creates a passive offer that could cross AMM. + // Carol's offer should stay in the ledger. + auto const& BTC = MPT(ammAlice[1]); + env(offer(carol, XRP(100), BTC(100), tfPassive)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), BTC(10'000), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 1, {{{XRP(100), BTC(100)}}})); + }, + {{XRP(10'100), AMMMPT(10'000)}}, + 0, + std::nullopt, + {features}); + + // tfPassive -- cross only offers of better quality. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const& BTC = MPT(ammAlice[1]); + env(offer(alice, BTC(110), XRP(100))); + env.close(); + + // Carol creates a passive offer. That offer should cross + // AMM and leave Alice's offer untouched. + env(offer(carol, XRP(100), BTC(100), tfPassive)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'900), BTC(9083), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, alice, 1)); + }, + {{XRP(11'000), AMMMPT(9'000)}}, + 0, + std::nullopt, + {features}); + } + + void + testOfferCrossWithXRP(FeatureBitset features) + { + testcase("Offer Crossing with XRP, Normal order"); + + using namespace jtx; + + Env env{*this, features}; + + fund(env, gw, {bob, alice}, XRP(300'000)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 100'000'000, + .flags = MPTDEXFlags}); + + AMM const ammAlice(env, alice, XRP(150'000), BTC(50'000'000)); + + // Existing offer pays better than this wants. + // Partially consume existing offer. + // Pay 1'000'000 BTC, get 3061224490 Drops. + auto const xrpTransferred = XRPAmount{3'061'224'490}; + env(offer(bob, BTC(1'000'000), XRP(4'000))); + + BEAST_EXPECT(ammAlice.expectBalances( + XRP(150'000) + xrpTransferred, BTC(49'000'000), IOUAmount{273'861'278752583, -5})); + + env.require(balance(bob, BTC(101'000'000))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(300'000) - xrpTransferred - 2 * txfee(env, 1))); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + void + testOfferCrossWithLimitOverride(FeatureBitset features) + { + testcase("Offer Crossing with Limit Override"); + + using namespace jtx; + + Env env{*this, features}; + + env.fund(XRP(200'000), gw, alice, bob); + env.close(); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(500'000'000))); + + AMM const ammAlice(env, alice, XRP(150'000), BTC(51'000'000)); + env(offer(bob, BTC(1'000'000), XRP(3'000))); + + BEAST_EXPECT(ammAlice.expectBalances(XRP(153'000), BTC(50'000'000), ammAlice.tokens())); + + env.require(balance(bob, BTC(1'000'000))); + env.require(balance(bob, XRP(200'000) - XRP(3'000) - env.current()->fees().base * 2)); + } + + void + testCurrencyConversionEntire(FeatureBitset features) + { + testcase("Currency Conversion: Entire Offer"); + + using namespace jtx; + + Env env{*this, features}; + + fund(env, gw, {alice, bob}, XRP(10'000)); + env.require(owners(bob, 0)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + env(pay(gw, bob, BTC(1'000'000'000))); + + env.require(owners(alice, 1), owners(bob, 1)); + + env(pay(gw, alice, BTC(100'000'000))); + AMM const ammBob(env, bob, BTC(200'000'000), XRP(1'500)); + + env(pay(alice, alice, XRP(500)), sendmax(BTC(100'000'000))); + + BEAST_EXPECT(ammBob.expectBalances(BTC(300'000'000), XRP(1'000), ammBob.tokens())); + env.require(balance(alice, BTC(0))); + + auto jrr = ledgerEntryRoot(env, alice); + env.require(balance(alice, XRP(10'000) + XRP(500) - env.current()->fees().base * 2)); + } + + void + testCurrencyConversionInParts(FeatureBitset features) + { + testcase("Currency Conversion: In Parts"); + + using namespace jtx; + + Env env{*this, features}; + env.fund(XRP(30'000), gw, bob); + env.fund(XRP(40'000), alice); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 30'000'000'000, + .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(10'000'000'000))); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000'000'000)); + env.close(); + + // Alice converts BTC to XRP which should fail + // due to PartialPayment. + env(pay(alice, alice, XRP(100)), sendmax(BTC(100'000'000)), ter(tecPATH_PARTIAL)); + + // Alice converts BTC to XRP, should succeed because + // we permit partial payment + env(pay(alice, alice, XRP(100)), sendmax(BTC(100'000'000)), txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{9'900'990'100}, BTC(10'100'000'000), ammAlice.tokens())); + // initial 40,000'000'000 - 10,000'000'000AMM - 100'000'000pay + env.require(balance(alice, BTC(29'900'000'000))); + // initial 40,000 - 10,0000AMM + 99.009900pay - fee*3 + BEAST_EXPECT(expectLedgerEntryRoot( + env, + alice, + XRP(40'000) - XRP(10'000) + XRPAmount{99'009'900} - ammCrtFee(env) - txfee(env, 3))); + } + + void + testCrossCurrencyStartXRP(FeatureBitset features) + { + testcase("Cross Currency Payment: Start with XRP"); + + using namespace jtx; + + Env env{*this, features}; + env.fund(XRP(30'000), gw); + env.fund(XRP(40'000), alice); + env.fund(XRP(1'000), bob); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(10'100'000'000))); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000'000)); + env.close(); + + env(pay(alice, bob, BTC(100'000'000)), sendmax(XRP(100))); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), BTC(10'000'000'000), ammAlice.tokens())); + env.require(balance(bob, BTC(100'000'000))); + } + + void + testCrossCurrencyEndXRP(FeatureBitset features) + { + testcase("Cross Currency Payment: End with XRP"); + + using namespace jtx; + + Env env{*this, features}; + env.fund(XRP(30'000), gw); + env.fund(XRP(40'100), alice); + env.fund(XRP(1'000), bob); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(40'000'000'000))); + + AMM const ammAlice(env, alice, XRP(10'100), BTC(10'000'000'000)); + env.close(); + + env(pay(alice, bob, XRP(100)), sendmax(BTC(100'000'000))); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'100'000'000), ammAlice.tokens())); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(1'000) + XRP(100) - txfee(env, 1))); + } + + void + testCrossCurrencyBridged(FeatureBitset features) + { + testcase("Cross Currency Payment: Bridged"); + + using namespace jtx; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + auto const dan = Account{"dan"}; + env.fund(XRP(60'000), alice, bob, carol, gw, dan); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob, carol, dan}, + .limit = 10'000'000'000'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol, dan}, + .limit = 10'000'000'000'000'000}); + env(pay(gw, alice, BTC(500'000'000'000'000))); + env(pay(gw, carol, BTC(6'000'000'000'000'000))); + env(pay(gw, dan, ETH(400'000'000'000'000))); + env.close(); + env.close(); + AMM const ammCarol(env, carol, BTC(5'000'000'000'000'000), XRP(50'000)); + + env(offer(dan, XRP(500), ETH(50'000'000'000'000))); + env.close(); + + Json::Value jtp{Json::arrayValue}; + jtp[0u][0u][jss::currency] = "XRP"; + env(pay(alice, bob, ETH(30'000'000'000'000)), + json(jss::Paths, jtp), + sendmax(BTC(333'000'000'000'000))); + env.close(); + BEAST_EXPECT(ammCarol.expectBalances( + XRP(49'700), BTC(5'030'181'086'519'115), ammCarol.tokens())); + BEAST_EXPECT(expectOffers(env, dan, 1, {{Amounts{XRP(200), ETH(20'000'000'000'000)}}})); + env.require(balance(bob, ETH(30'000'000'000'000))); + }; + testHelper2TokensMix(test); + } + + void + testOfferFeesConsumeFunds(FeatureBitset features) + { + testcase("Offer Fees Consume Funds"); + + using namespace jtx; + + Env env{*this, features}; + + // Provide micro amounts to compensate for fees to make results round + // nice. + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(2) + env.current()->fees().base * 3; + + env.fund(starting_xrp, gw, alice); + env.fund(XRP(2'000), bob); + env.close(); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + + // Created only to increase one reserve count for alice + MPTTester const ETH({.env = env, .issuer = gw, .holders = {alice}, .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(1'200'000'000'000'000))); + + AMM const ammBob(env, bob, XRP(1'000), BTC(1'200'000'000'000'000)); + // Alice has 400 - (2 reserve of 50 = 300 reserve) = 100 available. + // Ask for more than available to prove reserve works. + env(offer(alice, BTC(200'000'000'000'000), XRP(200))); + + // The pool gets only 100XRP for ~109.09e12BTC, even though + // it can exchange more. + BEAST_EXPECT( + ammBob.expectBalances(XRP(1'100), BTC(1'090'909'090'909'091), ammBob.tokens())); + + env.require(balance(alice, BTC(109'090'909'090'909))); + env.require(balance(alice, XRP(300))); + } + + void + testOfferCreateThenCross(FeatureBitset features) + { + testcase("Offer Create, then Cross"); + + using namespace jtx; + + Env env{*this, features}; + + fund(env, gw, {alice, bob}, XRP(200'000)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 500, + .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(1'000'000'000'000))); + env(pay(gw, alice, BTC(200'000'000'000'000))); + + AMM const ammAlice(env, alice, BTC(150'000'000'000'000), XRP(150'100)); + env(offer(bob, XRP(100), BTC(100'000'000'000))); + + BEAST_EXPECT( + ammAlice.expectBalances(BTC(150'100'000'000'000), XRP(150'000), ammAlice.tokens())); + + // Bob pays 0.005 transfer fee. + env.require(balance(bob, BTC(899'500'000'000))); + } + + void + testSellFlagBasic(FeatureBitset features) + { + testcase("Offer tfSell: Basic Sell"); + + using namespace jtx; + + Env env{*this, features}; + env.fund(XRP(30'000), gw, bob, carol); + env.fund(XRP(39'900), alice); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000, + .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(10'100))); + + AMM const ammAlice(env, alice, XRP(9'900), BTC(10'100)); + + env(offer(carol, BTC(100), XRP(100)), json(jss::Flags, tfSell)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(9'999), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + env.require(balance(carol, BTC(30'101))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(30'000) - XRP(100) - 2 * txfee(env, 1))); + } + + void + testSellFlagExceedLimit(FeatureBitset features) + { + testcase("Offer tfSell: 2x Sell Exceed Limit"); + + using namespace jtx; + + Env env{*this, features}; + + auto const starting_xrp = XRP(100) + reserve(env, 1) + env.current()->fees().base * 2; + + env.fund(starting_xrp, gw, alice); + env.fund(XRP(2'000), bob); + env.close(); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + env(pay(gw, bob, BTC(2'200'000'000))); + + AMM const ammBob(env, bob, XRP(1'000), BTC(2'200'000'000)); + // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. + // Ask for more than available to prove reserve works. + // Taker pays 100'000'000 BTC for 100 XRP. + // Selling XRP. + // Will sell all 100 XRP and get more BTC than asked for. + env(offer(alice, BTC(100'000'000), XRP(200)), json(jss::Flags, tfSell)); + BEAST_EXPECT(ammBob.expectBalances(XRP(1'100), BTC(2'000'000'000), ammBob.tokens())); + env.require(balance(alice, BTC(200'000'000))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, XRP(250))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + + void + testGatewayCrossCurrency(FeatureBitset features) + { + testcase("Client Issue: Gateway Cross Currency"); + + using namespace jtx; + + Env env{*this, features}; + + auto const starting_xrp = XRP(100.1) + reserve(env, 1) + env.current()->fees().base * 2; + env.fund(starting_xrp, gw, alice, bob); + + MPTTester const XTS( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const XXX( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammAlice(env, alice, XTS(1'000'000'000'000'000), XXX(1'000'000'000'000'000)); + + Json::Value payment; + payment[jss::secret] = toBase58(generateSeed("bob")); + payment[jss::id] = env.seq(bob); + payment[jss::build_path] = true; + payment[jss::tx_json] = pay(bob, bob, XXX(10'000'000'000'000)); + payment[jss::tx_json][jss::Sequence] = + env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); + payment[jss::tx_json][jss::SendMax] = + XTS(15'000'000'000'000).value().getJson(JsonOptions::none); + payment[jss::tx_json][jss::Flags] = tfPartialPayment; + auto const jrr = env.rpc("json", "submit", to_string(payment)); + BEAST_EXPECT(jrr[jss::result][jss::status] == "success"); + BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); + + BEAST_EXPECT(ammAlice.expectBalances( + XTS(1'010'101'010'101'011), XXX(990'000'000'000'000), ammAlice.tokens())); + env.require(balance(bob, XTS(989'898'989'898'989))); + env.require(balance(bob, XXX(1'010'000'000'000'000))); + } + + void + testBridgedCross(FeatureBitset features) + { + testcase("Bridged Crossing"); + + using namespace jtx; + + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + + // The scenario: + // o BTC/XRP AMM is created. + // o ETH/XRP AMM is created. + // o carol has ETH but wants BTC. + // Note that carol's offer must come last. If carol's offer is + // placed before AMM is created, then autobridging will not occur. + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000'000)); + AMM const ammBob(env, bob, ETH(10'000'000'000), XRP(10'100)); + + // Carol makes an offer that consumes AMM liquidity and + // fully consumes Carol's offer. + env(offer(carol, BTC(100'000'000), ETH(100'000'000))); + env.close(); + + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), BTC(10'000'000'000), ammAlice.tokens())); + BEAST_EXPECT(ammBob.expectBalances(XRP(10'000), ETH(10'100'000'000), ammBob.tokens())); + env.require(balance(carol, BTC(15'100'000'000))); + env.require(balance(carol, ETH(14'900'000'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + + // The scenario: + // o BTC/XRP AMM is created. + // o ETH/XRP offer is created. + // o carol has ETH but wants BTC. + // Note that carol's offer must come last. If carol's offer is + // placed before AMM and bob's offer are created, then autobridging + // will not occur. + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000'000)); + env(offer(bob, ETH(100'000'000), XRP(100))); + env.close(); + + // Carol makes an offer that consumes AMM liquidity and + // fully consumes Carol's offer. + env(offer(carol, BTC(100'000'000), ETH(100'000'000))); + env.close(); + + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), BTC(10'000'000'000), ammAlice.tokens())); + env.require(balance(carol, BTC(15'100'000'000))); + env.require(balance(carol, ETH(14'900'000'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 15'000'000'000, + .flags = MPTDEXFlags}); + + // The scenario: + // o BTC/XRP offer is created. + // o ETH/XRP AMM is created. + // o carol has ETH but wants BTC. + // Note that carol's offer must come last. If carol's offer is + // placed before AMM and alice's offer are created, then + // autobridging will not occur. + env(offer(alice, XRP(100), BTC(100'000'000))); + env.close(); + AMM const ammBob(env, bob, ETH(10'000'000'000), XRP(10'100)); + + // Carol makes an offer that consumes AMM liquidity and + // fully consumes Carol's offer. + env(offer(carol, BTC(100'000'000), ETH(100'000'000))); + env.close(); + + BEAST_EXPECT(ammBob.expectBalances(XRP(10'000), ETH(10'100'000'000), ammBob.tokens())); + env.require(balance(carol, BTC(15'100'000'000))); + env.require(balance(carol, ETH(14'900'000'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + } + + void + testSellWithFillOrKill(FeatureBitset features) + { + // Test a number of different corner cases regarding offer crossing + // when both the tfSell flag and tfFillOrKill flags are set. + testcase("Combine tfSell with tfFillOrKill"); + + using namespace jtx; + + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 20'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammBob(env, bob, XRP(20'000), BTC(200'000'000)); + // alice submits a tfSell | tfFillOrKill offer that does not cross. + env(offer(alice, BTC(2'100'000), XRP(210), tfSell | tfFillOrKill), ter(tecKILLED)); + + BEAST_EXPECT(ammBob.expectBalances(XRP(20'000), BTC(200'000'000), ammBob.tokens())); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammBob(env, bob, XRP(20'000), BTC(200'000'000'000'000)); + // alice submits a tfSell | tfFillOrKill offer that crosses. + // Even though tfSell is present it doesn't matter this time. + env(offer(alice, BTC(2'000'000'000'000), XRP(220), tfSell | tfFillOrKill)); + env.close(); + BEAST_EXPECT( + ammBob.expectBalances(XRP(20'220), BTC(197'823'936'696'341), ammBob.tokens())); + env.require(balance(alice, BTC(1'002'176'063'303'659))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + { + // alice submits a tfSell | tfFillOrKill offer that crosses and + // returns more than was asked for (because of the tfSell flag). + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammBob(env, bob, XRP(20'000), BTC(200'000'000'000'000)); + + env(offer(alice, BTC(10'000'000'000'000), XRP(1'500), tfSell | tfFillOrKill)); + env.close(); + + BEAST_EXPECT( + ammBob.expectBalances(XRP(21'500), BTC(186'046'511'627'907), ammBob.tokens())); + env.require(balance(alice, BTC(1'013'953'488'372'093))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + { + // alice submits a tfSell | tfFillOrKill offer that doesn't cross. + // This would have succeeded with a regular tfSell, but the + // fillOrKill prevents the transaction from crossing since not + // all of the offer is consumed because AMM generated offer, + // which matches alice's offer quality is ~ 10XRP/0.01996e3BTC. + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 10'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammBob(env, bob, XRP(5000), BTC(10'000'000)); + + env(offer(alice, BTC(1'000'000), XRP(501), tfSell | tfFillOrKill), ter(tecKILLED)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + } + + void + testTransferRateOffer(FeatureBitset features) + { + testcase("Transfer Rate Offer"); + + using namespace jtx; + + // AMM XRP/BTC. Alice places BTC/XRP offer. + { + Env env(*this, features); + env.fund(XRP(30'000), gw, bob, carol); + env.fund(XRP(40'000), alice); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 30'000'000, + .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(10'100'000))); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000)); + env.close(); + + env(offer(carol, BTC(100'000), XRP(100))); + env.close(); + + // AMM doesn't pay the transfer fee + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), BTC(10'000'000), ammAlice.tokens())); + env.require(balance(carol, BTC(30'100'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + { + Env env(*this, features); + env.fund(XRP(30'000), gw, bob, carol); + env.fund(XRP(40'100), alice); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 30'000'000, + .flags = MPTDEXFlags}); + env(pay(gw, alice, BTC(10'000'000))); + + AMM const ammAlice(env, alice, XRP(10'100), BTC(10'000'000)); + env.close(); + + env(offer(carol, XRP(100), BTC(100'000))); + env.close(); + + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'100'000), ammAlice.tokens())); + // Carol pays 25% transfer fee + env.require(balance(carol, BTC(29'875'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + { + // Bridged crossing. + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 15'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 15'000'000, + .flags = MPTDEXFlags}); + + // The scenario: + // o BTC/XRP AMM is created. + // o ETH/XRP Offer is created. + // o carol has ETH but wants BTC. + // Note that Carol's offer must come last. If Carol's offer is + // placed before AMM is created, then autobridging will not occur. + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000)); + env(offer(bob, ETH(100'000), XRP(100))); + env.close(); + + // Carol makes an offer that consumes AMM liquidity and + // fully consumes Bob's offer. + env(offer(carol, BTC(100'000), ETH(100'000))); + env.close(); + + // AMM doesn't pay the transfer fee + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'100), BTC(10'000'000), ammAlice.tokens())); + env.require(balance(carol, BTC(15'100'000))); + // Carol pays 25% transfer fee. + env.require(balance(carol, ETH(14'875'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + { + // Bridged crossing. The transfer fee is paid on the step not + // involving AMM as src/dst. + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 15'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 15'000'000, + .flags = MPTDEXFlags}); + + // The scenario: + // o BTC/XRP AMM is created. + // o ETH/XRP Offer is created. + // o carol has ETH but wants BTC. + // Note that Carol's offer must come last. If Carol's offer is + // placed before AMM is created, then autobridging will not occur. + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'050'000)); + env(offer(bob, ETH(100'000), XRP(100))); + env.close(); + + // Carol makes an offer that consumes AMM liquidity and + // partially consumes Bob's offer. + env(offer(carol, BTC(50'000), ETH(50'000))); + env.close(); + // This test verifies that the amount removed from an offer + // accounts for the transfer fee that is removed from the + // account but not from the remaining offer. + + // AMM doesn't pay the transfer fee + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'050), BTC(10'000'000), ammAlice.tokens())); + env.require(balance(carol, BTC(15'050'000))); + // Carol pays 25% transfer fee. + env.require(balance(carol, ETH(14'937'500))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, 1, {{Amounts{ETH(50'000), XRP(50)}}})); + } + } + + void + testSelfIssueOffer(FeatureBitset features) + { + // This test is not the same as corresponding testSelfIssueOffer() + // in the Offer_test. It simply tests AMM with self issue and + // offer crossing. + using namespace jtx; + + Env env{*this, features}; + + auto const f = env.current()->fees().base; + + env.fund(XRP(30'000) + f, alice, bob); + env.close(); + + MPTTester const BTC({.env = env, .issuer = bob, .holders = {alice}, .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, XRP(10'000), BTC(10'100)); + + env(offer(alice, BTC(100), XRP(100))); + env.close(); + + BEAST_EXPECT(ammBob.expectBalances(XRP(10'100), BTC(10'000), ammBob.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 0)); + env.require(balance(alice, BTC(100))); + } + + void + testDirectToDirectPath(FeatureBitset features) + { + // The offer crossing code expects that a DirectStep is always + // preceded by a BookStep. In one instance the default path + // was not matching that assumption. Here we recreate that case + // so we can prove the bug stays fixed. + testcase("Direct to Direct path"); + + using namespace jtx; + + Env env{*this, features}; + + auto const ann = Account("ann"); + auto const bob = Account("bob"); + auto const cam = Account("cam"); + auto const carol = Account("carol"); + + auto const fee = env.current()->fees().base; + env.fund(XRP(1'000), carol); + env.fund(reserve(env, 4) + (fee * 5), ann, bob, cam); + env.close(); + + MPTTester const A_BUX( + {.env = env, .issuer = ann, .holders = {bob, cam, carol}, .flags = MPTDEXFlags}); + + MPTTester const B_BUX( + {.env = env, .issuer = bob, .holders = {ann, cam, carol}, .flags = MPTDEXFlags}); + + env(pay(ann, cam, A_BUX(350'000'000'000'000))); + env(pay(bob, cam, B_BUX(350'000'000'000'000))); + env(pay(bob, carol, B_BUX(4'000'000'000'000'000))); + env(pay(ann, carol, A_BUX(4'000'000'000'000'000))); + + AMM const ammCarol(env, carol, A_BUX(3'000'000'000'000'000), B_BUX(3'300'000'000'000'000)); + + // cam puts an offer on the books that her upcoming offer could cross. + // But this offer should be deleted, not crossed, by her upcoming + // offer. + env(offer(cam, A_BUX(290'000'000'000'000), B_BUX(300'000'000'000'000), tfPassive)); + env.close(); + env.require(balance(cam, A_BUX(350'000'000'000'000))); + env.require(balance(cam, B_BUX(350'000'000'000'000))); + env.require(offers(cam, 1)); + + // This offer caused the assert. + env(offer(cam, B_BUX(300'000'000'000'000), A_BUX(300'000'000'000'000))); + + // AMM is consumed up to the first cam Offer quality + BEAST_EXPECT(ammCarol.expectBalances( + A_BUX(3'093'541'659'651'604), B_BUX(3'200'215'509'984'418), ammCarol.tokens())); + BEAST_EXPECT(expectOffers( + env, cam, 1, {{Amounts{B_BUX(200'215'509'984'418), A_BUX(200'215'509'984'419)}}})); + } + + void + testRequireAuth(FeatureBitset features) + { + testcase("RequireAuth"); + + using namespace jtx; + + Env env{*this, features}; + env.fund(XRP(400'000), gw, alice, bob); + + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .flags = tfMPTRequireAuth | MPTDEXFlags}); + + // Authorize bob and alice + BTC.authorize({.holder = alice}); + BTC.authorize({.holder = bob}); + + env(pay(gw, alice, BTC(1'000))); + env.close(); + + // Alice is able to create AMM since the GW has authorized her + AMM const ammAlice(env, alice, BTC(1'000), XRP(1'050)); + + env(pay(gw, bob, BTC(50))); + env.close(); + + env.require(balance(bob, BTC(50))); + + // Bob's offer should cross Alice's AMM + env(offer(bob, XRP(50), BTC(50))); + env.close(); + + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'050), XRP(1'000), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, bob, 0)); + env.require(balance(bob, BTC(0))); + } + + void + testMissingAuth(FeatureBitset features) + { + testcase("Missing Auth"); + + using namespace jtx; + + Env env{*this, features}; + + env.fund(XRP(400'000), gw, alice, bob); + env.close(); + + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .flags = tfMPTRequireAuth | MPTDEXFlags}); + + // Alice doesn't have the funds + { + AMM const ammAlice(env, alice, BTC(1'000), XRP(1'000), ter(tecNO_AUTH)); + } + + BTC.authorize({.holder = bob}); + env(pay(gw, bob, BTC(50))); + env.close(); + env.require(balance(bob, BTC(50))); + + // Alice should not be able to create AMM without authorization. + { + AMM const ammAlice(env, alice, BTC(1'000), XRP(1'000), ter(tecNO_AUTH)); + } + + // Finally, authorize alice. Now alice's AMM create should succeed. + BTC.authorize({.holder = alice}); + env(pay(gw, alice, BTC(1'000))); + env.close(); + + AMM const ammAlice(env, alice, BTC(1'000), XRP(1'050)); + + // Authorize AMM. + // BTC.authorize({.account = ammAlice.ammAccount()}); + // env.close(); + + // Now bob creates his offer again, which crosses with alice's AMM. + env(offer(bob, XRP(50), BTC(50))); + env.close(); + + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'050), XRP(1'000), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, bob, 0)); + env.require(balance(bob, BTC(0))); + } + + void + testOffers() + { + using namespace jtx; + FeatureBitset const all{testable_amendments()}; + testRmFundedOffer(all); + testFillModes(all); + testOfferCrossWithXRP(all); + testOfferCrossWithLimitOverride(all); + testCurrencyConversionEntire(all); + testCurrencyConversionInParts(all); + testCrossCurrencyStartXRP(all); + testCrossCurrencyEndXRP(all); + testCrossCurrencyBridged(all); + testOfferFeesConsumeFunds(all); + testOfferCreateThenCross(all); + testSellFlagExceedLimit(all); + testGatewayCrossCurrency(all); + testBridgedCross(all); + testSellWithFillOrKill(all); + testTransferRateOffer(all); + testSelfIssueOffer(all); + testSellFlagBasic(all); + testDirectToDirectPath(all); + testRequireAuth(all); + testMissingAuth(all); + } + + void + path_find_consume_all() + { + testcase("path find consume all"); + using namespace jtx; + + Env env = pathTestEnv(); + env.fund(XRP(100'000'260), alice); + env.fund(XRP(30'000), gw, bob, carol); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 100'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammCarol(env, carol, XRP(100), ETH(100'000'000'000'000)); + + STPathSet st; + STAmount sa; + STAmount da; + std::tie(st, sa, da) = + find_paths(env, alice, bob, bob["AUD"](-1), std::optional(XRP(100'000'000))); + BEAST_EXPECT(st.empty()); + std::tie(st, sa, da) = + find_paths(env, alice, bob, ETH(-1), std::optional(XRP(100'000'000))); + // Alice sends all requested 100,000,000XRP + BEAST_EXPECT(sa == XRP(100'000'000)); + // Bob gets ~99.99e12ETH. This is the amount Bob + // can get out of AMM for 100,000,000XRP. + BEAST_EXPECT(equal(da, ETH(99'999'900'000'100))); + } + + // carol holds ETH, sells ETH for XRP + // bob will hold ETH + // alice pays bob ETH using XRP + void + via_offers_via_gateway() + { + testcase("via gateway"); + using namespace jtx; + + Env env = pathTestEnv(); + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 10'000, + .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 10'000, + .flags = MPTDEXFlags}); + + env(pay(gw, carol, ETH(51))); + env.close(); + AMM const ammCarol(env, carol, XRP(40), ETH(51)); + env(pay(alice, bob, ETH(10)), sendmax(XRP(100)), paths(XRP)); + env.close(); + // AMM offer is 51.282052XRP/11ETH, 11ETH/1.1 = 10ETH to bob + BEAST_EXPECT(ammCarol.expectBalances(XRP(51), ETH(40), ammCarol.tokens())); + env.require(balance(bob, ETH(10))); + + auto const result = find_paths(env, alice, bob, BTC(25)); + BEAST_EXPECT(std::get<0>(result).empty()); + } + + void + receive_max() + { + testcase("Receive max"); + using namespace jtx; + auto const charlie = Account("charlie"); + { + // XRP -> MPT receive max + Env env = pathTestEnv(); + env.fund(XRP(30'000), alice, bob, charlie, gw); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, charlie}, + .pay = 11'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammCharlie(env, charlie, XRP(10), ETH(11'000'000'000'000)); + auto [st, sa, da] = find_paths(env, alice, bob, ETH(-1), XRP(1).value()); + BEAST_EXPECT(sa == XRP(1)); + BEAST_EXPECT(equal(da, ETH(1'000'000'000'000))); + if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) + { + auto const& pathElem = st[0][0]; + BEAST_EXPECT( + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && + pathElem.getMPTID() == ETH.issuanceID()); + } + } + { + // MPT -> XRP receive max + Env env = pathTestEnv(); + env.fund(XRP(30'000), alice, bob, charlie, gw); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, charlie}, + .pay = 11'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammCharlie(env, charlie, XRP(11), ETH(10'000'000'000'000)); + env.close(); + auto [st, sa, da] = + find_paths(env, alice, bob, drops(-1), ETH(1'000'000'000'000).value()); + BEAST_EXPECT(sa == ETH(1'000'000'000'000)); + BEAST_EXPECT(equal(da, XRP(1))); + if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) + { + auto const& pathElem = st[0][0]; + BEAST_EXPECT( + pathElem.isOffer() && pathElem.getIssuerID() == xrpAccount() && + pathElem.getCurrency() == xrpCurrency()); + } + } + } + + void + path_find_01() + { + testcase("Path Find: XRP -> XRP and XRP -> MPT"); + using namespace jtx; + Env env = pathTestEnv(); + Account A1{"A1"}; + Account A2{"A2"}; + Account A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account G3{"G3"}; + Account M1{"M1"}; + + env.fund(XRP(100'000), A1); + env.fund(XRP(10'000), A2); + env.fund(XRP(1'000), A3, G1, G2, G3); + env.fund(XRP(20'000), M1); + env.close(); + + MPTTester const XYZ_G1( + {.env = env, .issuer = G1, .holders = {A1, M1, A2}, .flags = MPTDEXFlags}); + + MPTTester const XYZ_G2( + {.env = env, .issuer = G2, .holders = {A2, M1, A1}, .flags = MPTDEXFlags}); + + MPTTester const ABC_G3( + {.env = env, .issuer = G3, .holders = {A1, A2, M1, A3}, .flags = MPTDEXFlags}); + + MPTTester const ABC_A2( + {.env = env, .issuer = A2, .holders = {G3, A1}, .flags = MPTDEXFlags}); + + env(pay(G1, A1, XYZ_G1(3'500'000'000))); + env(pay(G3, A1, ABC_G3(1'200'000'000))); + env(pay(G1, M1, XYZ_G1(25'000'000'000))); + env(pay(G2, M1, XYZ_G2(25'000'000'000))); + env(pay(G3, M1, ABC_G3(25'000'000'000))); + env(pay(A2, G3, ABC_A2(101'000'000))); + env.close(); + + AMM const ammM1_XYZ_G1_XYZ_G2(env, M1, XYZ_G1(1'000'000'000), XYZ_G2(1'000'000'000)); + AMM const ammM1_XRP_ABC_G3(env, M1, XRP(10'000), ABC_G3(1'000'000'000)); + AMM const ammG3_ABC_G3_ABC_A2(env, G3, ABC_G3(100'000'000), ABC_A2(101'000'000)); + env.close(); + + STPathSet st; + STAmount sa, da; + + { + auto const& send_amt = XRP(10); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(st.empty()); + } + + { + // no path should exist for this since dest account + // does not exist. + auto const& send_amt = XRP(200); + std::tie(st, sa, da) = + find_paths(env, A1, Account{"A0"}, send_amt, std::nullopt, xrpCurrency()); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(st.empty()); + } + + { + auto const& send_amt = ABC_G3(10'000'000); + std::tie(st, sa, da) = find_paths(env, A2, G3, send_amt, std::nullopt, xrpCurrency()); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(equal(sa, XRPAmount{101'010'102})); + BEAST_EXPECT(same(st, stpath(IPE(MPT(ABC_G3))))); + } + + { + auto const& send_amt = ABC_A2(1'000'000); + std::tie(st, sa, da) = find_paths(env, A1, A2, send_amt, std::nullopt, xrpCurrency()); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(equal(sa, XRPAmount{10'010'011})); + BEAST_EXPECT(same(st, stpath(IPE(MPT(ABC_G3)), IPE(MPT(ABC_A2))))); + } + } + + void + path_find_02() + { + testcase("Path Find: non-XRP -> XRP"); + using namespace jtx; + Env env = pathTestEnv(); + Account A1{"A1"}; + Account A2{"A2"}; + Account const G3{"G3"}; + Account M1{"M1"}; + + env.fund(XRP(1'000), A1, A2, G3); + env.fund(XRP(11'000), M1); + env.close(); + + MPTTester const ETH( + {.env = env, + .issuer = G3, + .holders = {A1, A2, M1}, + .pay = 1'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammM1(env, M1, ETH(1'000'000'000), XRP(10'010)); + + STPathSet st; + STAmount sa, da; + + auto const& send_amt = XRP(10); + + std::tie(st, sa, da) = + find_paths_by_element(env, A1, A2, send_amt, std::nullopt, IPE(MPT(ETH))); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(equal(sa, ETH(1'000'000))); + BEAST_EXPECT(same(st, stpath(IPE(xrpIssue())))); + } + + void + path_find_06() + { + testcase("Path Find: non-XRP -> non-XRP, same issuanceID"); + using namespace jtx; + { + Env env = pathTestEnv(); + Account A1{"A1"}; + Account A2{"A2"}; + Account const A3{"A3"}; + Account const G1{"G1"}; + Account const G2{"G2"}; + Account M1{"M1"}; + + env.fund(XRP(11'000), M1); + env.fund(XRP(1'000), A1, A2, A3, G1, G2); + env.close(); + + MPTTester const HKD_G1( + {.env = env, + .issuer = G1, + .holders = {A1, M1}, + .pay = 5'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const HKD_G2( + {.env = env, + .issuer = G2, + .holders = {A2, M1}, + .pay = 5'000'000'000, + .flags = MPTDEXFlags}); + + AMM const ammM1(env, M1, HKD_G1(1'000'000'000), HKD_G2(1'010'000'000)); + + auto const& send_amt = HKD_G2(10'000'000); + STPathSet st; + STAmount sa, da; + std::tie(st, sa, da) = jtx::find_paths( + env, + G1, + A2, + send_amt, + std::nullopt, + HKD_G1.issuanceID(), + std::nullopt, + std::nullopt); + BEAST_EXPECT(equal(da, send_amt)); + BEAST_EXPECT(equal(sa, HKD_G1(10'000'000))); + BEAST_EXPECT(same(st, stpath(IPE(MPT(HKD_G2))))); + } + } + + void + testFalseDry(FeatureBitset features) + { + testcase("falseDryChanges"); + + using namespace jtx; + + Env env(*this, features); + env.memoize(bob); + + env.fund(XRP(10'000), alice, gw); + fund(env, gw, {carol}, XRP(10'000), {}, Fund::Acct); + auto const AMMXRPPool = env.current()->fees().increment * 2; + env.fund(reserve(env, 5) + ammCrtFee(env) + AMMXRPPool, bob); + env.close(); + + MPTTester const ETH( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + env(pay(gw, alice, ETH(50'000))); + env(pay(gw, bob, BTC(150'000))); + + // Bob has _just_ slightly less than 50 xrp available + // If his owner count changes, he will have more liquidity. + // This is one error case to test (when Flow is used). + // Computing the incoming xrp to the XRP/BTC offer will require two + // recursive calls to the ETH/XRP offer. The second call will return + // tecPATH_DRY, but the entire path should not be marked as dry. + // This is the second error case to test (when flowV1 is used). + env(offer(bob, ETH(50'000), XRP(50))); + AMM const ammBob(env, bob, AMMXRPPool, BTC(150'000)); + + env(pay(alice, carol, BTC(1'000'000'000)), + path(~XRP, ~MPT(BTC)), + sendmax(ETH(500'000)), + txflags(tfNoRippleDirect | tfPartialPayment)); + + auto const carolBTC = env.balance(carol, MPT(BTC)); + BEAST_EXPECT(carolBTC > BTC(0) && carolBTC < BTC(50'000)); + } + + void + testBookStep(FeatureBitset features) + { + testcase("Book Step"); + + using namespace jtx; + + // simple MPT/IOU mix offer + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + env(pay(gw, alice, BTC(500000))); + env(pay(gw, bob, BTC(500000))); + env(pay(gw, carol, BTC(500000))); + env(pay(gw, alice, ETH(500000))); + env(pay(gw, bob, ETH(500000))); + env(pay(gw, carol, ETH(500000))); + env.close(); + AMM const ammBob(env, bob, BTC(100'000), ETH(150'000)); + + env(pay(alice, carol, ETH(50'000)), path(~ETH), sendmax(BTC(50'000))); + + env.require(balance(alice, BTC(450'000))); + env.require(balance(bob, BTC(400'000))); + env.require(balance(bob, ETH(350'000))); + env.require(balance(carol, ETH(550'000))); + BEAST_EXPECT(ammBob.expectBalances(BTC(150'000), ETH(100'000), ammBob.tokens())); + }; + testHelper2TokensMix(test); + } + + { + // simple MPT/XRP XRP/MPT offer + Env env(*this, features); + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 100'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 150'000, + .flags = MPTDEXFlags}); + + AMM const ammBobBTC_XRP(env, bob, BTC(100'000), XRP(150)); + AMM const ammBobXRP_ETH(env, bob, XRP(100), ETH(150'000)); + + env(pay(alice, carol, ETH(50'000)), path(~XRP, ~MPT(ETH)), sendmax(BTC(50'000))); + + env.require(balance(alice, BTC(50'000))); + env.require(balance(bob, BTC(0))); + env.require(balance(bob, ETH(0))); + env.require(balance(carol, ETH(200'000))); + BEAST_EXPECT( + ammBobBTC_XRP.expectBalances(BTC(150'000), XRP(100), ammBobBTC_XRP.tokens())); + BEAST_EXPECT( + ammBobXRP_ETH.expectBalances(XRP(150), ETH(100'000), ammBobXRP_ETH.tokens())); + } + { + // simple XRP -> MPT through offer and sendmax + Env env(*this, features); + XRPAmount const baseFee{env.current()->fees().base}; + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 150'000, + .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, XRP(100), ETH(150'000)); + + env(pay(alice, carol, ETH(50'000)), path(~MPT(ETH)), sendmax(XRP(50))); + BEAST_EXPECT(expectLedgerEntryRoot(env, alice, XRP(10'000) - XRP(50) - 2 * baseFee)); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(10'000) - XRP(100) - ammCrtFee(env) - baseFee)); + env.require(balance(bob, ETH(0))); + env.require(balance(carol, ETH(200'000))); + BEAST_EXPECT(ammBob.expectBalances(XRP(150), ETH(100'000), ammBob.tokens())); + } + { + // simple MPT -> XRP through offer and sendmax + Env env(*this, features); + XRPAmount const baseFee{env.current()->fees().base}; + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 100'000, + .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, ETH(100'000), XRP(150)); + + env(pay(alice, carol, XRP(50)), path(~XRP), sendmax(ETH(50'000))); + + env.require(balance(alice, ETH(50'000))); + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(10'000) - XRP(150) - ammCrtFee(env) - baseFee)); + env.require(balance(bob, ETH(0))); + BEAST_EXPECT(expectLedgerEntryRoot(env, carol, XRP(10'000 + 50) - baseFee)); + BEAST_EXPECT(ammBob.expectBalances(ETH(150'000), XRP(100), ammBob.tokens())); + } + + // test unfunded offers are removed when payment succeeds + { + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + auto const BTC = issue1( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1000'000000}); + auto const ETH = issue2( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1000'000000}); + auto const GBP = issue3( + {.env = env, + .token = "GBP", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1000'000000}); + + env(pay(gw, alice, BTC(60'000))); + env(pay(gw, bob, ETH(200'000))); + env(pay(gw, bob, GBP(150'000))); + env(offer(bob, BTC(50'000), ETH(50'000))); + env(offer(bob, BTC(40'000), GBP(50'000))); + env.close(); + AMM const ammBob(env, bob, GBP(100'000), ETH(150'000)); + + // unfund offer + env(pay(bob, gw, GBP(50'000))); + BEAST_EXPECT(isOffer(env, bob, BTC(50'000), ETH(50'000))); + BEAST_EXPECT(isOffer(env, bob, BTC(40'000), GBP(50'000))); + env(pay(alice, carol, ETH(50'000)), + path(~ETH), + path(~GBP, ~ETH), + sendmax(BTC(60'000))); + env.require(balance(alice, BTC(10'000))); + env.require(balance(bob, BTC(50'000))); + env.require(balance(bob, ETH(0))); + env.require(balance(bob, GBP(0))); + env.require(balance(carol, ETH(50'000))); + // used in the payment + BEAST_EXPECT(!isOffer(env, bob, BTC(50'000), ETH(50'000))); + // found unfunded + BEAST_EXPECT(!isOffer(env, bob, BTC(40'000), GBP(50'000))); + // unchanged + BEAST_EXPECT(ammBob.expectBalances(GBP(100'000), ETH(150'000), ammBob.tokens())); + }; + testHelper3TokensMix(test); + } + + { + // test unfunded offers are removed when the payment fails. + // bob makes two offers: a funded 50'000'000 ETH for 50'000'000 BTC + // and an unfunded 50'000'000 GBP for 60'000'000 BTC. alice pays + // carol 61'000'000 ETH with 61'000'000 BTC. alice only has + // 60'000'000 BTC, so the payment will fail. The payment uses two + // paths: one through bob's funded offer and one through his + // unfunded offer. When the payment fails `flow` should return the + // unfunded offer. This test is intentionally similar to the one + // that removes unfunded offers when the payment succeeds. + Env env(*this, features); + + env.fund(XRP(10'000), bob, carol, gw); + env.close(); + // Sets rippling on, this is different from + // the original test + fund(env, gw, {alice}, XRP(10'000), {}, Fund::Acct); + + MPTTester BTC( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + MPTTester ETH( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + MPTTester GBP( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + env(pay(gw, alice, BTC(60'000'000))); + env(pay(gw, bob, BTC(100'000'000))); + env(pay(gw, bob, ETH(100'000'000))); + env(pay(gw, bob, GBP(50'000'000))); + env(pay(gw, carol, GBP(1'000'000))); + env.close(); + + // This is multiplath, which generates limited # of offers + AMM const ammBobBTC_ETH(env, bob, BTC(50'000'000), ETH(50'000'000)); + env(offer(bob, BTC(60'000'000), GBP(50'000'000))); + env(offer(carol, BTC(1'000'000'000), GBP(1'000'000))); + env(offer(bob, GBP(50'000'000), ETH(50'000'000))); + + // unfund offer + env(pay(bob, gw, GBP(50'000'000))); + BEAST_EXPECT(ammBobBTC_ETH.expectBalances( + BTC(50'000'000), ETH(50'000'000), ammBobBTC_ETH.tokens())); + BEAST_EXPECT(isOffer(env, bob, BTC(60'000'000), GBP(50'000'000))); + BEAST_EXPECT(isOffer(env, carol, BTC(1'000'000'000), GBP(1'000'000))); + BEAST_EXPECT(isOffer(env, bob, GBP(50'000'000), ETH(50'000'000))); + + auto flowJournal = env.app().getLogs().journal("Flow"); + auto const flowResult = [&] { + STAmount const deliver(ETH(51'000'000)); + STAmount smax(BTC(61'000'000)); + PaymentSandbox sb(env.current().get(), tapNONE); + STPathSet paths; + auto IPE = [](MPTTester const& iss) { + return STPathElement( + STPathElement::typeMPT | STPathElement::typeIssuer, + xrpAccount(), + PathAsset{iss.issuanceID()}, + iss.issuer()); + }; + { + // BTC -> ETH + STPath const p1({IPE(ETH)}); + paths.push_back(p1); + // BTC -> GBP -> ETH + STPath const p2({IPE(GBP), IPE(ETH)}); + paths.push_back(p2); + } + + return flow( + sb, + deliver, + alice, + carol, + paths, + false, + false, + true, + OfferCrossing::no, + std::nullopt, + smax, + std::nullopt, + flowJournal); + }(); + + BEAST_EXPECT(flowResult.removableOffers.size() == 1); + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { + if (flowResult.removableOffers.empty()) + return false; + Sandbox sb(&view, tapNONE); + for (auto const& o : flowResult.removableOffers) + { + if (auto ok = sb.peek(keylet::offer(o))) + { + offerDelete(sb, ok, flowJournal); + } + } + sb.apply(view); + return true; + }); + + // used in payment, but since payment failed should be untouched + BEAST_EXPECT(ammBobBTC_ETH.expectBalances( + BTC(50'000'000), ETH(50'000'000), ammBobBTC_ETH.tokens())); + BEAST_EXPECT(isOffer(env, carol, BTC(1'000'000'000), GBP(1'000'000))); + // found unfunded + BEAST_EXPECT(!isOffer(env, bob, BTC(60'000'000), GBP(50'000'000))); + } + { + // Do not produce more in the forward pass than the reverse pass + // This test uses a path that whose reverse pass will compute a + // 500 ETH input required for a 1'000 BTC output. It sets a sendmax + // of 400 ETH, so the payment engine will need to do a forward + // pass. Without limits, the 400 ETH would produce 1'000 BTC in + // the forward pass. This test checks that the payment produces + // 1'000 BTC, as expected. + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000'000}); + + env(pay(gw, alice, ETH(1'000'000))); + env(pay(gw, bob, BTC(1'000'000))); + env(pay(gw, bob, ETH(1'000'000))); + env.close(); + + AMM const ammBob(env, bob, ETH(8'000), XRPAmount{21}); + env(offer(bob, drops(1), BTC(1'000'000)), txflags(tfPassive)); + + env(pay(alice, carol, BTC(1'000)), + path(~XRP, ~BTC), + sendmax(ETH(400)), + txflags(tfNoRippleDirect | tfPartialPayment)); + + env.require(balance(carol, BTC(1'000))); + BEAST_EXPECT(ammBob.expectBalances(ETH(8400), XRPAmount{20}, ammBob.tokens())); + }; + testHelper2TokensMix(test); + } + } + + void + testTransferRateNoOwnerFee(FeatureBitset features) + { + testcase("No Owner Fee"); + using namespace jtx; + + { + // payment via AMM + Env env(*this, features); + env.fund(XRP(1'000), gw, alice, bob, carol); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm(env, bob, GBP(1'000'000'000'000'000), BTC(1'000'000'000'000'000)); + + env(pay(alice, carol, BTC(100'000'000'000'000)), + path(~MPT(BTC)), + sendmax(GBP(150'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment)); + env.close(); + + // alice buys 107.1428e12BTC with 120e12GBP and pays 25% tr fee on + // 120e12GBP 1,000e12 - 120e12*1.25 = 850e12GBP + env.require(balance(alice, GBP(850'000'000'000'000))); + + BEAST_EXPECT(amm.expectBalances( + GBP(1'120'000'000'000'000), BTC(892'857'142'857'143), amm.tokens())); + + // 25% of 85.7142e12BTC is paid in tr fee + // 85.7142e12*1.25 = 107.1428e12BTC + env.require(balance(carol, BTC(1'085'714'285'714'285))); + } + { + // Payment via offer and AMM + Env env(*this, features); + Account const ed("ed"); + + env.fund(XRP(1'000), gw, alice, bob, carol, ed); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + env(offer(ed, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)), + txflags(tfPassive)); + env.close(); + + AMM const amm(env, bob, ETH(1'000'000'000'000'000), BTC(1'000'000'000'000'000)); + + env(pay(alice, carol, BTC(100'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(150'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment)); + env.close(); + + // alice buys 120e12ETH with 120e12GBP via the offer + // and pays 25% tr fee on 120e12GBP + // 1,000e12 - 120e12*1.25 = 850e12GBP + env.require(balance(alice, GBP(850'000'000'000'000))); + // consumed offer is 120e12GBP/120e12ETH + // ed doesn't pay tr fee + env.require(balance(ed, ETH(880'000'000'000'000))); + env.require(balance(ed, GBP(1'120'000'000'000'000))); + BEAST_EXPECT(expectOffers( + env, ed, 1, {Amounts{GBP(880'000'000'000'000), ETH(880'000'000'000'000)}})); + // 25% on 96e12ETH is paid in tr fee 96e12*1.25 = 120e12ETH + // 96e12ETH is swapped in for 87.5912e12BTC + BEAST_EXPECT(amm.expectBalances( + ETH(1'096'000'000'000'000), BTC(912'408'759'124'088), amm.tokens())); + // 25% on 70.0729e12BTC is paid in tr fee 70.0729e12*1.25 + // = 87.5912e12BTC + env.require(balance(carol, BTC(1'070'072'992'700'729))); + } + { + // Payment via AMM, AMM + Env env(*this, features); + Account const ed("ed"); + + env.fund(XRP(1'000), gw, alice, bob, carol, ed); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm1(env, bob, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)); + AMM const amm2(env, ed, ETH(1'000'000'000'000'000), BTC(1'000'000'000'000'000)); + + env(pay(alice, carol, BTC(100'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(150'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment)); + env.close(); + + env.require(balance(alice, GBP(850'000'000'000'000))); + + // alice buys 107.1428e12ETH with 120e12GBP and pays 25% tr fee on + // 120e12GBP 1,000e12 - 120e12*1.25 = 850e12GBP 120e12GBP is swapped + // in for 107.1428e12ETH + BEAST_EXPECT(amm1.expectBalances( + GBP(1'120'000'000'000'000), ETH(892'857'142'857'143), amm1.tokens())); + // 25% on 85.7142e12ETH is paid in tr fee 85.7142e12*1.25 = + // 107.1428e12ETH 85.7142e12ETH is swapped in for 78.9473e12BTC + BEAST_EXPECT(amm2.expectBalances( + ETH(1'085'714'285'714'285), BTC(921'052'631'578'948), amm2.tokens())); + + // 25% on 63.1578e12BTC is paid in tr fee 63.1578e12*1.25 + // = 78.9473e12BTC + env.require(balance(carol, BTC(1'063'157'894'736'841))); + } + { + // AMM offer crossing + Env env(*this, features); + + env.fund(XRP(1'000), gw, alice, bob); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 25'000, + .pay = 1'100'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 25'000, + .pay = 1'100'000, + .flags = MPTDEXFlags}); + + AMM const amm(env, bob, BTC(1'000'000), ETH(1'100'000)); + env(offer(alice, ETH(100'000), BTC(100'000))); + env.close(); + + // 100e3BTC is swapped in for 100e3ETH + BEAST_EXPECT(amm.expectBalances(BTC(1'100'000), ETH(1'000'000), amm.tokens())); + // alice pays 25% tr fee on 100e3BTC 1100e3-100e3*1.25 = 975e3BTC + env.require(balance(alice, BTC(975'000))); + env.require(balance(alice, ETH(1'200'000))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + { + // Payment via AMM with limit quality + Env env(*this, features); + + env.fund(XRP(1'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'000'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm(env, bob, GBP(1'000'000'000'000'000), BTC(1'000'000'000'000'000)); + + // requested quality limit is 100e12BTC/178.58e12GBP = 0.55997 + // trade quality is 100e12BTC/178.5714 = 0.55999e12 + env(pay(alice, carol, BTC(100'000'000'000'000)), + path(~MPT(BTC)), + sendmax(GBP(178'580'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // alice buys 125e12BTC with 142.8571e12GBP and pays 25% tr fee + // on 142.8571e12GBP + // 1,000e12 - 142.8571e12*1.25 = 821.4285e12GBP + env.require(balance(alice, GBP(821'428'571'428'571))); + // 142.8571e12GBP is swapped in for 125e12BTC + BEAST_EXPECT(amm.expectBalances( + GBP(1'142'857'142'857'143), BTC(875'000'000'000'000), amm.tokens())); + // 25% on 100e12BTC is paid in tr fee + // 100e12*1.25 = 125e12BTC + env.require(balance(carol, BTC(1'100'000'000'000'000))); + } + { + // Payment via AMM with limit quality, deliver less + // than requested + Env env(*this, features); + + env.fund(XRP(1'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'200'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'200'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm(env, bob, GBP(1'000'000'000'000'000), BTC(1'200'000'000'000'000)); + + // requested quality limit is 90e12BTC/120e12GBP = 0.75 + // trade quality is 22.5e12BTC/30e12GBP = 0.75 + env(pay(alice, carol, BTC(90'000'000'000'000)), + path(~MPT(BTC)), + sendmax(GBP(120'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // alice buys 28.125e12BTC with 24e12GBP and pays 25% tr fee + // on 24e12GBP + // 1,200e12 - 24e12*1.25 =~ 1,170e12GBP + env.require(balance(alice, GBP(1'170'000'000'000'000))); + // 24e12GBP is swapped in for 28.125e12BTC + BEAST_EXPECT(amm.expectBalances( + GBP(1'024'000'000'000'000), BTC(1'171'875'000'000'000), amm.tokens())); + + // 25% on 22.5e12BTC is paid in tr fee + // 22.5*1.25 = 28.125e12BTC + env.require(balance(carol, BTC(1'222'500'000'000'000))); + } + { + // Payment via offer and AMM with limit quality, deliver less + // than requested + Env env(*this, features); + Account const ed("ed"); + + env.fund(XRP(1'000), gw, alice, bob, carol, ed); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + env(offer(ed, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)), + txflags(tfPassive)); + env.close(); + + AMM const amm(env, bob, ETH(1'000'000'000'000'000), BTC(1'400'000'000'000'000)); + + // requested quality limit is 95e12BTC/140e12GBP = 0.6785 + // trade quality is 59.7321e12BTC/88.0262e12GBP = 0.6785 + env(pay(alice, carol, BTC(95'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(140'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // alice buys 70.4210e12ETH with 70.4210e12GBP via the offer + // and pays 25% tr fee on 70.4210e12GBP + // 1,400e12 - 70.4210e12*1.25 = 1400e12 - 88.0262e12 = + // 1311.9736e12GBP + env.require(balance(alice, GBP(1'311'973'684'210'525))); + // ed doesn't pay tr fee, the balances reflect consumed offer + // 70.4210e12GBP/70.4210e12ETH + env.require(balance(ed, ETH(1'329'578'947'368'420))); + env.require(balance(ed, GBP(1'470'421'052'631'580))); + BEAST_EXPECT(expectOffers( + env, ed, 1, {Amounts{GBP(929'578'947'368'420), ETH(929'578'947'368'420)}})); + // 25% on 56.3368e12ETH is paid in tr fee 56.3368e12*1.25 + // = 70.4210e12ETH 56.3368e12ETH is swapped in for 74.6651e12BTC + BEAST_EXPECT(amm.expectBalances( + ETH(1'056'336'842'105'264), BTC(1'325'334'821'428'571), amm.tokens())); + + // 25% on 59.7321e12BTC is paid in tr fee 59.7321e12*1.25 + // = 74.6651e12BTC + env.require(balance(carol, BTC(1'459'732'142'857'143))); + } + { + // Payment via AMM and offer with limit quality, deliver less + // than requested + Env env(*this, features); + Account const ed("ed"); + + env.fund(XRP(1'000), gw, alice, bob, carol, ed); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm(env, bob, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)); + + env(offer(ed, ETH(1'000'000'000'000'000), BTC(1'400'000'000'000'000)), + txflags(tfPassive)); + env.close(); + + // requested quality limit is 95e12BTC/140e12GBP = 0.6785 + // trade quality is 47.7857e12BTC/70.4210e12GBP = 0.6785 + env(pay(alice, carol, BTC(95'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(140'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // alice buys 53.3322e12ETH with 56.3368e12GBP via the amm + // and pays 25% tr fee on 56.3368e12GBP + // 1,400e12 - 56.3368e12*1.25 = 1400e12 - 70.4210e12 = + // 1329.5789e12GBP + env.require(balance(alice, GBP(1'329'578'947'368'420))); + //// 25% on 56.3368e12ETH is paid in tr fee 56.3368e12*1.25 + ///= 70.4210e12ETH + // 56.3368e12GBP is swapped in for 53.3322e12ETH + BEAST_EXPECT(amm.expectBalances( + GBP(1'056'336'842'105'264), ETH(946'667'729'591'836), amm.tokens())); + + // 25% on 42.6658e12ETH is paid in tr fee 42.6658e12*1.25 + // = 53.3322e12ETH 42.6658e12ETH/59.7321e12BTC + env.require(balance(ed, BTC(1'340'267'857'142'857))); + env.require(balance(ed, ETH(1'442'665'816'326'531))); + BEAST_EXPECT(expectOffers( + env, ed, 1, {Amounts{ETH(957'334'183'673'469), BTC(1'340'267'857'142'857)}})); + // 25% on 47.7857e12BTC is paid in tr fee 47.7857e12*1.25 + // = 59.7321e12BTC + env.require(balance(carol, BTC(1'447'785714285714))); + } + { + // Payment via AMM, AMM with limit quality, deliver less + // than requested + Env env(*this, features); + Account const ed("ed"); + + env.fund(XRP(1'000), gw, alice, bob, carol, ed); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm1(env, bob, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)); + AMM const amm2(env, ed, ETH(1'000'000'000'000'000), BTC(1'400'000'000'000'000)); + + // requested quality limit is 90e12BTC/145e12GBP = 0.6206 + // trade quality is 66.7432e12BTC/107.5308e12GBP = 0.6206 + env(pay(alice, carol, BTC(90'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(145'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // alice buys 53.3322e12ETH with 107.5308e12GBP + // 25% on 86.0246e12GBP is paid in tr fee + // 1,400e12 - 86.0246e12*1.25 = 1400e12 - 107.5308e12 = + // 1229.4691e12GBP + env.require(balance(alice, GBP(1'292'469'135'802'465))); + // 86.0246e12GBP is swapped in for 79.2106e12ETH + BEAST_EXPECT(amm1.expectBalances( + GBP(1'086'024'691'358'028), ETH(920'789'377'955'618), amm1.tokens())); + // 25% on 63.3684e12ETH is paid in tr fee 63.3684e12*1.25 + // = 79.2106e12ETH 63.3684e12ETH is swapped in for 83.4291e12BTC + BEAST_EXPECT(amm2.expectBalances( + ETH(1'063'368'497'635'505), BTC(1'316'570'881'226'053), amm2.tokens())); + + // 25% on 66.7432e12BTC is paid in tr fee 66.7432e12*1.25 + // = 83.4291e12BTC + env.require(balance(carol, BTC(1'466'743'295'019'157))); + } + { + // Payment by the issuer via AMM, AMM with limit quality, + // deliver less than requested + Env env(*this, features); + + env.fund(XRP(1'000), gw, alice, bob, carol); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 1'400'000'000'000'000, + .flags = MPTDEXFlags}); + + AMM const amm1(env, alice, GBP(1'000'000'000'000'000), ETH(1'000'000'000'000'000)); + AMM const amm2(env, bob, ETH(1'000'000'000'000'000), BTC(1'400'000'000'000'000)); + + // requested quality limit is 90e12BTC/120e12GBP = 0.75 + // trade quality is 81.1111e12BTC/108.1481e12GBP = 0.75 + env(pay(gw, carol, BTC(90'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(GBP(120'000'000'000'000)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + + // 108.1481e12GBP is swapped in for 97.5935e12ETH + BEAST_EXPECT(amm1.expectBalances( + GBP(1'108'148'148'148'150), ETH(902'406'417'112'298), amm1.tokens())); + // 25% on 78.0748e12ETH is paid in tr fee 78.0748e12*1.25 + // = 97.5935e12ETH 78.0748e12ETH is swapped in for 101.3888e12BTC + BEAST_EXPECT(amm2.expectBalances( + ETH(1'078'074'866'310'161), BTC(1'298'611'111'111'111), amm2.tokens())); + + // 25% on 81.1111e12BTC is paid in tr fee 81.1111e12*1.25 = + // 101.3888e12BTC + env.require(balance(carol, BTC(1'481'111'111'111'111))); + } + } + + void + testLimitQuality() + { + // Single path with amm, offer, and limit quality. The quality limit + // is such that the first offer should be taken but the second + // should not. The total amount delivered should be the sum of the + // two offers and sendMax should be more than the first offer. + testcase("limitQuality"); + using namespace jtx; + + { + Env env(*this); + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 2'000'000, + .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, XRP(1'000), ETH(1'050'000)); + env(offer(bob, XRP(100), ETH(50'000))); + + env(pay(alice, carol, ETH(100'000)), + path(~MPT(ETH)), + sendmax(XRP(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + + BEAST_EXPECT(ammBob.expectBalances(XRP(1'050), ETH(1'000'000), ammBob.tokens())); + env.require(balance(carol, ETH(2'050'000))); + BEAST_EXPECT(expectOffers(env, bob, 1, {{{XRP(100), ETH(50'000)}}})); + } + } + + void + testXRPPathLoop() + { + testcase("Circular XRP"); + + using namespace jtx; + + // Payment path starting with XRP + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, gw); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + + env(pay(gw, alice, BTC(200'000))); + env(pay(gw, bob, BTC(200'000))); + env(pay(gw, alice, ETH(200'000))); + env(pay(gw, bob, ETH(200'000))); + env.close(); + + AMM const ammAliceXRP_BTC(env, alice, XRP(100), BTC(101'000)); + AMM const ammAliceXRP_ETH(env, alice, XRP(100), ETH(101'000)); + env(pay(alice, bob, ETH(1'000)), + path(~BTC, ~XRP, ~ETH), + sendmax(XRP(1)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper2TokensMix(test); + } + + // Payment path ending with XRP + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, gw); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + + env(pay(gw, alice, BTC(200'000))); + env(pay(gw, bob, BTC(200'000))); + env(pay(gw, alice, ETH(200'000))); + env(pay(gw, bob, ETH(200'000))); + env.close(); + + AMM const ammAliceXRP_BTC(env, alice, XRP(100), BTC(100'000)); + AMM const ammAliceXRP_ETH(env, alice, XRP(100), ETH(100'000)); + // ETH -> //XRP -> //BTC ->XRP + env(pay(alice, bob, XRP(1)), + path(~XRP, ~BTC, ~XRP), + sendmax(ETH(1'000)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper2TokensMix(test); + } + + // Payment where loop is formed in the middle of the path, not + // on an endpoint + { + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this); + env.fund(XRP(10'000), gw, alice, bob); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + auto const JPY = issue2( + {.env = env, + .token = "JPY", + .issuer = gw, + .holders = {alice, bob}, + .limit = 2000'000}); + + env(pay(gw, alice, BTC(200'000))); + env(pay(gw, bob, BTC(200'000))); + env(pay(gw, alice, ETH(200'000))); + env(pay(gw, bob, ETH(200'000))); + env(pay(gw, alice, JPY(200'000))); + env(pay(gw, bob, JPY(200'000))); + env.close(); + + AMM const ammAliceXRP_BTC(env, alice, XRP(100), BTC(100'000)); + AMM const ammAliceXRP_ETH(env, alice, XRP(100), ETH(100'000)); + AMM const ammAliceXRP_JPY(env, alice, XRP(100), JPY(100'000)); + + env(pay(alice, bob, JPY(1'000)), + path(~XRP, ~ETH, ~XRP, ~JPY), + sendmax(BTC(1'000)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper3TokensMix(test); + } + } + + void + testStepLimit(FeatureBitset features) + { + testcase("Step Limit"); + + using namespace jtx; + { + Env env(*this, features); + auto const dan = Account("dan"); + auto const ed = Account("ed"); + + env.fund(XRP(100'000'000), gw, alice, bob, carol, dan, ed); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {bob, dan, ed}, .flags = MPTDEXFlags}); + + env(pay(gw, ed, BTC(11'000'000'000'000))); + env(pay(gw, bob, BTC(1'000'000'000'000))); + env(pay(gw, dan, BTC(1'000'000'000'000))); + + n_offers(env, 2'000, bob, XRP(1), BTC(1'000'000'000'000)); + n_offers(env, 1, dan, XRP(1), BTC(1'000'000'000'000)); + AMM const ammEd(env, ed, XRP(9), BTC(11'000'000'000'000)); + + // Alice offers to buy 1000 XRP for 1000e12 BTC. She takes Bob's + // first offer, removes 999 more as unfunded, then hits the step + // limit. + env(offer(alice, BTC(1'000'000'000'000'000), XRP(1'000))); + env.require(balance(alice, BTC(2'050'125'257'867))); + env.require(owners(alice, 2)); + env.require(balance(bob, BTC(0))); + env.require(owners(bob, 1'001)); + env.require(balance(dan, BTC(1'000'000'000'000))); + env.require(owners(dan, 2)); + + // Carol offers to buy 1000 XRP for 1000e12 BTC. She removes Bob's + // next 1000 offers as unfunded and hits the step limit. + env(offer(carol, BTC(1'000'000'000'000'000), XRP(1'000))); + env.require(balance(carol, MPT(BTC)(none))); + env.require(owners(carol, 1)); + env.require(balance(bob, BTC(0))); + env.require(owners(bob, 1)); + env.require(balance(dan, BTC(1'000'000'000'000))); + env.require(owners(dan, 2)); + } + + // MPT/IOU, similar to the case above + { + Env env(*this, features); + auto const dan = Account("dan"); + auto const ed = Account("ed"); + + env.fund(XRP(100'000), gw, alice, bob, carol, dan, ed); + env.close(); + + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .pay = 10000'000'000, + .flags = MPTDEXFlags}); + + env.trust(BTC(11'000'000'000'000), ed); + env(pay(gw, ed, BTC(11'000'000'000'000))); + env.trust(BTC(1'000'000'000'000), bob); + env(pay(gw, bob, BTC(1'000'000'000'000))); + env.trust(BTC(1'000'000'000'000), dan); + env(pay(gw, dan, BTC(1'000'000'000'000))); + env.close(); + + n_offers(env, 2'000, bob, USD(1000000), BTC(1'000'000'000'000)); + n_offers(env, 1, dan, USD(1000000), BTC(1'000'000'000'000)); + AMM const ammEd(env, ed, USD(9000000), BTC(11'000'000'000'000)); + env(offer(alice, BTC(1'000'000'000'000'000), USD(1'000000000))); + + env.require(balance(alice, STAmount{BTC, UINT64_C(2050125257867'587), -3})); + env.require(owners(alice, 3)); + env.require(balance(bob, BTC(0))); + env.require(owners(bob, 1'002)); + env.require(balance(dan, BTC(1000000000000))); + env.require(owners(dan, 3)); + } + + // IOU/MPT, similar to the case above + { + Env env(*this, features); + auto const dan = Account("dan"); + auto const ed = Account("ed"); + + env.fund(XRP(100'000), gw, alice, bob, carol, dan, ed); + env.close(); + + env.trust(USD(10000'000'000), alice); + env(pay(gw, alice, USD(10000'000'000))); + env.trust(USD(10000'000'000), bob); + env(pay(gw, bob, USD(10000'000'000))); + env.trust(USD(10000'000'000), carol); + env(pay(gw, carol, USD(10000'000'000))); + env.trust(USD(10000'000'000), dan); + env(pay(gw, dan, USD(10000'000'000))); + env.trust(USD(10000'000'000), ed); + env(pay(gw, ed, USD(10000'000'000))); + env.close(); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {bob, dan, ed}, .flags = MPTDEXFlags}); + + env(pay(gw, ed, BTC(11'000'000'000'000))); + env(pay(gw, bob, BTC(1'000'000'000'000))); + env(pay(gw, dan, BTC(1'000'000'000'000))); + env.close(); + + n_offers(env, 2'000, bob, USD(1000000), BTC(1'000'000'000'000)); + n_offers(env, 1, dan, USD(1000000), BTC(1'000'000'000'000)); + AMM const ammEd(env, ed, USD(9000000), BTC(11'000'000'000'000)); + env(offer(alice, BTC(1'000'000'000'000'000), USD(1'000000000))); + + env.require(balance(alice, BTC(2050125628933))); + env.require(owners(alice, 3)); + env.require(balance(bob, BTC(0))); + env.require(owners(bob, 1'002)); + env.require(balance(dan, BTC(1000000000000))); + env.require(owners(dan, 3)); + } + + // MPT/MPT, similar to the case above + { + Env env(*this, features); + auto const dan = Account("dan"); + auto const ed = Account("ed"); + + env.fund(XRP(100'000), gw, alice, bob, carol, dan, ed); + env.close(); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {bob, dan, ed}, .flags = MPTDEXFlags}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .pay = 10000'000'000, + .flags = MPTDEXFlags}); + + env(pay(gw, ed, BTC(11'000'000'000'000))); + env(pay(gw, bob, BTC(1'000'000'000'000))); + env(pay(gw, dan, BTC(1'000'000'000'000))); + env.close(); + + n_offers(env, 2'000, bob, USD(1000000), BTC(1'000'000'000'000)); + n_offers(env, 1, dan, USD(1000000), BTC(1'000'000'000'000)); + AMM const ammEd(env, ed, USD(9000000), BTC(11'000'000'000'000)); + env(offer(alice, BTC(1'000'000'000'000'000), USD(1'000000000))); + + env.require(balance(alice, BTC(2050125257867))); + env.require(owners(alice, 3)); + env.require(balance(bob, BTC(0))); + env.require(owners(bob, 1'002)); + env.require(balance(dan, BTC(1000000000000))); + env.require(owners(dan, 3)); + } + } + + void + test_convert_all_of_an_asset(FeatureBitset features) + { + testcase("Convert all of an asset using DeliverMin"); + + using namespace jtx; + + { + Env env(*this, features); + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + env(pay(alice, bob, BTC(10'000)), deliver_min(BTC(10'000)), ter(temBAD_AMOUNT)); + env(pay(alice, bob, BTC(10'000)), + deliver_min(BTC(-5'000)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); + env(pay(alice, bob, BTC(10'000)), + deliver_min(XRP(5)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); + env(pay(alice, bob, BTC(10'000)), + deliver_min(BTC(5'000)), + txflags(tfPartialPayment), + ter(tecPATH_DRY)); + env(pay(alice, bob, BTC(10'000)), + deliver_min(BTC(15'000)), + txflags(tfPartialPayment), + ter(temBAD_AMOUNT)); + env(pay(gw, carol, BTC(50'000))); + AMM const ammCarol(env, carol, XRP(10), BTC(15'000)); + env(pay(alice, bob, BTC(10'000)), + paths(XRP), + deliver_min(BTC(7'000)), + txflags(tfPartialPayment), + sendmax(XRP(5)), + ter(tecPATH_PARTIAL)); + env.require( + balance(alice, drops(10'000'000'000 - (3 * env.current()->fees().base.drops())))); + env.require(balance(bob, drops(10'000'000'000 - env.current()->fees().base.drops()))); + } + + { + Env env(*this, features); + fund(env, gw, {alice, bob}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob}, .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(1'100'000))); + AMM const ammBob(env, bob, XRP(1'000), BTC(1'100'000)); + env(pay(alice, alice, BTC(10'000'000)), + paths(XRP), + deliver_min(BTC(100'000)), + txflags(tfPartialPayment), + sendmax(XRP(100))); + env.require(balance(alice, BTC(100'000))); + } + + // IOU/MPT mix, similar to the above case + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 3000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, USD(10'000))); + env(pay(gw, bob, USD(10'000))); + env(pay(gw, bob, BTC(1'200))); + env.close(); + + AMM const ammBob(env, bob, USD(1'000), BTC(1'100)); + env(pay(alice, alice, BTC(10'000)), + paths(USD), + deliver_min(BTC(100)), + txflags(tfPartialPayment), + sendmax(USD(100))); + env.require(balance(alice, BTC(100))); + }; + testHelper2TokensMix(test); + } + + { + Env env(*this, features); + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {bob, carol}, .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(1'200'000))); + AMM const ammBob(env, bob, XRP(5'500), BTC(1'200'000)); + env(pay(alice, carol, BTC(10'000'000)), + paths(XRP), + deliver_min(BTC(200'000)), + txflags(tfPartialPayment), + sendmax(XRP(1'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, BTC(10'000'000)), + paths(XRP), + deliver_min(BTC(200'000)), + txflags(tfPartialPayment), + sendmax(XRP(1'100))); + BEAST_EXPECT(ammBob.expectBalances(XRP(6'600), BTC(1'000'000), ammBob.tokens())); + env.require(balance(carol, BTC(200'000))); + } + + // IOU/MPT mix, similar to the above case + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 3000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, USD(100'000))); + env(pay(gw, bob, USD(100'000))); + env(pay(gw, carol, USD(100'000))); + + env(pay(gw, bob, BTC(1'200))); + env.close(); + + AMM const ammBob(env, bob, USD(5'500), BTC(1'200)); + env(pay(alice, carol, BTC(10'000)), + paths(USD), + deliver_min(BTC(200)), + txflags(tfPartialPayment), + sendmax(USD(1'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, BTC(10'000)), + paths(USD), + deliver_min(BTC(200)), + txflags(tfPartialPayment), + sendmax(USD(1'100))); + BEAST_EXPECT(ammBob.expectBalances(USD(6'600), BTC(1'000), ammBob.tokens())); + env.require(balance(carol, BTC(200))); + }; + testHelper2TokensMix(test); + } + + { + auto const dan = Account("dan"); + Env env(*this, features); + fund(env, gw, {alice, bob, carol, dan}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {bob, carol, dan}, .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(100'000'000))); + env(pay(gw, dan, BTC(1'100'000'000))); + env(offer(bob, XRP(100), BTC(100'000'000))); + env(offer(bob, XRP(1'000), BTC(100'000'000))); + AMM const ammDan(env, dan, XRP(1'000), BTC(1'100'000'000)); + + env(pay(alice, carol, BTC(10'000'000'000)), + paths(XRP), + deliver_min(BTC(200'000'000)), + txflags(tfPartialPayment), + sendmax(XRPAmount(200'000'001))); + env.require(balance(bob, BTC(0))); + env.require(balance(carol, BTC(200'000'000))); + BEAST_EXPECT( + ammDan.expectBalances(XRPAmount{1'100'000'001}, BTC(1000'000000), ammDan.tokens())); + } + } + + void + testPayment(FeatureBitset features) + { + testcase("Payment"); + + using namespace jtx; + Account const becky{"becky"}; + + Env env(*this, features); + fund(env, gw, {alice, becky}, XRP(5'000)); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, becky}, .flags = MPTDEXFlags}); + + env(pay(gw, alice, BTC(500'000))); + env.close(); + + AMM const ammAlice(env, alice, XRP(100), BTC(140'000)); + + // becky pays herself BTC (10'000) by consuming part of alice's offer. + // Make sure the payment works if PaymentAuth is not involved. + env(pay(becky, becky, BTC(10'000)), path(~MPT(BTC)), sendmax(XRP(10))); + env.close(); + BEAST_EXPECT( + ammAlice.expectBalances(XRPAmount(107'692'308), BTC(130'000), ammAlice.tokens())); + + // becky decides to require authorization for deposits. + env(fset(becky, asfDepositAuth)); + env.close(); + + // becky pays herself again. + env(pay(becky, becky, BTC(10'000)), path(~MPT(BTC)), sendmax(XRP(10)), ter(tesSUCCESS)); + + env.close(); + } + + void + testPayMPT() + { + // Exercise MPT payments and non-direct XRP payments to an account + // that has the lsfDepositAuth flag set. + testcase("Pay MPT"); + + using namespace jtx; + + Env env(*this); + + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester BTC( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + env(pay(gw, alice, BTC(150'000))); + env(pay(gw, carol, BTC(150'000))); + AMM const ammCarol(env, carol, BTC(100'000), XRPAmount(101)); + + env(pay(alice, bob, BTC(50'000))); + env.close(); + + // bob sets the lsfDepositAuth flag. + env(fset(bob, asfDepositAuth), require(flags(bob, asfDepositAuth))); + env.close(); + + // None of the following payments should succeed. + auto failedMptPayments = [this, &env, &BTC]() { + env.require(flags(bob, asfDepositAuth)); + + // Capture bob's balances before hand to confirm they don't + // change. + PrettyAmount const bobXrpBalance{env.balance(bob, XRP)}; + PrettyAmount const bobBTCBalance{env.balance(bob, MPT(BTC))}; + + env(pay(alice, bob, BTC(50'000)), ter(tecNO_PERMISSION)); + env.close(); + + // Note that even though alice is paying bob in XRP, the payment + // is still not allowed since the payment passes through an + // offer. + env(pay(alice, bob, drops(1)), sendmax(BTC(1'000)), ter(tecNO_PERMISSION)); + env.close(); + + BEAST_EXPECT(bobXrpBalance == env.balance(bob, XRP)); + BEAST_EXPECT(bobBTCBalance == env.balance(bob, MPT(BTC))); + }; + + // Test when bob has an XRP balance > base reserve. + failedMptPayments(); + + // Set bob's XRP balance == base reserve. Also demonstrate that + // bob can make payments while his lsfDepositAuth flag is set. + env(pay(bob, alice, BTC(25'000))); + env.close(); + + { + STAmount const bobPaysXRP{env.balance(bob, XRP) - reserve(env, 1)}; + XRPAmount const bobPaysFee{reserve(env, 1) - reserve(env, 0)}; + env(pay(bob, alice, bobPaysXRP), fee(bobPaysFee)); + env.close(); + } + + // Test when bob's XRP balance == base reserve. + BEAST_EXPECT(env.balance(bob, XRP) == reserve(env, 0)); + BEAST_EXPECT(env.balance(bob, MPT(BTC)) == BTC(25'000)); + failedMptPayments(); + + // Test when bob has an XRP balance == 0. + env(noop(bob), fee(reserve(env, 0))); + env.close(); + + BEAST_EXPECT(env.balance(bob, XRP) == XRP(0)); + failedMptPayments(); + + // Give bob enough XRP for the fee to clear the lsfDepositAuth flag. + env(pay(alice, bob, drops(env.current()->fees().base))); + + // bob clears the lsfDepositAuth and the next payment succeeds. + env(fclear(bob, asfDepositAuth)); + env.close(); + + env(pay(alice, bob, BTC(50'000))); + env.close(); + + env(pay(alice, bob, drops(1)), sendmax(BTC(1'000))); + env.close(); + BEAST_EXPECT(ammCarol.expectBalances(BTC(101'000), XRPAmount(100), ammCarol.tokens())); + } + + void + testIndividualLock(FeatureBitset features) + { + testcase("Individual Lock"); + + using namespace test::jtx; + Env env(*this, features); + + Account const G1{"G1"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + env.fund(XRP(1'000), G1, alice, bob); + + MPTTester BTC( + {.env = env, + .issuer = G1, + .holders = {alice, bob}, + .flags = tfMPTCanLock | MPTDEXFlags}); + + env(pay(G1, bob, BTC(10))); + env(pay(G1, alice, BTC(205))); + env.close(); + + AMM const ammAlice(env, alice, XRP(500), BTC(105)); + + env.require(balance(bob, BTC(10))); + env.require(balance(alice, BTC(100))); + + // Account with MPT unlocked (proving operations normally work) + // can make Payment + env(pay(alice, bob, BTC(1))); + + // can receive Payment + env(pay(bob, alice, BTC(1))); + env.close(); + + // Lock MPT for bob + BTC.set({.holder = bob, .flags = tfMPTLock}); + + { + // different from IOU. The offer is created but not crossed. + env(offer(bob, BTC(5), XRP(25))); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 1, {{{BTC(5), XRP(25)}}})); + BEAST_EXPECT(ammAlice.expectBalances(XRP(500), BTC(105), ammAlice.tokens())); + } + + { + // can not sell assets + env(offer(bob, XRP(1), BTC(5)), ter(tecUNFUNDED_OFFER)); + + // different from IOU + // can not receive Payment when locked + env(pay(alice, bob, BTC(1)), ter(tecPATH_DRY)); + + // can not make Payment when locked + env(pay(bob, alice, BTC(1)), ter(tecPATH_DRY)); + + env.require(balance(bob, BTC(10))); + } + + { + // Unlock + BTC.set({.holder = bob, .flags = tfMPTUnlock}); + env(offer(bob, XRP(1), BTC(5))); + env(pay(bob, alice, BTC(1))); + env(pay(alice, bob, BTC(1))); + env.close(); + } + } + + void + testGlobalLock(FeatureBitset features) + { + testcase("Global Lock"); + + using namespace test::jtx; + Env env(*this, features); + + Account const G1{"G1"}; + Account A1{"A1"}; + Account A2{"A2"}; + Account A3{"A3"}; + Account A4{"A4"}; + + env.fund(XRP(12'000), G1); + env.fund(XRP(1'000), A1); + env.fund(XRP(20'000), A2, A3, A4); + + MPTTester const ETH( + {.env = env, + .issuer = G1, + .holders = {A1, A2, A3, A4}, + .flags = tfMPTCanLock | MPTDEXFlags}); + + MPTTester BTC( + {.env = env, + .issuer = G1, + .holders = {A1, A2, A3, A4}, + .flags = tfMPTCanLock | MPTDEXFlags}); + + env(pay(G1, A1, ETH(1'000))); + env(pay(G1, A2, ETH(100))); + env(pay(G1, A3, BTC(100))); + env(pay(G1, A4, BTC(100))); + env.close(); + + AMM const ammG1(env, G1, XRP(10'000), ETH(100)); + env(offer(A1, XRP(10'000), ETH(100)), txflags(tfPassive)); + env(offer(A2, ETH(100), XRP(10'000)), txflags(tfPassive)); + env.close(); + + { + // Account without Global Lock (proving operations normally + // work) + // visible offers where taker_pays is unlocked issuer + auto offers = getAccountOffers(env, A2)[jss::offers]; + if (!BEAST_EXPECT(checkArraySize(offers, 1u))) + return; + + // visible offers where taker_gets is unlocked issuer + offers = getAccountOffers(env, A1)[jss::offers]; + if (!BEAST_EXPECT(checkArraySize(offers, 1u))) + return; + } + + { + // Offers/Payments + // assets can be bought on the market + AMM ammA3(env, A3, BTC(1), XRP(1)); + + // assets can be sold on the market + // AMM is bidirectional + env(pay(G1, A2, ETH(1))); + env(pay(A2, G1, ETH(1))); + env(pay(A2, A1, ETH(1))); + env(pay(A1, A2, ETH(1))); + ammA3.withdrawAll(std::nullopt); + } + + { + // Account with Global Lock + // set Global Lock first + BTC.set({.flags = tfMPTLock}); + + // assets can't be bought on the market + AMM const ammA3(env, A3, BTC(1), XRP(1), ter(tecFROZEN)); + + // direct issues can be sent + env(pay(G1, A2, BTC(1))); + env(pay(A2, G1, BTC(1))); + // locked + env(pay(A2, A1, BTC(1)), ter(tecPATH_DRY)); + env(pay(A1, A2, BTC(1)), ter(tecPATH_DRY)); + } + + { + auto offers = getAccountOffers(env, A2)[jss::offers]; + if (!BEAST_EXPECT(checkArraySize(offers, 1u))) + return; + + offers = getAccountOffers(env, A1)[jss::offers]; + if (!BEAST_EXPECT(checkArraySize(offers, 1u))) + return; + } + } + + void + testOffersWhenLocked(FeatureBitset features) + { + testcase("Offers for Locked MPTs"); + + using namespace test::jtx; + Env env(*this, features); + + Account const G1{"G1"}; + Account A2{"A2"}; + Account A3{"A3"}; + Account A4{"A4"}; + + env.fund(XRP(2'000), G1, A3, A4); + env.fund(XRP(2'000), A2); + env.close(); + + MPTTester BTC( + {.env = env, + .issuer = G1, + .holders = {A2, A3, A4}, + .flags = tfMPTCanLock | MPTDEXFlags}); + + env(pay(G1, A3, BTC(2'000))); + env(pay(G1, A4, BTC(2'001))); + env.close(); + + AMM const ammA3(env, A3, XRP(1'000), BTC(1'001)); + + // removal after successful payment + // test: make a payment with partially consuming offer + env(pay(A2, G1, BTC(1)), paths(MPT(BTC)), sendmax(XRP(1))); + env.close(); + + BEAST_EXPECT(ammA3.expectBalances(XRP(1'001), BTC(1'000), ammA3.tokens())); + + // test: someone else creates an offer providing liquidity + env(offer(A4, XRP(999), BTC(999))); + env.close(); + // The offer consumes AMM offer + BEAST_EXPECT(ammA3.expectBalances(XRP(1'000), BTC(1'001), ammA3.tokens())); + + // test: AMM is Locked + BTC.set({.holder = ammA3.ammAccount(), .flags = tfMPTLock}); + auto const info = ammA3.ammRpcInfo(); + BEAST_EXPECT(info[jss::amm][jss::asset2_frozen].asBool()); + env.close(); + + // test: Can make a payment via the new offer + env(pay(A2, G1, BTC(1)), paths(MPT(BTC)), sendmax(XRP(1))); + env.close(); + // AMM is not consumed + BEAST_EXPECT(ammA3.expectBalances(XRP(1'000), BTC(1'001), ammA3.tokens())); + + // removal buy successful OfferCreate + // test: lock the new offer + BTC.set({.holder = A4, .flags = tfMPTUnlock}); + env.close(); + + // test: can no longer create a crossing offer + env(offer(A2, BTC(999), XRP(999))); + env.close(); + + // test: offer was removed by offer_create + auto offers = getAccountOffers(env, A4)[jss::offers]; + if (!BEAST_EXPECT(checkArraySize(offers, 0u))) + return; + } + + void + testTxMultisign(FeatureBitset features) + { + testcase("Multisign AMM Transactions"); + + using namespace jtx; + Env env{*this, features}; + Account const bogie{"bogie", KeyType::secp256k1}; + Account const alice{"alice", KeyType::secp256k1}; + Account const becky{"becky", KeyType::ed25519}; + Account const zelda{"zelda", KeyType::secp256k1}; + fund(env, gw, {alice, becky, zelda}, XRP(20'000)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, becky, zelda}, + .pay = 20'000'000'000, + .flags = MPTDEXFlags}); + + // alice uses a regular key with the master disabled. + Account const alie{"alie", KeyType::secp256k1}; + env(regkey(alice, alie)); + env(fset(alice, asfDisableMaster), sig(alice)); + + // Attach signers to alice. + env(signers(alice, 2, {{becky, 1}, {bogie, 1}}), sig(alie)); + env.close(); + int constexpr signerListOwners{2}; + env.require(owners(alice, signerListOwners + 0)); + + msig const ms{becky, bogie}; + + // Multisign all AMM transactions + AMM ammAlice( + env, + alice, + XRP(10'000), + BTC(10'000), + false, + 0, + ammCrtFee(env).drops(), + std::nullopt, + std::nullopt, + ms, + ter(tesSUCCESS)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'000), ammAlice.tokens())); + + ammAlice.deposit(alice, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances(XRP(11'000), BTC(11'000), IOUAmount{11'000'000, 0})); + + ammAlice.withdraw(alice, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'000), ammAlice.tokens())); + + ammAlice.vote({}, 1'000); + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + + env(ammAlice.bid({.account = alice, .bidMin = 100}), ms).close(); + BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, IOUAmount{4'000})); + // 4000 tokens burnt + BEAST_EXPECT(ammAlice.expectBalances(XRP(10'000), BTC(10'000), IOUAmount{9'996'000, 0})); + } + + void + testToStrand(FeatureBitset features) + { + testcase("To Strand"); + + using namespace jtx; + + // cannot have more than one offer with the same output issue + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const ETH = issue1( + {.env = env, + .token = "ETH", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, ETH(50000))); + env(pay(gw, bob, ETH(50000))); + env(pay(gw, carol, ETH(50000))); + env.close(); + AMM const bobXRP_BTC(env, bob, XRP(1'000), BTC(1'000)); + AMM const bobBTC_ETH(env, bob, BTC(1'000), ETH(1'000)); + + // payment path: XRP -> XRP/BTC -> BTC/ETH -> ETH/BTC + env(pay(alice, carol, BTC(100)), + path(~BTC, ~ETH, ~BTC), + sendmax(XRP(200)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper2TokensMix(test); + } + } + + void + testRIPD1373(FeatureBitset features) + { + using namespace jtx; + testcase("RIPD1373"); + + { + Env env(*this, features); + fund(env, gw, {alice, bob}, XRP(10'000)); + + MPTTester BTC( + {.env = env, + .issuer = bob, + .holders = {alice, gw}, + .pay = 100'000'000, + .flags = MPTDEXFlags}); + + MPTTester ETH( + {.env = env, + .issuer = bob, + .holders = {alice, gw}, + .pay = 100'000'000, + .flags = MPTDEXFlags}); + + AMM const ammXRP_BTC(env, bob, XRP(100), BTC(100'000)); + env(offer(gw, XRP(100), BTC(100'000)), txflags(tfPassive)); + + AMM const ammBTC_ETH(env, bob, BTC(100'000), ETH(100'000)); + env(offer(gw, BTC(100'000), ETH(100'000)), txflags(tfPassive)); + + Path const p = [&] { + Path result; + result.push_back(allPathElements(gw, MPT(BTC))); + result.push_back(cpe(ETH.issuanceID())); + return result; + }(); + + PathSet const paths(p); + + env(pay(alice, alice, ETH(1'000)), + json(paths.json()), + sendmax(XRP(10)), + txflags(tfNoRippleDirect | tfPartialPayment), + ter(temBAD_PATH)); + } + + { + Env env(*this, features); + + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 100'000, + .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, XRP(100), BTC(100)); + + // payment path: XRP -> XRP/BTC -> BTC/XRP + env(pay(alice, carol, XRP(100)), + path(~MPT(BTC), ~XRP), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_PATHS)); + } + + { + Env env(*this, features); + + fund(env, gw, {alice, bob, carol}, XRP(10'000)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 100'000, + .flags = MPTDEXFlags}); + + AMM const ammBob(env, bob, XRP(100), BTC(100)); + + // payment path: XRP -> XRP/BTC -> BTC/XRP + env(pay(alice, carol, XRP(100)), + path(~MPT(BTC), ~XRP), + sendmax(XRP(200)), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_MAX)); + } + } + + void + testLoop(FeatureBitset features) + { + testcase("test loop"); + using namespace jtx; + + { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .flags = MPTDEXFlags}); + + env(pay(gw, bob, BTC(100'000'000))); + env(pay(gw, alice, BTC(100'000'000))); + env.close(); + + AMM const ammBob(env, bob, XRP(100), BTC(100'000'000)); + + // payment path: BTC -> BTC/XRP -> XRP/BTC + env(pay(alice, carol, BTC(100'000'000)), + sendmax(BTC(100'000'000)), + path(~XRP, ~MPT(BTC)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + } + + { + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const BTC = issue1( + {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}}); + auto const ETH = issue2( + {.env = env, .token = "ETH", .issuer = gw, .holders = {alice, bob, carol}}); + auto const CNY = issue3( + {.env = env, .token = "CNY", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, bob, BTC(200))); + env(pay(gw, bob, ETH(200))); + env(pay(gw, bob, CNY(100))); + env.close(); + + AMM const ammBobXRP_BTC(env, bob, XRP(100), BTC(100)); + AMM const ammBobBTC_ETH(env, bob, BTC(100), ETH(100)); + AMM const ammBobETH_CNY(env, bob, ETH(100), CNY(100)); + + // payment path: XRP->XRP/BTC->BTC/ETH->BTC/CNY + env(pay(alice, carol, CNY(100)), + sendmax(XRP(100)), + path(~BTC, ~ETH, ~BTC, ~CNY), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper3TokensMix(test); + } + } + + void + testPaths() + { + path_find_consume_all(); + via_offers_via_gateway(); + receive_max(); + path_find_01(); + path_find_02(); + path_find_06(); + } + + void + testFlow() + { + using namespace jtx; + FeatureBitset const all{testable_amendments()}; + + testFalseDry(all); + testBookStep(all); + testTransferRateNoOwnerFee(all); + testLimitQuality(); + testXRPPathLoop(); + } + + void + testCrossingLimits() + { + using namespace jtx; + FeatureBitset const all{testable_amendments()}; + testStepLimit(all); + } + + void + testDeliverMin() + { + using namespace jtx; + FeatureBitset const all{testable_amendments()}; + test_convert_all_of_an_asset(all); + } + + void + testDepositAuth() + { + auto const supported{jtx::testable_amendments()}; + testPayment(supported); + testPayMPT(); + } + + void + testLock() + { + using namespace test::jtx; + auto const sa = testable_amendments(); + testIndividualLock(sa); + testGlobalLock(sa); + testOffersWhenLocked(sa); + } + + void + testMultisign() + { + using namespace jtx; + auto const all = testable_amendments(); + + testTxMultisign(all); + } + + void + testPayStrand() + { + using namespace jtx; + auto const all = testable_amendments(); + + testToStrand(all); + testRIPD1373(all); + testLoop(all); + } + + void + run() override + { + testOffers(); + testPaths(); + testFlow(); + testCrossingLimits(); + testDeliverMin(); + testDepositAuth(); + testLock(); + testMultisign(); + testPayStrand(); + } +}; + +BEAST_DEFINE_TESTSUITE_PRIO(AMMExtendedMPT, app, xrpl, 1); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/AMMExtended_test.cpp b/src/test/app/AMMExtended_test.cpp index 281ceafd19..e98822266d 100644 --- a/src/test/app/AMMExtended_test.cpp +++ b/src/test/app/AMMExtended_test.cpp @@ -1348,7 +1348,7 @@ private: Env env = pathTestEnv(); env.fund(XRP(100'000'250), alice); fund(env, gw, {carol, bob}, {USD(100)}, Fund::All); - fund(env, gw, {alice}, {USD(100)}, Fund::IOUOnly); + fund(env, gw, {alice}, {USD(100)}, Fund::TokenOnly); AMM const ammCarol(env, carol, XRP(100), USD(100)); STPathSet st; @@ -1363,7 +1363,7 @@ private: BEAST_EXPECT(sa == XRP(100'000'000)); // Bob gets ~99.99USD. This is the amount Bob // can get out of AMM for 100,000,000XRP. - BEAST_EXPECT(equal(da, STAmount{bob["USD"].issue(), UINT64_C(99'9999000001), -10})); + BEAST_EXPECT(equal(da, STAmount{bob["USD"], UINT64_C(99'9999000001), -10})); } // carol holds gateway AUD, sells gateway AUD for XRP @@ -1941,10 +1941,10 @@ private: }; { // BTC -> USD - STPath const p1({IPE(USD.issue())}); + STPath const p1({IPE(USD)}); paths.push_back(p1); // BTC -> EUR -> USD - STPath const p2({IPE(EUR.issue()), IPE(USD.issue())}); + STPath const p2({IPE(EUR), IPE(USD)}); paths.push_back(p2); } @@ -3324,8 +3324,7 @@ private: env.trust(USD(1'000), alice, bob); env.trust(EUR(1'000), alice, bob); env.close(); - fund(env, bob, {alice, gw}, {BobUSD(100), BobEUR(100)}, Fund::IOUOnly); - env.close(); + fund(env, bob, {alice, gw}, {BobUSD(100), BobEUR(100)}, Fund::TokenOnly); AMM const ammBobXRP_USD(env, bob, XRP(100), BobUSD(100)); env(offer(gw, XRP(100), USD(100)), txflags(tfPassive)); diff --git a/src/test/app/AMMMPT_test.cpp b/src/test/app/AMMMPT_test.cpp new file mode 100644 index 0000000000..0a2f1de234 --- /dev/null +++ b/src/test/app/AMMMPT_test.cpp @@ -0,0 +1,7043 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +/** + * Basic tests of AMM functionality involving MPT assets, excluding those that + * use offers. Tests incorporating offers are in `AMMExtended_test`. + */ +struct AMMMPT_test : public jtx::AMMTest +{ +private: + void + testInstanceCreate() + { + testcase("Instance Create"); + + using namespace jtx; + + // XRP to MPT + testAMM( + [&](AMM& ammAlice, Env&) { + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'000), IOUAmount{10'000'000})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // IOU to MPT + testAMM( + [&](AMM& ammAlice, Env&) { + BEAST_EXPECT(ammAlice.expectBalances( + USD(20'000), MPT(ammAlice[1])(20'000), IOUAmount{20'000})); + }, + {{USD(20'000), AMMMPT(20'000)}}); + + // MPT to MPT + testAMM( + [&](AMM& ammAlice, Env&) { + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(20'000), MPT(ammAlice[1])(20'000), IOUAmount{20'000})); + }, + {{AMMMPT(20'000), AMMMPT(20'000)}}); + + // IOU to MPT + transfer fee + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + env(rate(gw, 1.25)); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .transferFee = 1'500, + .pay = 30'000}); + // no transfer fee on create + AMM const ammAlice(env, alice, USD(20'000), BTC(20'000)); + BEAST_EXPECT(ammAlice.expectBalances(USD(20'000), BTC(20'000), IOUAmount{20'000, 0})); + BEAST_EXPECT(expectHolding(env, alice, USD(0))); + // alice initially had 30'000 + BEAST_EXPECT(expectMPT(env, alice, BTC(10'000))); + } + + // Require authorization is set, account is authorized + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + env(fset(gw, asfRequireAuth)); + env(trust(alice, gw["USD"](30'000), 0)); + env(trust(gw, alice["USD"](0), tfSetfAuth)); + env(pay(gw, alice, USD(10'000))); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000)); + } + + // Cleared global freeze + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + MPTTester USD( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + USD.set({.flags = tfMPTLock}); + AMM const ammAliceFail(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); + USD.set({.flags = tfMPTUnlock}); + AMM const ammAlice(env, alice, XRP(10'000), USD(10'000)); + } + } + + void + testInvalidInstance() + { + testcase("Invalid Instance"); + + using namespace jtx; + + // Can't have both tokens the same MPT + { + Env env{*this}; + env.fund(XRP(30'000), alice, gw); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .transferFee = 1'500, + .pay = 40'000}); + AMM const ammAlice(env, alice, BTC(20'000), BTC(10'000), ter(temBAD_AMM_TOKENS)); + } + + // MPTCanTrade is not set and AMM creator is not the issuer of MPT + { + Env env{*this}; + env.fund(XRP(30'000), alice, gw); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanLock}); + AMM const ammAlice(env, alice, BTC(20'000), XRP(10'000), ter(tecNO_PERMISSION)); + } + + // MPTokenIssuance doesn't exist + { + Env env{*this}; + env.fund(XRP(30'000), alice, gw); + env.close(); + AMM const ammAlice( + env, alice, MPT(gw, 1'000)(20'000), XRP(10'000), ter(tecOBJECT_NOT_FOUND)); + } + + // MPToken doesn't exist and amm creator is not the issuer + { + Env env{*this}; + env.fund(XRP(30'000), alice, gw); + env.close(); + MPT const BTC = MPTTester({ + .env = env, + .issuer = gw, + }); + AMM const ammAlice(env, alice, BTC(20'000), XRP(10'000), ter(tecNO_AUTH)); + } + + // Can't have zero or negative amounts + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + env(rate(gw, 1.25)); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .transferFee = 1'500, + .pay = 30'000}); + + AMM const ammAlice(env, alice, XRP(0), BTC(10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice.ammExists()); + AMM const ammAlice1(env, alice, XRP(10'000), BTC(0), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice1.ammExists()); + AMM const ammAlice2(env, alice, USD(0), BTC(10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice2.ammExists()); + AMM const ammAlice3(env, alice, USD(10'000), BTC(0), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice3.ammExists()); + AMM const ammAlice4(env, alice, XRP(-10'0000), BTC(10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice4.ammExists()); + AMM const ammAlice5(env, alice, XRP(10'000), BTC(-10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice5.ammExists()); + AMM const ammAlice6(env, alice, USD(-10'000), BTC(10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice6.ammExists()); + AMM const ammAlice7(env, alice, USD(10'000), BTC(-10'000), ter(temBAD_AMOUNT)); + BEAST_EXPECT(!ammAlice7.ammExists()); + } + + // Bad MPT + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + + AMM const ammAlice(env, alice, XRP(10'000), MPT(badMPT())(100), ter(temBAD_MPT)); + + BEAST_EXPECT(!ammAlice.ammExists()); + } + + // Insufficient MPT balance + { + Env env{*this}; + fund(env, gw, {alice}, {USD(30'000)}, Fund::All); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .transferFee = 1'500, + .pay = 30'000}); + AMM const ammAlice(env, alice, XRP(10'000), BTC(40'000), ter(tecUNFUNDED_AMM)); + BEAST_EXPECT(!ammAlice.ammExists()); + } + + // Invalid trading fee + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .transferFee = 1'500, + .pay = 30'000}); + AMM const ammAlice( + env, + alice, + USD(10'000), + BTC(10'000), + false, + 65'001, + 10, + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_FEE)); + BEAST_EXPECT(!ammAlice.ammExists()); + } + + // AMM already exists XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + // Account bob1("bob1"); + env.fund(XRP(30'000), bob); + env.close(); + AMM const ammBob(env, bob, XRP(1'000), MPT(ammAlice[1])(1'000), ter(tecDUPLICATE)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // AMM already exists IOU/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + env.fund(XRP(30'000), bob); + env.close(); + env.trust(USD(10000), bob); + env(pay(gw, bob, USD(100))); + + AMM const ammBob(env, bob, USD(1'000), MPT(ammAlice[1])(1'000), ter(tecDUPLICATE)); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // AMM already exists MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + AMM const ammCarol( + env, + carol, + MPT(ammAlice[0])(1'000), + MPT(ammAlice[1])(2'000), + ter(tecDUPLICATE)); + }, + {{AMMMPT(20'000), AMMMPT(10'000)}}); + + // MPTRequireAuth flag is set and AMM creator is not authorized + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + env(fset(gw, asfRequireAuth)); + env(trust(alice, gw["USD"](30'000), 0)); + env(trust(gw, alice["USD"](0), tfSetfAuth)); + env.close(); + env(pay(gw, alice, USD(10'000))); + env.close(); + MPT const BTC = MPTTester( + {.env = env, .issuer = gw, .holders = {alice}, .flags = tfMPTRequireAuth}); + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000), ter(tecNO_AUTH)); + BEAST_EXPECT(!ammAlice.ammExists()); + } + + // MPTLocked flag is set + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + BTC.set({.flags = tfMPTLock}); + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000), ter(tecFROZEN)); + BEAST_EXPECT(!ammAlice.ammExists()); + } + + // MPT individually locked + { + Env env{*this}; + fund(env, gw, {alice, bob}, {USD(20'000)}, Fund::All); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + BTC.set({.holder = alice, .flags = tfMPTLock}); + + // alice's token is locked + AMM const ammAlice(env, alice, USD(10'000), BTC(10'000), ter(tecFROZEN)); + BEAST_EXPECT(!ammAlice.ammExists()); + + // bob can create + AMM const ammBob(env, bob, USD(10'000), BTC(10'000)); + BEAST_EXPECT(ammBob.ammExists()); + } + + // OutstandingAmount > MaximumAmount + { + Env env{*this}; + env.fund(XRP(1'000), gw, alice); + + MPTTester const BTC({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 100}); + + // OutstandingAmount is 0, issuer issues 10 over MaximumAmount + AMM const amm(env, gw, XRP(100), BTC(110), ter(tecUNFUNDED_AMM)); + + env(pay(gw, alice, BTC(100))); + + // OutstandingAmount is 100, issuer issues 100 over MaximumAmount + AMM const amm1(env, gw, XRP(100), BTC(100), ter(tecUNFUNDED_AMM)); + // This is fine - alice transfers 100 to AMM. OutstandingAmount + // is 100. + AMM const ammAlice(env, alice, XRP(100), BTC(100)); + } + } + + void + testInvalidDeposit(FeatureBitset features) + { + testcase("Invalid Deposit"); + + using namespace jtx; + + testAMM( + [&](AMM& ammAlice, Env& env) { + // LPTokenOut can not be zero + ammAlice.deposit(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + + // LPTokenOut can not be negative + ammAlice.deposit( + alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + + // LPTokenOut can not be MPT + { + Json::Value jv = Json::objectValue; + jv[jss::Account] = alice.human(); + jv[jss::TransactionType] = jss::AMMDeposit; + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::none); + jv[jss::LPTokenOut] = MPT(ammAlice[1])(100).value().getJson(JsonOptions::none); + jv[jss::Flags] = tfLPToken; + env(jv, ter(telENV_RPC_FAILED)); + } + + // Provided LPTokenOut does not match AMM pool's LPToken + // asset + { + Json::Value jv = Json::objectValue; + jv[jss::Account] = alice.human(); + jv[jss::TransactionType] = jss::AMMDeposit; + jv[jss::Asset] = STIssue(sfAsset, XRP).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, MPT(ammAlice[1])).getJson(JsonOptions::none); + jv[jss::LPTokenOut] = USD(100).value().getJson(JsonOptions::none); + jv[jss::Flags] = tfLPToken; + env(jv, ter(temBAD_AMM_TOKENS)); + } + + // Invalid trading fee + ammAlice.deposit( + carol, + std::nullopt, + XRP(200), + MPT(ammAlice[1])(200), + std::nullopt, + tfTwoAssetIfEmpty, + std::nullopt, + std::nullopt, + 10'000, + ter(temBAD_FEE)); + + // Invalid tokens + { + auto const mpt1 = MPTIssue{MPTID(0xabc)}; + auto const mpt2 = MPTIssue{MPTID(0xdef)}; + ammAlice.deposit( + alice, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + {{mpt1, mpt2}}, + std::nullopt, + std::nullopt, + ter(terNO_AMM)); + } + + // invalid MPT + ammAlice.deposit( + alice, badMPT(), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_MPT)); + ammAlice.deposit( + alice, XRP(100), badMPT(), std::nullopt, std::nullopt, ter(temBAD_MPT)); + + // MPTokenIssuance object doesn't exist + ammAlice.deposit( + alice, + XRP(100), + MPT(gw, 1'000)(100), + std::nullopt, + tfTwoAsset, + ter(temBAD_AMM_TOKENS)); + + // MPToken object doesn't exist + env.fund(XRP(1'000), bob); + ammAlice.deposit( + bob, + XRP(100), + MPT(ammAlice[1])(200), + std::nullopt, + tfTwoAsset, + ter(tecNO_AUTH)); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .flags = tfMPTCanLock | MPTDEXFlags, + .authHolder = true}); + + // Depositing mismatched token, invalid Asset1In.issue + ammAlice.deposit( + alice, + BTC(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMM_TOKENS)); + + // Depositing mismatched token, invalid Asset2In.issue + ammAlice.deposit( + alice, XRP(100), BTC(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + + // Assets can not be the same + ammAlice.deposit( + alice, + MPT(ammAlice[1])(100), + MPT(ammAlice[1])(200), + std::nullopt, + tfTwoAsset, + ter(temBAD_AMM_TOKENS)); + + // Invalid amount value + ammAlice.deposit( + alice, + MPT(ammAlice[1])(0), + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMOUNT)); + ammAlice.deposit( + alice, + MPT(ammAlice[1])(-1'000), + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMOUNT)); + + // Invalid Account + { + Account bad("bad"); + env.memoize(bad); + ammAlice.deposit( + bad, + std::nullopt, + MPT(ammAlice[1])(1'000), + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + seq(1), + std::nullopt, + ter(terNO_ACCOUNT)); + } + + // Invalid AMM + ammAlice.deposit( + alice, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + {{MPT(BTC), MPT(ammAlice[1])}}, + std::nullopt, + std::nullopt, + ter(terNO_AMM)); + + // Single deposit: 100000 tokens worth of MPT + // Amount to deposit exceeds Max + ammAlice.deposit( + carol, + 100'000, + MPT(ammAlice[1])(200), + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + + // Single deposit: 100000 tokens worth of XRP + // Amount to deposit exceeds Max + ammAlice.deposit( + carol, + 100'000, + XRP(200), + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + + // Deposit amount is invalid + ammAlice.deposit( + alice, + MPT(ammAlice[1])(0), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}, + std::nullopt, + ter(tecUNFUNDED_AMM)); + // Calculated amount is 0 + ammAlice.deposit( + alice, + MPT(ammAlice[1])(0), + std::nullopt, + STAmount{ammAlice.lptIssue(), 2'000, -6}, + std::nullopt, + ter(tecAMM_FAILED)); + + // Tiny deposit + ammAlice.deposit( + carol, + IOUAmount{1, -10}, + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + + // Deposit non-empty AMM + ammAlice.deposit( + carol, + XRP(100), + MPT(ammAlice[1])(100), + std::nullopt, + tfTwoAssetIfEmpty, + ter(tecAMM_NOT_EMPTY)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Tiny deposit + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const enabledV1_3 = env.current()->rules().enabled(fixAMMv1_3); + auto const err = !enabledV1_3 ? ter(temBAD_AMOUNT) : ter(tesSUCCESS); + // Pre-amendment XRP deposit side is rounded to 0 + // and deposit fails. + ammAlice.deposit(carol, IOUAmount{1, -1}, std::nullopt, std::nullopt, err); + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 0, + std::nullopt, + {features, features - fixAMMv1_3}); + + // Invalid AMM + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.withdrawAll(alice); + ammAlice.deposit(alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit MPT with eprice + // the calculated amount to deposit is negative. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}, + tfLimitLPToken, + ter(tecAMM_FAILED)); + + // although we should use lptoken unit for eprice, + // we don't check the currency any more, we just use + // the value + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{USD, 1, -1}, + tfLimitLPToken, + ter(tecAMM_FAILED)); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Globally locked MPT + { + Env env{*this}; + fund(env, gw, {alice, carol}, {USD(20'000)}, Fund::All); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM ammAlice(env, alice, USD(10'000), BTC(10'000)); + BTC.set({.flags = tfMPTLock}); + + ammAlice.deposit( + carol, BTC(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + + ammAlice.deposit(carol, USD(100), BTC(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + } + + // Individually lock MPT or freeze IOU (AMM) with IOU/MPT AMM + { + Env env{*this, features}; + fund(env, gw, {alice, carol}, {USD(20'000)}, Fund::All); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM ammAlice(env, alice, USD(10'000), BTC(10'000)); + + // Carol's mpt is locked + BTC.set({.holder = carol, .flags = tfMPTLock}); + + // Carol can not deposit locked mpt + ammAlice.deposit( + carol, BTC(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + + if (!features[featureAMMClawback]) + { + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecLOCKED)); + } + else + { + // Carol can not deposit non-forzen token either + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + } + + // Alice can deposit because she's not individually locked + ammAlice.deposit(alice, BTC(100), std::nullopt, std::nullopt, std::nullopt); + ammAlice.deposit(alice, 1'000, std::nullopt, std::nullopt); + ammAlice.deposit(alice, USD(100), std::nullopt, std::nullopt, std::nullopt); + + // Unlock + BTC.set({.holder = carol, .flags = tfMPTUnlock}); + // Carol can deposit after unlock + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt); + + // Individually frozen AMM + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env.close(); + + // Can deposit non-frozen token + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + + // Cannot deposit frozen token + ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // unfreeze IOU + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfClearFreeze)); + env.close(); + // Can deposit + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt); + + // Individually lock AMM + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); + + // Can deposit non-frozen token + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt); + + // Can not deposit locked token + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, BTC(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unlock AMM MPT + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); + // can deposit + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt); + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + } + + // Individually lock MPT (AMM) account with MPT/MPT AMM + { + Env env{*this}; + env.fund(XRP(10'000), gw, alice, carol); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester USD( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 40'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM ammAlice(env, alice, USD(10'000), BTC(10'000)); + + // Carol's BTC is locked + BTC.set({.holder = carol, .flags = tfMPTLock}); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + ammAlice.deposit( + carol, BTC(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unlock carol's BTC + BTC.set({.holder = carol, .flags = tfMPTUnlock}); + + // Can deposit + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt); + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + + // Individually lock MPT BTC (AMM) account + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); + + // Can deposit non-locked token USD + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt); + + // Can not deposit locked token BTC + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, BTC(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unlock AMM MPT BTC + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); + // Can deposit BTC + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt); + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + + // Individually Lock MPT USD (AMM) account + USD.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); + + // Can deposit non-locked token BTC + ammAlice.deposit(carol, BTC(100), std::nullopt, std::nullopt, std::nullopt); + + // Can not deposit locked token USD + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unlock AMM MPT USD + USD.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); + // Can deposit USD + ammAlice.deposit(carol, 1'000, std::nullopt, std::nullopt); + ammAlice.deposit(carol, USD(100), std::nullopt, std::nullopt, std::nullopt); + } + + // Deposit unauthorized token + { + Env env{*this, features}; + Account const gw("gateway"), alice{"alice"}, carol{"carol"}; + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + + MPTTester BTC(env, gw, {.holders = {alice, carol}, .fund = false}); + BTC.create( + {.maxAmt = 1'000'000, + .authorize = {{alice}}, + .pay = {{{alice}, 10'000}}, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + + AMM amm(env, alice, XRP(10'000), BTC(10'000)); + env.close(); + + if (!features[featureAMMClawback]) + { + amm.deposit(carol, XRP(10), std::nullopt, std::nullopt, std::nullopt); + } + else + { + amm.deposit( + carol, XRP(10), std::nullopt, std::nullopt, std::nullopt, ter(tecNO_AUTH)); + } + } + + // MPTCanTransfer is not set and the account is not the issuer of MPT + { + Env env{*this, features}; + Account const gw("gateway"), alice{"alice"}, carol{"carol"}; + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 1'000, + .flags = tfMPTCanTrade}); + + AMM amm(env, gw, XRP(10'000), BTC(10'000)); + + amm.deposit({.account = alice, .asset1In = BTC(10), .err = ter(tecNO_PERMISSION)}); + } + + // Insufficient XRP balance + testAMM( + [&](AMM& ammAlice, Env& env) { + env.fund(XRP(1'000), bob); + env.close(); + ammAlice.deposit(bob, XRP(10)); + ammAlice.deposit( + bob, + XRP(1'000), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecUNFUNDED_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Insufficient MPT balance + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[1])(450'000), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecUNFUNDED_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Insufficient IOU balance + testAMM( + [&](AMM& ammAlice, Env& env) { + fund(env, gw, {bob}, {USD(1'000)}, Fund::Acct); + ammAlice.deposit( + bob, + USD(1'001), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecUNFUNDED_AMM)); + }, + {{USD(1000), AMMMPT(1000)}}); + + // Insufficient MPT balance by tokens + { + Env env{*this}; + env.fund(XRP(30'000), alice, bob, gw); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 1'500, + .pay = 1000}); + AMM ammAlice(env, alice, XRP(20'000), BTC(1000)); + ammAlice.deposit( + bob, + 10'000'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecUNFUNDED_AMM)); + } + + // Insufficient reserve, XRP/MPT + { + Env env(*this); + auto const starting_xrp = reserve(env, 4) + env.current()->fees().base * 4; + env.fund(XRP(10'000), gw); + env.fund(XRP(10'000), alice); + env.fund(starting_xrp, carol); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 1'500, + .pay = 40'000}); + + env(offer(carol, XRP(100), BTC(101))); + AMM ammAlice(env, alice, XRP(1000), BTC(1000)); + ammAlice.deposit( + carol, + XRP(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecINSUF_RESERVE_LINE)); + + env(offer(carol, XRP(100), BTC(102))); + ammAlice.deposit( + carol, + BTC(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecINSUF_RESERVE_LINE)); + } + + // Invalid min + testAMM( + [&](AMM& ammAlice, Env& env) { + // min tokens can't be <= zero + ammAlice.deposit(carol, 0, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit(carol, -1, XRP(100), tfSingleAsset, ter(temBAD_AMM_TOKENS)); + ammAlice.deposit( + carol, + 0, + XRP(100), + MPT(ammAlice[1])(100), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMM_TOKENS)); + + // min amounts can't be <= zero + ammAlice.deposit( + carol, + 1'000, + XRP(0), + MPT(ammAlice[1])(100), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMOUNT)); + ammAlice.deposit( + carol, + 1'000, + XRP(100), + MPT(ammAlice[1])(-1), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_AMOUNT)); + ammAlice.deposit( + carol, + 1'000, + XRP(100), + badMPT(), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(temBAD_MPT)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Min deposit + testAMM( + [&](AMM& ammAlice, Env& env) { + // Equal deposit by tokens + ammAlice.deposit( + carol, + 1'000'000, + XRP(1'000), + MPT(ammAlice[1])(1'001), + std::nullopt, + tfLPToken, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + ammAlice.deposit( + carol, + 1'000'000, + XRP(1'001), + MPT(ammAlice[1])(1'000), + std::nullopt, + tfLPToken, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + // Equal deposit by asset + ammAlice.deposit( + carol, + 100'001, + XRP(100), + MPT(ammAlice[1])(100), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + // Single deposit by asset + ammAlice.deposit( + carol, + 488'090, + XRP(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_FAILED)); + }, + {{XRP(1000), AMMMPT(1000)}}); + + // OutstandingAmount > MaximumAmount + { + Env env{*this}; + env.fund(XRP(1'000), gw, alice); + + MPTTester const BTC({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 100}); + + AMM amm(env, gw, XRP(100), BTC(90)); + // OutstandingAmount is 90, issuer issues 1 over MaximumAmount + amm.deposit( + DepositArg{.account = gw, .asset1In = BTC(11), .err = ter(tecUNFUNDED_AMM)}); + + env(pay(gw, alice, BTC(10))); + + // OutstandingAmount is 100, issuer issues 10 over MaximumAmount + amm.deposit( + DepositArg{.account = gw, .asset1In = BTC(10), .err = ter(tecUNFUNDED_AMM)}); + // This is fine - alice transfers 10 to AMM. OutstandingAmount + // is 100. + amm.deposit(DepositArg{.account = alice, .asset1In = BTC(10)}); + } + } + + void + testDeposit() + { + testcase("Deposit"); + + using namespace jtx; + + // Equal deposit: 1000000 tokens. XRP/MPT AMM. + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + + // carol deposited 1000 XRP and pays the transaction fee + env.require(balance(carol, carolXRP - XRP(1000) - drops(baseFee))); + // carol deposited 1000 MPT + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(1000))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // single deposit MPT with eprice + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}, + tfLimitLPToken); + + // although we should use lptoken unit for eprice, + // we don't check the currency any more, we just use + // the value + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{USD, 1, -1}, + tfLimitLPToken); + }, + {{USD(10'000'000), AMMMPT(10'000)}}); + + // Equal deposit: 1000000 tokens. IOU/MPT combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit(carol, 1'000); + BEAST_EXPECT(ammAlice.expectBalances(BTC(11'000), USD(11'000), IOUAmount(11'000))); + + env.require(balance(carol, carolBTC - BTC(1000))); + env.require(balance(carol, carolUSD - USD(1000))); + }; + testHelper2TokensMix(test); + } + + // Deposit 100MPT/100XRP. XRP/MPT AMM. + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, MPT(ammAlice[1])(100), XRP(100)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'100), IOUAmount{10'100'000, 0})); + + env.require(balance(carol, carolXRP - XRP(100) - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(100))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Deposit MPT/IOU combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + ammAlice.deposit(carol, BTC(100), USD(100)); + + BEAST_EXPECT(ammAlice.expectBalances(BTC(10'100), USD(10'100), IOUAmount(10'100))); + + env.require(balance(carol, carolBTC - BTC(100))); + env.require(balance(carol, carolUSD - USD(100))); + }; + testHelper2TokensMix(test); + } + + // Equal limit deposit. + // Try to deposit 200MPT/100XRP. Is truncated to 100MPT/100XRP. + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, MPT(ammAlice[1])(200), XRP(100)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'100), IOUAmount{10'100'000, 0})); + + env.require(balance(carol, carolXRP - XRP(100) - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(100))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal limit deposit. MPT/IOU combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + ammAlice.deposit(carol, BTC(200), USD(100)); + BEAST_EXPECT(ammAlice.expectBalances(BTC(10'100), USD(10'100), IOUAmount(10'100))); + + env.require(balance(carol, carolBTC - BTC(100))); + env.require(balance(carol, carolUSD - USD(100))); + }; + testHelper2TokensMix(test); + } + + // Single deposit: 1000 MPT into MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, MPT(ammAlice[1])(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(11'000), IOUAmount{10'488'088'48170151, -8})); + + env.require(balance(carol, carolXRP - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(1000))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit: 1000 XRP into MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, XRP(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(10'000), IOUAmount{10'488'088'48170151, -8})); + + env.require(balance(carol, carolXRP - XRP(1000) - drops(baseFee))); + env.require(balance(carol, carolMPT)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit: 1000 MPT0 into MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT0 = env.balance(carol, MPT(ammAlice[0])); + auto carolMPT1 = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, MPT(ammAlice[0])(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(11'000), + MPT(ammAlice[1])(10'000), + IOUAmount{10'488'08848170151, -11})); + + env.require(balance(carol, carolMPT0 - MPT(ammAlice[0])(1000))); + env.require(balance(carol, carolMPT1)); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + // Single deposit: 1000 MPT into MPT/IOU + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[0])); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit(carol, MPT(ammAlice[0])(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(11'000), USD(10'000), IOUAmount{10'488'08848170151, -11})); + + env.require(balance(carol, carolMPT - MPT(ammAlice[0])(1000))); + env.require(balance(carol, carolUSD)); + }, + {{AMMMPT(10'000), USD(10'000)}}); + + // Single deposit: 1000 IOU into MPT/IOU + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[0])); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit(carol, USD(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000), + STAmount{USD, UINT64_C(10999'99999999999), -11}, + IOUAmount{10'488'08848170151, -11})); + + env.require(balance(carol, carolMPT)); + env.require( + balance(carol, carolUSD - STAmount{USD, UINT64_C(999'99999999999), -11})); + }, + {{AMMMPT(10'000), USD(10'000)}}); + + // Single deposit: 100000 tokens worth of MPT into XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, 100'000, MPT(ammAlice[1])(205)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'201), IOUAmount{10'100'000, 0})); + + env.require(balance(carol, carolXRP - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(201))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit: 100000 tokens worth of XRP into XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit(carol, 100'000, XRP(205)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'201), MPT(ammAlice[1])(10'000), IOUAmount{10'100'000, 0})); + + env.require(balance(carol, carolXRP - XRP(201) - drops(baseFee))); + env.require(balance(carol, carolMPT)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit: 100 tokens worth of MPT/IOU into pool of MPT/IOU + // combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit(carol, 100, USD(205)); + auto deltaUSD = [&]() { + if constexpr (std::is_same_v>) + return USD(202); + return USD(201); + }(); + BEAST_EXPECT(ammAlice.expectBalances( + BTC(10'000), USD(10'000) + deltaUSD, IOUAmount{10'100, 0})); + + env.require(balance(carol, carolBTC)); + env.require(balance(carol, carolUSD - deltaUSD)); + }; + testHelper2TokensMix(test); + } + + // Single deposit with EP not exceeding specified: + // 100 MPT with EP not to exceed 0.1 (AssetIn/TokensOut) + // for XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}); + + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10100), IOUAmount{10'049'875'62112089, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit with EP not exceeding specified: + // 100 MPT with EP not to exceed 0.002004 (AssetIn/TokensOut) + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 2004, -6}); + + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'081), IOUAmount{10'039'920'31840891, -8})); + + env.require(balance(carol, carolXRP - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(81))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit with EP not exceeding specified: + // 0 MPT with EP not to exceed 0.002004 (AssetIn/TokensOut) + testAMM( + [&](AMM& ammAlice, Env& env) { + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + ammAlice.deposit( + carol, + MPT(ammAlice[1])(0), + std::nullopt, + STAmount{ammAlice.lptIssue(), 2004, -6}); + + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'081), IOUAmount{10'039'920'31840891, -8})); + + env.require(balance(carol, carolXRP - drops(baseFee))); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(81))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit with EP not exceeding specified: + // 100 MPT with EP not to exceed 0.1 (AssetIn/TokensOut) + // for IOU/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}); + + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'000'000'000), + MPT(ammAlice[1])(10100), + IOUAmount{10'049'875'62112089, -8})); + }, + {{USD(10'000'000'000), AMMMPT(10'000)}}); + + // Single deposit with EP not exceeding specified: + // 100 IOU with EP not to exceed 0.1 (AssetIn/TokensOut) + // for IOU/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, USD(100), std::nullopt, STAmount{USD, 1, -1}); + + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[1])(10'000'000'000), + USD(10100), + IOUAmount{10'049'875'62112089, -8})); + }, + {{USD(10'000), AMMMPT(10'000'000'000)}}); + + // Single deposit with EP not exceeding specified: + // 100 IOU with EP not to exceed 0.1 (AssetIn/TokensOut) + // for MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + MPT(ammAlice[0])(100), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}); + + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[1])(10'000'000'000), + MPT(ammAlice[0])(10100), + IOUAmount{10'049'875'62112089, -8})); + }, + {{AMMMPT(10'000), AMMMPT(10'000'000'000)}}); + + // MPT/MPT with transfer fee + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 25'000, + .pay = 400'000}); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 25'000, + .pay = 400'000}); + + AMM ammAlice(env, alice, USD(200'000), BTC(5)); + BEAST_EXPECT(ammAlice.expectBalances(USD(200'000), BTC(5), IOUAmount{1000, 0})); + + ammAlice.deposit(carol, 100, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(USD(220'000), BTC(6), IOUAmount{1100, 0})); + } + + // IOU/MPT with transfer fee + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, bob, carol); + env.close(); + + env(rate(gw, 1.25)); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 400'000}); + + auto const USD = gw["USD"]; + env.trust(USD(1000000), alice); + env(pay(gw, alice, USD(1000000))); + env.trust(USD(1000000), bob); + env(pay(gw, bob, USD(1000000))); + env.trust(USD(1000000), carol); + env(pay(gw, carol, USD(1000000))); + env.close(); + + // IOU/MPT + AMM ammAlice(env, alice, USD(200'000), BTC(5)); + BEAST_EXPECT(ammAlice.expectBalances(USD(200'000), BTC(5), IOUAmount{1000, 0})); + ammAlice.deposit(carol, 100, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(USD(220'000), BTC(6), IOUAmount{1100, 0})); + + MPT const ETH = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 400'000}); + + // MPT/IOU + AMM ammBob(env, bob, ETH(20'000), USD(0.5)); + BEAST_EXPECT(ammBob.expectBalances(ETH(20'000), USD(0.5), IOUAmount{100, 0})); + ammBob.deposit(carol, 10); + BEAST_EXPECT(ammBob.expectBalances(ETH(22'000), USD(0.55), IOUAmount{110, 0})); + } + + // Tiny deposits for IOU/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + // tiny amount causes MPT to deposit rounded to 0 + ammAlice.deposit(carol, IOUAmount{1, -3}, std::nullopt, std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'000'001), -3}, + MPT(ammAlice[1])(10'001), + IOUAmount{10'000'001, -3})); + + ammAlice.deposit(carol, IOUAmount{1}); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'001'001), -3}, + MPT(ammAlice[1])(10'003), + IOUAmount{10'001'001, -3})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, STAmount{USD, 1, -10}); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'000'00000000008), -11}, + MPT(ammAlice[1])(10'000), + IOUAmount{1'000'000'000000004, -11})); + + ammAlice.deposit(carol, MPT(ammAlice[1])(1)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'000'00000000008), -11}, + MPT(ammAlice[1])(10'001), + IOUAmount{10'000'49998750066, -11})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Tiny deposits for XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, XRPAmount{1}); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'000'000'001}, + MPT(ammAlice[1])(10'000), + IOUAmount{1'000'000'000049999, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'001), IOUAmount{10'000'499'98750062, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Tiny deposits for MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1)); + + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000), + MPT(ammAlice[1])(10'001), + IOUAmount{1'000'049'998750062, -11})); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + // MPT Issuer create/deposit + { + Env env(*this); + env.fund(XRP(30'000), gw); + env.close(); + + MPT const BTC = MPTTester({.env = env, .issuer = gw, .holders = {}}); + + AMM ammGw(env, gw, XRP(10'000), BTC(10'000'000'000)); + BEAST_EXPECT( + ammGw.expectBalances(XRP(10'000), BTC(10'000'000'000), IOUAmount{10'000'000'000})); + + ammGw.deposit(gw, 1'000'000); + BEAST_EXPECT( + ammGw.expectBalances(XRP(10'001), BTC(10'001000000), IOUAmount{10'001000000})); + + ammGw.deposit(gw, BTC(1'000000000)); + BEAST_EXPECT(ammGw.expectBalances( + XRP(10'001), BTC(11'001000000), IOUAmount{1048'908'961731188, -5})); + } + + // Issuer deposit in MPT/MPT pool + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(gw, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(1'010'000), + MPT(ammAlice[1])(1'010'000), + IOUAmount{1'010'000})); + + ammAlice.deposit(gw, MPT(ammAlice[0])(1000)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(1'010'999), + MPT(ammAlice[1])(1'010'000), + IOUAmount{1'010'499'376546071, -9})); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + // Issuer deposit in MPT/XRP pool + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(gw, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000})); + ammAlice.deposit(gw, MPT(ammAlice[1])(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(12'000), IOUAmount{11'489'125'29307605, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit by tokens MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 1'000'000, + XRP(1'000), + MPT(ammAlice[1])(1'000), + std::nullopt, + tfLPToken, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit by tokens MPT/IOU combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit( + carol, + 1'000, + USD(1'000), + BTC(1'000), + std::nullopt, + tfLPToken, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances(USD(11'000), BTC(11'000), IOUAmount{11'000})); + + env.require(balance(carol, carolBTC - BTC(1000))); + env.require(balance(carol, carolUSD - USD(1000))); + }; + testHelper2TokensMix(test); + } + + // Equal deposit by asset XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 1'000'000, + XRP(1'000), + MPT(ammAlice[1])(1'000), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit by asset IOU/MPT combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + + ammAlice.deposit( + carol, + 1'000, + USD(1'000), + BTC(1'000), + std::nullopt, + tfTwoAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT( + ammAlice.expectBalances(USD(11'000), BTC(11'000), IOUAmount{11'000, 0})); + + env.require(balance(carol, carolBTC - BTC(1000))); + env.require(balance(carol, carolUSD - USD(1000))); + }; + testHelper2TokensMix(test); + } + + // Single deposit XRP by asset MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 488'088, + XRP(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(10'000), IOUAmount{10'488'088'48170151, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit MPT by asset MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 488'088, + MPT(ammAlice[1])(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(11'000), IOUAmount{10'488'088'48170151, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit IOU by asset MPT/IOU + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 488, + USD(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + MPT(ammAlice[1])(10'000), + IOUAmount{10'488'08848170151, -11})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit MPT by asset MPT/IOU + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 488, + MPT(ammAlice[1])(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'000), MPT(ammAlice[1])(11'000), IOUAmount{10'488'088'48170151, -11})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit MPT by asset MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit( + carol, + 488, + MPT(ammAlice[1])(1'000), + std::nullopt, + std::nullopt, + tfSingleAsset, + std::nullopt, + std::nullopt); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000), + MPT(ammAlice[1])(11'000), + IOUAmount{10'488'088'48170151, -11})); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + } + + void + testInvalidWithdraw() + { + testcase("Invalid AMMWithdraw"); + + using namespace jtx; + auto const all = testable_amendments(); + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .asset1Out = XRP(100), + .err = ter(tecAMM_BALANCE), + }; + ammAlice.withdraw(args); + }, + {{XRP(99), AMMMPT(99)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .asset1Out = MPT(ammAlice[1])(100), + .err = ter(tecAMM_BALANCE), + }; + ammAlice.withdraw(args); + }, + {{XRP(99), AMMMPT(99)}}); + + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice, bob); + env.close(); + // alice is authorized to hold gw MPT, bob is not authorized + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + WithdrawArg const args{ + .account = bob, + .asset1Out = BTC(100), + .err = ter(tecNO_AUTH), + }; + ammAlice.withdraw(args); + } + + testAMM( + [&](AMM& ammAlice, Env& env) { + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 2'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + // Invalid tokens + ammAlice.withdraw(alice, 0, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw( + alice, IOUAmount{-1}, std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + + // Mismatched token, invalid Asset1Out issue + ammAlice.withdraw( + alice, BTC(100), std::nullopt, std::nullopt, ter(temBAD_AMM_TOKENS)); + ammAlice.withdraw( + alice, MPT(badMPT())(100), std::nullopt, std::nullopt, ter(temBAD_MPT)); + + // Mismatched token, invalid Asset2Out issue + ammAlice.withdraw(alice, XRP(100), BTC(100), std::nullopt, ter(temBAD_AMM_TOKENS)); + + // Mismatched token, Asset1Out.issue == Asset2Out.issue + ammAlice.withdraw( + alice, + MPT(ammAlice[1])(100), + MPT(ammAlice[1])(100), + std::nullopt, + ter(temBAD_AMM_TOKENS)); + + // Invalid amount value + ammAlice.withdraw( + alice, MPT(ammAlice[1])(0), std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.withdraw( + alice, MPT(ammAlice[1])(-100), std::nullopt, std::nullopt, ter(temBAD_AMOUNT)); + ammAlice.withdraw( + alice, MPT(ammAlice[1])(10), std::nullopt, IOUAmount{-1}, ter(temBAD_AMOUNT)); + + // Invalid amount/token value, withdraw all tokens from one side + // of the pool. + ammAlice.withdraw( + alice, + MPT(ammAlice[1])(10'000), + std::nullopt, + std::nullopt, + ter(tecAMM_BALANCE)); + ammAlice.withdraw( + alice, XRP(10'000), std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); + ammAlice.withdraw( + alice, + std::nullopt, + MPT(ammAlice[1])(0), + std::nullopt, + std::nullopt, + tfOneAssetWithdrawAll, + std::nullopt, + std::nullopt, + ter(tecAMM_BALANCE)); + + // Bad MPT + ammAlice.withdraw( + alice, XRP(100), MPT(badMPT())(100), std::nullopt, ter(temBAD_MPT)); + + // Specified MPToken doesn't match the pool assets + ammAlice.withdraw( + alice, XRP(100), MPT(noMPT())(100), std::nullopt, ter(temBAD_AMM_TOKENS)); + + // Invalid Account + Account bad("bad"); + env.memoize(bad); + ammAlice.withdraw( + bad, + 1'000'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + seq(1), + ter(terNO_ACCOUNT)); + + // Invalid AMM + ammAlice.withdraw( + alice, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + std::nullopt, + {{MPT(ammAlice[1]), GBP}}, + std::nullopt, + ter(terNO_AMM)); + + // Carol is not a Liquidity Provider + ammAlice.withdraw(carol, 10'000, std::nullopt, std::nullopt, ter(tecAMM_BALANCE)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + // Withdraw entire one side of the pool. + // Pre-fixAMMv1_3: + // Equal withdraw but due to MPT precision limit, + // this results in full withdraw of MPT pool only, + // while leaving a tiny amount in USD pool. + // Post-fixAMMv1_3: + // Most of the pool is withdrawn with remaining tiny amounts + auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); + ammAlice.withdraw( + alice, IOUAmount{9'999'999'9999, -4}, std::nullopt, std::nullopt, err); + if (env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(1), STAmount{USD, 1, -7}, IOUAmount{1, -4})); + } + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}, + 0, + std::nullopt, + {all, all - fixAMMv1_3}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + // Similar to above with even smaller remaining amount + // Pre-fixAMMv1_3: results in full withdraw of MPT pool only, + // returning tecAMM_BALANCE. Post-fixAMMv1_3: most of the pool + // is withdrawn with remaining tiny amounts + auto err = env.enabled(fixAMMv1_3) ? ter(tesSUCCESS) : ter(tecAMM_BALANCE); + ammAlice.withdraw( + alice, IOUAmount{9'999'999'999999999, -9}, std::nullopt, std::nullopt, err); + if (env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(1), STAmount{USD, 1, -11}, IOUAmount{1, -8})); + } + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}, + 0, + std::nullopt, + {all, all - fixAMMv1_3}); + + // Invalid AMM + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.withdrawAll(alice); + ammAlice.withdraw(alice, 10'000, std::nullopt, std::nullopt, ter(terNO_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // MPTokenIssuance object doesn't exist + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + MPT const BTC = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 30'000}); + + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + + ammAlice.withdraw( + WithdrawArg{ + .account = alice, + .asset1Out = MPT(gw, 1'000)(10), + .assets = {{XRP, MPT(gw, 1'000)}}, + .err = ter(terNO_AMM)}); + } + + // MPTRequireAuth flag is set and the account is not authorized + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + auto BTCM = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + MPT const BTC = BTCM; + + AMM amm(env, alice, XRP(10'000), BTC(10'000)); + + BTCM.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + + amm.withdraw( + WithdrawArg{ + .account = alice, + .asset1Out = BTC(100), + .assets = {{XRP, BTC}}, + .err = ter(tecNO_AUTH)}); + } + + // MPTCanTransfer is not set and the account is not the issuer of MPT + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + auto BTCM = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanTrade, + .authHolder = true}); + MPT const BTC = BTCM; + + AMM amm(env, gw, XRP(10'000), BTC(10'000)); + + amm.withdraw( + WithdrawArg{ + .account = alice, + .asset1Out = BTC(100), + .assets = {{XRP, BTC}}, + .err = ter(tecNO_PERMISSION)}); + } + + // Globally locked MPT + // MPTLocked flag is set and the account is not the issuer of MPT + { + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags, + .authHolder = true}); + + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + BTC.set({.flags = tfMPTLock}); + + ammAlice.withdraw( + alice, MPT(ammAlice[1])(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + + // can single withdraw the other asset + ammAlice.withdraw({.account = alice, .asset1Out = XRP(100)}); + } + + // Individually frozen (AMM) account with MPT/MPT AMM + { + Env env{*this}; + env.fund(XRP(10'000), gw, alice); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM ammAlice(env, alice, USD(10'000), BTC(10'000)); + + // Alice's BTC is locked + BTC.set({.holder = alice, .flags = tfMPTLock}); + ammAlice.withdraw(alice, 1000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + + // can withdraw the other asset + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + + // Unlock and then alice can withdraw + BTC.set({.holder = alice, .flags = tfMPTUnlock}); + ammAlice.withdraw(alice, 1000, std::nullopt, std::nullopt); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + } + + // Individually lock MPT or freeze IOU (AMM) + { + Env env{*this}; + fund(env, gw, {alice}, {USD(20'000)}, Fund::All); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM ammAlice(env, alice, USD(10'000), BTC(10'000)); + + // Alice's BTC is locked + BTC.set({.holder = alice, .flags = tfMPTLock}); + + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + // can still single withdraw the unlocked other asset + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + + // Unlock alice's BTC + BTC.set({.holder = alice, .flags = tfMPTUnlock}); + + // Now alice can withdraw + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt); + + // Individually lock MPT BTC (AMM) account + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); + + // Can withdraw non-frozen token USD + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + + // Can not withdraw locked token BTC + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unlock AMM MPT + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTUnlock}); + // Can withdraw + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt); + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt); + + // Individually frozen AMM + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfSetFreeze)); + env.close(); + + // Can withdraw non-locked token BTC + ammAlice.withdraw(alice, BTC(100), std::nullopt, std::nullopt); + + // Can not withdraw frozen token USD + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + + // Unfreeze + env(trust( + gw, STAmount{Issue{gw["USD"].currency, ammAlice.ammAccount()}, 0}, tfClearFreeze)); + env.close(); + + // Can withdraw + ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt); + ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt); + } + + // Carol withdraws more than she owns + testAMM( + [&](AMM& ammAlice, Env&) { + // Single deposit of 100000 worth of tokens + // which is 10% of the pool. Carol is LP now. + ammAlice.deposit(carol, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + + ammAlice.withdraw( + carol, 2'000'000, std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Withdraw with EPrice limit. Fails to withdraw, calculated tokens + // to withdraw are 0. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + auto const err = + env.enabled(fixAMMv1_3) ? ter(tecAMM_INVALID_TOKENS) : ter(tecAMM_FAILED); + ammAlice.withdraw( + carol, MPT(ammAlice[1])(100), std::nullopt, IOUAmount{500, 0}, err); + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 0, + std::nullopt, + {all, all - fixAMMv1_3}); + + // Withdraw with EPrice limit. Fails to withdraw, calculated tokens + // to withdraw are greater than the LP shares. + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000'000); + ammAlice.withdraw( + carol, + MPT(ammAlice[1])(100), + std::nullopt, + IOUAmount{600, 0}, + ter(tecAMM_INVALID_TOKENS)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Withdraw with EPrice limit. Fails to withdraw, amount1 + // to withdraw is less than 1700 MPT. + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000'000); + ammAlice.withdraw( + carol, + MPT(ammAlice[1])(1'700), + std::nullopt, + IOUAmount{520, 0}, + ter(tecAMM_FAILED)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Deposit/Withdraw the same amount with the trading fee + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdraw( + carol, + MPT(ammAlice[1])(1'000), + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 1'000); + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, XRP(1'000)); + ammAlice.withdraw( + carol, XRP(1'000), std::nullopt, std::nullopt, ter(tecAMM_INVALID_TOKENS)); + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 1'000); + + // Deposit/Withdraw the same amount fails due to the tokens adjustment + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, STAmount{USD, 1, -6}); + ammAlice.withdraw( + carol, + STAmount{USD, 1, -6}, + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + + // Withdraw close to one side of the pool. Account's LP tokens + // are rounded to all LP tokens. + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw( + alice, + STAmount{MPT(ammAlice[1]), UINT64_C(9'999'999999999999), -12}, + std::nullopt, + std::nullopt, + ter(tecAMM_BALANCE)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Tiny withdraw + testAMM( + [&](AMM& ammAlice, Env&) { + // XRP amount to withdraw is 0 + ammAlice.withdraw( + alice, IOUAmount{1, -5}, std::nullopt, std::nullopt, ter(tecAMM_FAILED)); + // Calculated tokens to withdraw are 0 + ammAlice.withdraw( + alice, + std::nullopt, + STAmount{USD, 1, -11}, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + ammAlice.deposit(carol, STAmount{USD, 1, -10}); + ammAlice.withdraw( + carol, + std::nullopt, + STAmount{USD, 1, -9}, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + ammAlice.withdraw( + carol, + std::nullopt, + MPT(ammAlice[0])(1), + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + } + + void + testWithdraw() + { + testcase("Withdraw"); + + using namespace jtx; + + // Equal withdrawal by Carol: 1'000'000 of tokens, 10% of the current + // pool + testAMM( + [&](AMM& ammAlice, Env& env) { + // XRP/MPT + XRPAmount const baseFee{env.current()->fees().base}; + auto carolXRP = env.balance(carol, XRP); + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + + // Single deposit of 1'000'000 worth of tokens, + // which is 10% of the pool. Carol is LP now. + ammAlice.deposit(carol, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{11'000'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); + env.require(balance(carol, carolMPT - MPT(ammAlice[1])(1'000))); + env.require(balance(carol, carolXRP - XRP(1'000) - drops(baseFee))); + + // Carol withdraws all tokens + ammAlice.withdraw(carol, 1'000'000); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + env.require(balance(carol, carolMPT)); + env.require(balance(carol, carolXRP - drops(2 * baseFee))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal withdrawal by tokens 1000000, 10% + // of the current pool, XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + // XRP/MPT + ammAlice.withdraw(alice, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(9'000), MPT(ammAlice[1])(9'000), IOUAmount{9'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal withdrawal by tokens, 10% of the current pool, IOU/MPT + // combination + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env.close(); + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + ammAlice.withdraw(alice, 1'000); + BEAST_EXPECT(ammAlice.expectBalances(BTC(9'000), USD(9'000), IOUAmount(9'000))); + env.require(balance(alice, aliceBTC + BTC(1000))); + env.require(balance(alice, aliceUSD + USD(1000))); + }; + testHelper2TokensMix(test); + } + + // Equal withdrawal with a limit. Withdraw XRP200. + // If proportional withdraw of MPT is less than 100 + // then withdraw that amount, otherwise withdraw MPT100 + // and proportionally withdraw XRP. It's the latter + // in this case - XRP100/MPT100. + testAMM( + [&](AMM& ammAlice, Env&) { + // XRP/MPT + ammAlice.withdraw(alice, XRP(200), MPT(ammAlice[1])(100)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(9'900), MPT(ammAlice[1])(9'900), IOUAmount{9'900'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal withdrawal with a limit. XRP100/MPT200 truncated to + // XRP100/MPT100 + testAMM( + [&](AMM& ammAlice, Env&) { + // XRP/MPT + ammAlice.withdraw(alice, XRP(100), MPT(ammAlice[1])(200)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(9'900), MPT(ammAlice[1])(9'900), IOUAmount{9'900'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal withdrawal with a limit. IOU/MPT combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env.close(); + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + ammAlice.withdraw(alice, BTC(200), USD(100)); + BEAST_EXPECT(ammAlice.expectBalances(BTC(9'900), USD(9'900), IOUAmount(9'900))); + env.require(balance(alice, aliceBTC + BTC(100))); + env.require(balance(alice, aliceUSD + USD(100))); + }; + testHelper2TokensMix(test); + } + + // Single withdrawal by amount + testAMM( + [&](AMM& ammAlice, Env&) { + // single withdraw XRP from XRP/MPT + ammAlice.withdraw(alice, XRP(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(9000'000001), + MPT(ammAlice[1])(10'000), + IOUAmount{9'486'832'98050514, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // single withdraw MPT from XRP/MPT + ammAlice.withdraw(alice, MPT(ammAlice[1])(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10000), MPT(ammAlice[1])(9001), IOUAmount{9'486'832'98050514, -8})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // single withdraw IOU from IOU/MPT + ammAlice.withdraw(alice, USD(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(9000'000000000004), -12}, + MPT(ammAlice[1])(10'000), + IOUAmount{9486'83298050514, -11})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // single withdraw MPT from IOU/MPT + ammAlice.withdraw(alice, MPT(ammAlice[1])(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'000), MPT(ammAlice[1])(9001), IOUAmount{9486'83298050514, -11})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // single withdraw MPT from MPT/MPT + ammAlice.withdraw(alice, MPT(ammAlice[0])(1'000)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(9001), + MPT(ammAlice[1])(10'000), + IOUAmount{9486'83298050514, -11})); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + // Single withdrawal MPT by tokens 10000. XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, 10'000, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(9981), IOUAmount{9'990'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single withdrawal XRP by tokens 10000. XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, 10'000, XRP(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(9980010000), MPT(ammAlice[1])(10'000), IOUAmount{9'990'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single withdrawal by tokens 10000. MPT/IOU combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env.close(); + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto aliceBTC = env.balance(alice, BTC); + auto aliceUSD = env.balance(alice, USD); + ammAlice.withdraw(alice, 1000, BTC(0)); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'000), BTC(8100), IOUAmount{9000, 0})); + env.require(balance(alice, aliceBTC + BTC(1900))); + env.require(balance(alice, aliceUSD)); + }; + testHelper2TokensMix(test); + } + + // Withdraw all tokens. + testAMM( + [&](AMM& ammAlice, Env& env) { + env(trust(carol, STAmount{ammAlice.lptIssue(), 10'000})); + // Can SetTrust only for AMM LP tokens + env(trust(carol, STAmount{Issue{EUR.currency, ammAlice.ammAccount()}, 10'000}), + ter(tecNO_PERMISSION)); + env.close(); + ammAlice.withdrawAll(alice); + BEAST_EXPECT(!ammAlice.ammExists()); + + BEAST_EXPECT(!env.le(keylet::ownerDir(ammAlice.ammAccount()))); + + // Can create AMM for the XRP/MPT pair + AMM const ammCarol(env, carol, XRP(10'000), MPT(ammAlice[1])(10'000)); + BEAST_EXPECT(ammCarol.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'000), IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in MPT from XRP/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'001), IOUAmount{10'000'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in XRP from XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, XRP(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(9'090'909'091), MPT(ammAlice[1])(11000), IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in MPT from USD/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + // USD/MPT + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'000), MPT(ammAlice[1])(10'001), IOUAmount{10'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000USD, withdraw all tokens in USD from USD/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + // USD/MPT + ammAlice.deposit(carol, USD(1'000)); + ammAlice.withdrawAll(carol, USD(0)); + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'000), MPT(ammAlice[1])(10'000), IOUAmount{10'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in MPT from MPT/MPT + testAMM( + [&](AMM& ammAlice, Env& env) { + // MPT/MPT + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000), MPT(ammAlice[1])(10'001), IOUAmount{10'000, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount(beast::Zero()))); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10001), IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000MPT, withdraw all tokens in USD + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + ammAlice.withdrawAll(carol, USD(0)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(9'090'9090909091), -10}, + MPT(ammAlice[1])(11000), + IOUAmount{10'000, 0})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit 1000USD, withdraw all tokens in MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, USD(1'000)); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(10'999'99999999999), -11}, + MPT(ammAlice[1])(9091), + IOUAmount{10'000, 0})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + + // Single deposit/withdraw by the same account + testAMM( + [&](AMM& ammAlice, Env&) { + auto lpTokens = ammAlice.deposit(carol, USD(1'000)); + ammAlice.withdraw(carol, lpTokens, USD(0)); + lpTokens = ammAlice.deposit(carol, STAmount(USD, 1, -6)); + ammAlice.withdraw(carol, lpTokens, USD(0)); + lpTokens = ammAlice.deposit(carol, MPT(ammAlice[0])(1)); + ammAlice.withdraw(carol, lpTokens, MPT(ammAlice[0])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'001), USD(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + auto const& BTC = MPT(ammAlice[1]); + auto lpTokens = ammAlice.deposit(carol, BTC(1'000)); + ammAlice.withdraw(carol, lpTokens, BTC(0)); + lpTokens = ammAlice.deposit(carol, BTC(1)); + ammAlice.withdraw(carol, lpTokens, BTC(0)); + lpTokens = ammAlice.deposit(carol, BTC(1)); + ammAlice.withdraw(carol, lpTokens, BTC(0)); + BEAST_EXPECT(ammAlice.expectBalances(BTC(10'003), XRP(10'000), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Single deposit by different accounts and then withdraw + // in reverse. + testAMM( + [&](AMM& ammAlice, Env&) { + auto const carolTokens = ammAlice.deposit(carol, MPT(ammAlice[1])(1'000)); + auto const aliceTokens = ammAlice.deposit(alice, MPT(ammAlice[1])(1'000)); + ammAlice.withdraw(alice, aliceTokens, MPT(ammAlice[1])(0)); + ammAlice.withdraw(carol, carolTokens, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'001), ammAlice.tokens())); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + BEAST_EXPECT(ammAlice.expectLPTokens(alice, ammAlice.tokens())); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit 10%, withdraw all tokens. XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000'000); + ammAlice.withdrawAll(carol); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'000), IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + // Equal deposit 10%, withdraw all tokens. IOU/MPT combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, carol}, + .limit = 1'000'000}); + env(pay(gw, alice, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + auto carolBTC = env.balance(carol, BTC); + auto carolUSD = env.balance(carol, USD); + ammAlice.deposit(carol, 1'000); + ammAlice.withdrawAll(carol); + BEAST_EXPECT( + ammAlice.expectBalances(USD(10'000), BTC(10'000), IOUAmount{10'000, 0})); + env.require(balance(carol, carolBTC)); + env.require(balance(carol, carolUSD)); + }; + testHelper2TokensMix(test); + } + + // Equal deposit 10%, withdraw all tokens in MPT from XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000'000); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), + STAmount{MPT(ammAlice[1]), UINT64_C(9'090'909090909092), -12}, + IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit 10%, withdraw all tokens in XRP from XRP/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000'000); + ammAlice.withdrawAll(carol, XRP(0)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(9'090'909'091), MPT(ammAlice[1])(11'000), IOUAmount{10'000'000, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Equal deposit 10%, withdraw all tokens in USD from USD/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000); + ammAlice.withdrawAll(carol, USD(0)); + BEAST_EXPECT(ammAlice.expectBalances( + STAmount{USD, UINT64_C(9'090'909090909092), -12}, + MPT(ammAlice[1])(11'000), + IOUAmount{10'000})); + }, + {{USD(10'000), AMMMPT(10'000)}}); + // Equal deposit 10%, withdraw all tokens in MPT from MPT/MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.deposit(carol, 1'000); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(11'000), MPT(ammAlice[1])(9'091), IOUAmount{10'000})); + }, + {{AMMMPT(10'000), AMMMPT(10'000)}}); + + auto const all = testable_amendments(); + + // Withdraw with EPrice limit. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000'000'000); + ammAlice.withdraw( + carol, MPT(ammAlice[1])(100'000000), std::nullopt, IOUAmount{520, 0}); + if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781065), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + else if (env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781065), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + else if (env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781066), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + ammAlice.withdrawAll(carol); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + }, + {{XRP(10'000'000'000), AMMMPT(10'000'000'000)}}, + 0, + std::nullopt, + {all, all - fixAMMv1_3, all - fixAMMv1_1 - fixAMMv1_3}); + + // Withdraw with EPrice limit. AssetOut is 0. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000'000'000); + ammAlice.withdraw(carol, MPT(ammAlice[1])(0), std::nullopt, IOUAmount{520, 0}); + if (!env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781065), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + else if (env.enabled(fixAMMv1_1) && !env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781065), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + else if (env.enabled(fixAMMv1_3)) + { + BEAST_EXPECT( + ammAlice.expectBalances( + XRP(11'000'000000), + MPT(ammAlice[1])(9372781066), + IOUAmount{10'153'846'15384616, -2}) && + ammAlice.expectLPTokens(carol, IOUAmount{153'846'15384616, -2})); + } + ammAlice.withdrawAll(carol); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + }, + {{XRP(10'000'000'000), AMMMPT(10'000'000'000)}}, + 0, + std::nullopt, + {all, all - fixAMMv1_3, all - fixAMMv1_1 - fixAMMv1_3}); + + // IOU/MPT combination + transfer fee + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000, + .transferFee = 25'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000, + .transferFee = 25'000}); + env(pay(gw, alice, BTC(10000))); + env(pay(gw, bob, BTC(10000))); + env(pay(gw, carol, BTC(10000))); + env(pay(gw, alice, USD(10000))); + env(pay(gw, bob, USD(10000))); + env(pay(gw, carol, USD(10000))); + env.close(); + // no transfer fee on create + AMM ammAlice(env, alice, BTC(2'000), USD(5)); + BEAST_EXPECT(ammAlice.expectBalances(BTC(2'000), USD(5), IOUAmount{100, 0})); + env.require(balance(alice, BTC(8000))); + env.require(balance(alice, USD(9995))); + + // no transfer fee on deposit + ammAlice.deposit(carol, 100); + BEAST_EXPECT(ammAlice.expectBalances(BTC(4000), USD(10), IOUAmount{200, 0})); + env.require(balance(carol, BTC(8000))); + env.require(balance(carol, USD(9995))); + + // no transfer fee on withdraw + ammAlice.withdraw(carol, 100); + BEAST_EXPECT(ammAlice.expectBalances(BTC(2'000), USD(5), IOUAmount{100, 0})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0, 0})); + env.require(balance(carol, BTC(10000))); + env.require(balance(carol, USD(10000))); + }; + testHelper2TokensMix(test); + } + + // Tiny withdraw + testAMM( + [&](AMM& ammAlice, Env&) { + // By tokens + ammAlice.withdraw(alice, IOUAmount{1, -3}); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(9'999'999'999), + STAmount{USD, UINT64_C(9'999'999999), -6}, + IOUAmount{9'999'999'999, -3})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // Single withdraw MPT from MPT/IOU + ammAlice.withdraw(alice, std::nullopt, MPT(ammAlice[0])(1)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10000'000000), USD(10'000), IOUAmount{9'999'999'9995, -4})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // Single withdraw IOU from MPT/IOU + ammAlice.withdraw(alice, std::nullopt, STAmount{USD, 1, -10}); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'000), + STAmount{USD, UINT64_C(9'999'9999999999), -10}, + IOUAmount{9'999'999'99999995, -8})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + // Single withdraw XRP from MPT/XRP + ammAlice.withdraw(alice, std::nullopt, XRPAmount(1)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[1])(10'000), XRP(10'000), IOUAmount{9999999'9995, -4})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Withdraw close to entire pool + // Equal by tokens + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, IOUAmount{9'999'999'999, -3}); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(1), STAmount{USD, 1, -6}, IOUAmount{1, -3})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + // USD by tokens + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, IOUAmount{9'999'999}, USD(0)); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'000), STAmount{USD, 1, -10}, IOUAmount{1})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + // MPT by tokens + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, IOUAmount{9'999'900}, MPT(ammAlice[0])(0)); + BEAST_EXPECT( + ammAlice.expectBalances(MPT(ammAlice[0])(1), USD(10'000), IOUAmount{100})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + // XRP by tokens + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, IOUAmount{9'999'900}, XRP(0)); + BEAST_EXPECT( + ammAlice.expectBalances(MPT(ammAlice[1])(10000), XRPAmount(1), IOUAmount{100})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + // USD + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, STAmount{USD, UINT64_C(9'999'99999999999), -11}); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'000), + STAmount{USD, 1, -11}, + IOUAmount{316227765, -9})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + // XRP + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, XRPAmount{9'999'999'999}); + BEAST_EXPECT( + ammAlice.expectBalances(MPT(ammAlice[1])(10000), XRPAmount(1), IOUAmount{100})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + // MPT + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, MPT(ammAlice[0])(9'999'999'999)); + BEAST_EXPECT( + ammAlice.expectBalances(MPT(ammAlice[0])(1), USD(10'000), IOUAmount{100})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + testAMM( + [&](AMM& ammAlice, Env&) { + ammAlice.withdraw(alice, MPT(ammAlice[1])(9'999)); + BEAST_EXPECT( + ammAlice.expectBalances(MPT(ammAlice[1])(1), XRP(10'000), IOUAmount{100000})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + } + + void + testInvalidFeeVote() + { + testcase("Invalid Fee Vote"); + using namespace jtx; + + testAMM( + [&](AMM& ammAlice, Env& env) { + // Invalid Account + Account bad("bad"); + env.memoize(bad); + ammAlice.vote(bad, 1'000, std::nullopt, seq(1), std::nullopt, ter(terNO_ACCOUNT)); + + // Invalid AMM + ammAlice.vote( + alice, + 1'000, + std::nullopt, + std::nullopt, + {{MPT(ammAlice[1]), GBP}}, + ter(terNO_AMM)); + + // Account is not LP + ammAlice.vote( + carol, + 1'000, + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecAMM_INVALID_TOKENS)); + + // Invalid asset pair + ammAlice.vote( + alice, + 1'000, + std::nullopt, + std::nullopt, + {{MPT(ammAlice[1]), MPT(ammAlice[1])}}, + ter(temBAD_AMM_TOKENS)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Invalid AMM + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.withdrawAll(alice); + ammAlice.vote( + alice, 1'000, std::nullopt, std::nullopt, std::nullopt, ter(terNO_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // MPTokenInstance object doesn't exist + { + Env env(*this); + env.fund(XRP(1'000), alice); + env(AMM::voteJv({.account = alice, .tfee = 1'000, .assets = {{XRP, MPT(alice, 0)}}}), + ter(terNO_AMM)); + } + } + + void + testFeeVote() + { + testcase("Fee Vote"); + using namespace jtx; + + // One vote sets fee to 1%. + testAMM( + [&](AMM& ammAlice, Env& env) { + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{0})); + ammAlice.vote({}, 1'000); + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + // Discounted fee is 1/10 of trading fee. + BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, IOUAmount{0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + auto vote = [&](AMM& ammAlice, + Env& env, + int i, + std::uint32_t tokens = 10'000'000, + std::vector* accounts = nullptr) { + Account a(std::to_string(i)); + ammAlice.deposit(a, tokens); + ammAlice.vote(a, 50 * (i + 1)); + if (accounts) + accounts->push_back(std::move(a)); + }; + + { + // Eight votes fill all voting slots, set fee 0.175%. + // New vote, same account, sets fee 0.225% + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + std::vector holders = {alice}; + for (int i = 0; i <= 7; ++i) + { + Account const a(std::to_string(i)); + holders.push_back(a); + env.fund(XRP(30'000), a); + } + env.close(); + // create MPT and pay 30'000 to all the accounts + MPTTester const BTC({.env = env, .issuer = gw, .holders = holders, .pay = 30'000}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + for (int i = 0; i < 7; ++i) + vote(ammAlice, env, i); + BEAST_EXPECT(ammAlice.expectTradingFee(175)); + Account const a("0"); + ammAlice.vote(a, 450); + BEAST_EXPECT(ammAlice.expectTradingFee(225)); + } + + { + // Eight votes fill all voting slots, set fee 0.175%. + // New vote, new account, higher vote weight, set higher fee 0.244% + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + std::vector holders = {alice}; + for (int i = 0; i < 8; ++i) + { + Account const a(std::to_string(i)); + holders.push_back(a); + env.fund(XRP(30'000), a); + } + env.close(); + MPTTester const BTC({.env = env, .issuer = gw, .holders = holders, .pay = 30'000}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + for (int i = 0; i < 7; ++i) + vote(ammAlice, env, i); + BEAST_EXPECT(ammAlice.expectTradingFee(175)); + vote(ammAlice, env, 7, 20'000'000); + BEAST_EXPECT(ammAlice.expectTradingFee(244)); + } + + { + // Eight votes fill all voting slots, set fee 0.219%. + // New vote, new account, higher vote weight, set smaller fee 0.206% + Env env{*this}; + env.fund(XRP(30'000), gw, alice); + std::vector holders = {alice}; + for (int i = 0; i < 8; ++i) + { + Account const a(std::to_string(i)); + holders.push_back(a); + env.fund(XRP(30'000), a); + } + env.close(); + MPTTester const BTC({.env = env, .issuer = gw, .holders = holders, .pay = 30'000}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + for (int i = 7; i > 0; --i) + vote(ammAlice, env, i); + BEAST_EXPECT(ammAlice.expectTradingFee(219)); + vote(ammAlice, env, 0, 20'000'000); + BEAST_EXPECT(ammAlice.expectTradingFee(206)); + } + + { + // Eight votes fill all voting slots. The accounts then withdraw all + // tokens. An account sets a new fee and the previous slots are + // deleted. + Env env{*this}; + env.fund(XRP(30'000), gw, alice, carol); + std::vector holders = {alice, carol}; + for (int i = 0; i < 7; ++i) + { + Account const a(std::to_string(i)); + holders.push_back(a); + env.fund(XRP(30'000), a); + } + env.close(); + MPTTester const BTC({.env = env, .issuer = gw, .holders = holders, .pay = 30'000}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + std::vector accounts; + for (int i = 0; i < 7; ++i) + vote(ammAlice, env, i, 10'000'000, &accounts); + BEAST_EXPECT(ammAlice.expectTradingFee(175)); + for (int i = 0; i < 7; ++i) + ammAlice.withdrawAll(accounts[i]); + ammAlice.deposit(carol, 10'000'000); + ammAlice.vote(carol, 1'000); + // The initial LP set the fee to 1000. Carol gets 50% voting + // power, and the new fee is 500. + BEAST_EXPECT(ammAlice.expectTradingFee(500)); + } + { + // Eight votes fill all voting slots. The accounts then withdraw + // some tokens. The new vote doesn't get the voting power but the + // slots are refreshed and the fee is updated. + Env env{*this}; + env.fund(XRP(30'000), gw, alice, carol); + std::vector holders = {alice, carol}; + for (int i = 0; i < 7; ++i) + { + Account const a(std::to_string(i)); + holders.push_back(a); + env.fund(XRP(30'000), a); + } + env.close(); + MPTTester const BTC({.env = env, .issuer = gw, .holders = holders, .pay = 30'000}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + std::vector accounts; + for (int i = 0; i < 7; ++i) + vote(ammAlice, env, i, 10'000'000, &accounts); + BEAST_EXPECT(ammAlice.expectTradingFee(175)); + for (int i = 0; i < 7; ++i) + ammAlice.withdraw(accounts[i], 9'000'000); + ammAlice.deposit(carol, 1'000); + // The vote is not added to the slots + ammAlice.vote(carol, 1'000); + auto const info = ammAlice.ammRpcInfo()[jss::amm][jss::vote_slots]; + for (auto i = 0; i < info.size(); ++i) + BEAST_EXPECT(info[i][jss::account] != carol.human()); + // But the slots are refreshed and the fee is changed + BEAST_EXPECT(ammAlice.expectTradingFee(82)); + } + } + + void + testInvalidBid() + { + testcase("Invalid Bid"); + using namespace jtx; + using namespace std::chrono; + + // burn all the LPTokens through a AMMBid transaction + { + Env env(*this); + env.fund(XRP(2'000), gw, alice); + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice}, .pay = 2'000, .flags = MPTDEXFlags}); + AMM amm(env, gw, XRP(1'000), BTC(1'000), false, 1'000); + + // auction slot is owned by the creator of the AMM i.e. gw + BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0})); + + // gw attempts to burn all her LPTokens through a bid transaction + // this transaction fails because AMMBid transaction can not burn + // all the outstanding LPTokens + env(amm.bid({ + .account = gw, + .bidMin = 1'000'000, + }), + ter(tecAMM_INVALID_TOKENS)); + } + + // burn all the LPTokens through a AMMBid transaction + { + Env env(*this); + env.fund(XRP(2'000), gw, alice); + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice}, .pay = 2'000, .flags = MPTDEXFlags}); + AMM amm(env, gw, XRP(1'000), BTC(1'000), false, 1'000); + + // auction slot is owned by the creator of the AMM i.e. gw + BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0})); + + // gw burns all but one of its LPTokens through a bid transaction + // this transaction succeeds because the bid price is less than + // the total outstanding LPToken balance + env(amm.bid({ + .account = gw, + .bidMin = STAmount{amm.lptIssue(), UINT64_C(999'999)}, + }), + ter(tesSUCCESS)) + .close(); + + // gw must own the auction slot + BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{999'999})); + + // 999'999 tokens are burned, only 1 LPToken is owned by gw + BEAST_EXPECT(amm.expectBalances(XRP(1'000), BTC(1'000), IOUAmount{1})); + + // gw owns only 1 LPToken in its balance + BEAST_EXPECT(Number{amm.getLPTokensBalance(gw)} == 1); + + // gw attempts to burn the last of its LPTokens in an AMMBid + // transaction. This transaction fails because it would burn all + // the remaining LPTokens + env(amm.bid({ + .account = gw, + .bidMin = 1, + }), + ter(tecAMM_INVALID_TOKENS)); + } + + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + // Invlaid Min/Max combination + env(ammAlice.bid({ + .account = carol, + .bidMin = 200, + .bidMax = 100, + }), + ter(tecAMM_INVALID_TOKENS)); + + // Invalid Account + Account bad("bad"); + env.memoize(bad); + env(ammAlice.bid({ + .account = bad, + .bidMax = 100, + }), + seq(1), + ter(terNO_ACCOUNT)); + + // Account is not LP + Account const dan("dan"); + env.fund(XRP(1'000), dan); + env(ammAlice.bid({ + .account = dan, + .bidMin = 100, + }), + ter(tecAMM_INVALID_TOKENS)); + env(ammAlice.bid({ + .account = dan, + }), + ter(tecAMM_INVALID_TOKENS)); + + // Auth account is invalid. + env(ammAlice.bid({ + .account = carol, + .bidMin = 100, + .authAccounts = {bob}, + }), + ter(terNO_ACCOUNT)); + + // Invalid Assets + env(ammAlice.bid({ + .account = alice, + .bidMax = 100, + .assets = {{MPT(ammAlice[1]), GBP}}, + }), + ter(terNO_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Invalid AMM + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.withdrawAll(alice); + env(ammAlice.bid({ + .account = alice, + .bidMax = 100, + }), + ter(terNO_AMM)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Bid price exceeds LP owned tokens + { + Env env(*this); + fund(env, gw, {alice, bob, carol}, XRP(1'000), {USD(30'000)}, Fund::All); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 30'000'000'000, + .flags = MPTDEXFlags}); + + AMM ammAlice(env, alice, BTC(10'000'000'000), USD(10'000)); + ammAlice.deposit(carol, 1'000'000); + ammAlice.deposit(bob, 10); + env(ammAlice.bid({ + .account = carol, + .bidMin = 1'000'001, + }), + ter(tecAMM_INVALID_TOKENS)); + env(ammAlice.bid({ + .account = carol, + .bidMax = 1'000'001, + }), + ter(tecAMM_INVALID_TOKENS)); + env(ammAlice.bid({ + .account = carol, + .bidMin = 1'000, + })); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{1'000})); + // Slot purchase price is more than 1000 but bob only has 10 tokens + env(ammAlice.bid({ + .account = bob, + }), + ter(tecAMM_INVALID_TOKENS)); + } + + // Bid all tokens, still own the slot + { + Env env(*this); + env.fund(XRP(1'000), gw, alice, bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 1'000, + .flags = MPTDEXFlags}); + AMM amm(env, gw, XRP(10), BTC(1'000)); + auto const lpIssue = amm.lptIssue(); + env.trust(STAmount{lpIssue, 100}, alice); + env.trust(STAmount{lpIssue, 50}, bob); + env(pay(gw, alice, STAmount{lpIssue, 100})); + env(pay(gw, bob, STAmount{lpIssue, 50})); + env(amm.bid({.account = alice, .bidMin = 100})); + // Alice doesn't have any more tokens, but + // she still owns the slot. + env(amm.bid({ + .account = bob, + .bidMax = 50, + }), + ter(tecAMM_FAILED)); + } + } + + void + testBid(FeatureBitset features) + { + testcase("Bid"); + using namespace jtx; + using namespace std::chrono; + + // Auction slot initially is owned by AMM creator, who pays 0 price. + + // Bid 110 tokens. Pay bidMin. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + env(ammAlice.bid({.account = carol, .bidMin = 110})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); + // 110 tokens are burned. + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{10'999'890, 0})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Bid with min/max when the pay price is less than min. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + // Bid exactly 110. Pay 110 because the pay price is < 110. + env(ammAlice.bid({.account = carol, .bidMin = 110, .bidMax = 110})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{10'999'890})); + // Bid exactly 180-200. Pay 180 because the pay price is < 180. + env(ammAlice.bid({.account = alice, .bidMin = 180, .bidMax = 200})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{180})); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(11'000), MPT(ammAlice[1])(11'000), IOUAmount{10'999'814'5, -1})); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Start bid at bidMin 110. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol, bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 30'000, + .flags = MPTDEXFlags}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + + ammAlice.deposit(carol, 1'000'000); + // Bid, pay bidMin. + env(ammAlice.bid({.account = carol, .bidMin = 110})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); + + ammAlice.deposit(bob, 1'000'000); + // Bid, pay the computed price. + env(ammAlice.bid({.account = bob})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount(1155, -1))); + + // Bid bidMax fails because the computed price is higher. + env(ammAlice.bid({ + .account = carol, + .bidMax = 120, + }), + ter(tecAMM_FAILED)); + // Bid MaxSlotPrice succeeds - pay computed price + env(ammAlice.bid({.account = carol, .bidMax = 600})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{121'275, -3})); + + // Bid Min/MaxSlotPrice fails because the computed price is not + // in range + env(ammAlice.bid({ + .account = carol, + .bidMin = 10, + .bidMax = 100, + }), + ter(tecAMM_FAILED)); + // Bid Min/MaxSlotPrice succeeds - pay computed price + env(ammAlice.bid({.account = carol, .bidMin = 100, .bidMax = 600})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{127'33875, -5})); + } + + // Slot states. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol, bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 30'000, + .flags = MPTDEXFlags}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'000)); + + ammAlice.deposit(carol, 1'000'000); + ammAlice.deposit(bob, 1'000'000); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(12'000'000001), BTC(12'001), IOUAmount{12'000'000, 0})); + + // Initial state. Pay bidMin. + env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{110})); + + // 1st Interval after close, price for 0th interval. + env(ammAlice.bid({.account = bob})); + env.close(seconds(AUCTION_SLOT_INTERVAL_DURATION + 1)); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 1, IOUAmount{1'155, -1})); + + // 10th Interval after close, price for 1st interval. + env(ammAlice.bid({.account = carol})); + env.close(seconds((10 * AUCTION_SLOT_INTERVAL_DURATION) + 1)); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 10, IOUAmount{121'275, -3})); + + // 20th Interval (expired) after close, price for 10th interval. + env(ammAlice.bid({.account = bob})); + env.close(seconds((AUCTION_SLOT_TIME_INTERVALS * AUCTION_SLOT_INTERVAL_DURATION) + 1)); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{127'33875, -5})); + + // 0 Interval. + env(ammAlice.bid({.account = carol, .bidMin = 110})).close(); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, std::nullopt, IOUAmount{110})); + // ~321.09 tokens burnt on bidding fees. + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(12'000'000001), BTC(12'001), IOUAmount{11'999'678'91000001, -8})); + } + + // Pool's fee 1%. Bid bidMin. + // Auction slot owner and auth account trade at discounted fee - + // 1/10 of the trading fee. + // Other accounts trade at 1% fee. + { + Env env(*this); + Account const dan("dan"); + Account const ed("ed"); + env.fund(XRP(2'000), gw, alice, bob, carol, dan, ed); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .pay = 30'000'000'000}); + fund(env, gw, {alice, carol}, {USD(30'000)}, Fund::TokenOnly); + fund(env, gw, {bob, dan, ed}, {USD(20'000)}, Fund::TokenOnly); + + AMM ammAlice(env, alice, BTC(10'000'000'000), USD(10'000), CreateArg{.tfee = 1'000}); + ammAlice.deposit(bob, 1'000'000); + ammAlice.deposit(ed, 1'000'000); + ammAlice.deposit(carol, 500'000); + ammAlice.deposit(dan, 500'000); + auto ammTokens = ammAlice.getLPTokensBalance(); + env(ammAlice.bid({ + .account = carol, + .bidMin = 120, + .authAccounts = {bob, ed}, + })); + auto const slotPrice = IOUAmount{5'200}; + ammTokens -= slotPrice; + BEAST_EXPECT(ammAlice.expectAuctionSlot(100, 0, slotPrice)); + BEAST_EXPECT(ammAlice.expectBalances(BTC(13'000'000'003), USD(13'000), ammTokens)); + // Discounted trade + for (int i = 0; i < 10; ++i) + { + auto tokens = ammAlice.deposit(carol, USD(100)); + ammAlice.withdraw(carol, tokens, USD(0)); + tokens = ammAlice.deposit(bob, USD(100)); + ammAlice.withdraw(bob, tokens, USD(0)); + tokens = ammAlice.deposit(ed, USD(100)); + ammAlice.withdraw(ed, tokens, USD(0)); + } + // carol, bob, and ed pay ~0.99USD in fees. + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(29'499'00572620545), -11)); + BEAST_EXPECT(env.balance(bob, USD) == STAmount(USD, UINT64_C(18'999'00572616195), -11)); + BEAST_EXPECT(env.balance(ed, USD) == STAmount(USD, UINT64_C(18'999'00572611841), -11)); + // USD pool is slightly higher because of the fees. + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'000'000'003), STAmount(USD, UINT64_C(13'002'98282151419), -11), ammTokens)); + + ammTokens = ammAlice.getLPTokensBalance(); + // Trade with the fee + for (int i = 0; i < 10; ++i) + { + auto const tokens = ammAlice.deposit(dan, USD(100)); + ammAlice.withdraw(dan, tokens, USD(0)); + } + // dan pays ~9.94USD, which is ~10 times more in fees than + // carol, bob, ed. the discounted fee is 10 times less + // than the trading fee. + + BEAST_EXPECT(env.balance(dan, USD) == STAmount(USD, UINT64_C(19'490'05672274398), -11)); + // USD pool gains more in dan's fees. + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'000'000'003), STAmount{USD, UINT64_C(13'012'92609877021), -11}, ammTokens)); + // Discounted fee payment + ammAlice.deposit(carol, USD(100)); + ammTokens = ammAlice.getLPTokensBalance(); + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(13'000'000'003), + STAmount{USD, UINT64_C(13'112'92609877019), -11}, + ammTokens)); + env(pay(carol, bob, USD(100)), path(~USD), sendmax(BTC(110'000'000))); + env.close(); + // carol pays 100000 drops in fees + // 99900668MPT swapped in for 100USD + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'100'000'671), STAmount{USD, UINT64_C(13'012'92609877019), -11}, ammTokens)); + + // Payment with the trading fee + env(pay(alice, carol, BTC(100'000'000)), path(~MPT(ammAlice[0])), sendmax(USD(110))); + env.close(); + // alice pays ~1.011USD in fees, which is ~10 times more + // than carol's fee + // 100.099431529USD swapped in for 100MPT + + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'000'000'671), STAmount{USD, UINT64_C(13'114'03663044931), -11}, ammTokens)); + + // Auction slot expired, no discounted fee + env.close(seconds(TOTAL_TIME_SLOT_SECS + 1)); + // clock is parent's based + env.close(); + + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(29'399'00572620547), -11)); + ammTokens = ammAlice.getLPTokensBalance(); + for (int i = 0; i < 10; ++i) + { + auto const tokens = ammAlice.deposit(carol, USD(100)); + ammAlice.withdraw(carol, tokens, USD(0)); + } + // carol pays ~9.94USD in fees, which is ~10 times more in + // trading fees vs discounted fee. + + BEAST_EXPECT( + env.balance(carol, USD) == STAmount(USD, UINT64_C(29'389'06197177122), -11)); + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'000'000'671), STAmount{USD, UINT64_C(13'123'98038488356), -11}, ammTokens)); + + env(pay(carol, bob, USD(100)), path(~USD), sendmax(BTC(110'000'000))); + env.close(); + // carol pays ~1.008MPT in trading fee, which is + // ~10 times more than the discounted fee. + // 99.815876MPT is swapped in for 100USD + BEAST_EXPECT(ammAlice.expectBalances( + BTC(13'100'824'793), STAmount{USD, UINT64_C(13'023'98038488356), -11}, ammTokens)); + } + + // Bid tiny amount + testAMM( + [&](AMM& ammAlice, Env& env) { + // Bid a tiny amount + auto const tiny = Number{STAmount::cMinValue, STAmount::cMinOffset}; + env(ammAlice.bid({.account = alice, .bidMin = IOUAmount{tiny}})); + // Auction slot purchase price is equal to the tiny amount + // since the minSlotPrice is 0 with no trading fee. + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny})); + // The purchase price is too small to affect the total tokens + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'000), USD(10'000), ammAlice.tokens())); + // Bid the tiny amount + env(ammAlice.bid({ + .account = alice, + .bidMin = IOUAmount{STAmount::cMinValue, STAmount::cMinOffset}, + })); + // Pay slightly higher price + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{tiny * Number{105, -2}})); + // The purchase price is still too small to affect the total + // tokens + BEAST_EXPECT(ammAlice.expectBalances( + MPT(ammAlice[0])(10'000'000'000), USD(10'000), ammAlice.tokens())); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + + // Reset auth account + testAMM( + [&](AMM& ammAlice, Env& env) { + env(ammAlice.bid({ + .account = alice, + .bidMin = IOUAmount{100}, + .authAccounts = {carol}, + })); + BEAST_EXPECT(ammAlice.expectAuctionSlot({carol})); + env(ammAlice.bid({.account = alice, .bidMin = IOUAmount{100}})); + BEAST_EXPECT(ammAlice.expectAuctionSlot({})); + Account bob("bob"); + Account dan("dan"); + fund(env, {bob, dan}, XRP(1'000)); + env(ammAlice.bid({ + .account = alice, + .bidMin = IOUAmount{100}, + .authAccounts = {bob, dan}, + })); + BEAST_EXPECT(ammAlice.expectAuctionSlot({bob, dan})); + }, + {{AMMMPT(10'000'000'000), USD(10'000)}}); + + // Bid all tokens, still own the slot and trade at a discount + { + Env env(*this); + env.fund(XRP(2'000), gw, alice, bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 2'000'000'000, + .flags = MPTDEXFlags}); + fund(env, gw, {alice, bob}, {USD(2'000)}, Fund::TokenOnly); + AMM amm(env, gw, BTC(1'000'000'000), USD(1'010), false, 1'000); + auto const lpIssue = amm.lptIssue(); + env.trust(STAmount{lpIssue, 500}, alice); + env.trust(STAmount{lpIssue, 50}, bob); + env(pay(gw, alice, STAmount{lpIssue, 500})); + env(pay(gw, bob, STAmount{lpIssue, 50})); + // Alice doesn't have anymore lp tokens + env(amm.bid({.account = alice, .bidMin = 500})); + BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{500})); + BEAST_EXPECT(expectHolding(env, alice, STAmount{lpIssue, 0})); + // But trades with the discounted fee since she still owns the slot. + // Alice pays ~10011 MPT in fees + env(pay(alice, bob, USD(10)), path(~USD), sendmax(BTC(11'000'000))); + BEAST_EXPECT(amm.expectBalances( + BTC(1'010'010'011), USD(1'000), IOUAmount{1'004'487'562112089, -9})); + + // Bob pays the full fee ~0.1USD + env(pay(bob, alice, BTC(10'000'000)), path(~MPT(BTC)), sendmax(USD(11))); + + BEAST_EXPECT(amm.expectBalances( + BTC(1'000'010'011), + STAmount{USD, UINT64_C(1'010'10090898081), -11}, + IOUAmount{1'004'487'562112089, -9})); + } + + // preflight tests + { + Env env(*this, features); + env.fund(XRP(2'000), gw, alice, bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 2'000, + .flags = MPTDEXFlags}); + AMM amm(env, gw, XRP(1'000), BTC(1'010), false, 1'000); + Json::Value const tx = amm.bid({.account = alice, .bidMin = 500}); + + { + auto jtx = env.jt(tx, seq(1), fee(10)); + env.app().config().features.erase(featureMPTokensV2); + PreflightContext const pfctx( + env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); + auto pf = AMMBid::checkExtraFeatures(pfctx); + BEAST_EXPECT(pf == false); + env.app().config().features.insert(featureMPTokensV2); + } + + { + auto jtx = env.jt(tx, seq(1), fee(10)); + jtx.jv["Asset2"]["currency"] = "XRP"; + jtx.jv["Asset2"].removeMember("mpt_issuance_id"); + jtx.stx = env.ust(jtx); + PreflightContext const pfctx( + env.app(), *jtx.stx, env.current()->rules(), tapNONE, env.journal); + auto pf = AMMBid::preflight(pfctx); + BEAST_EXPECT(pf == temBAD_AMM_TOKENS); + } + } + } + + void + testClawback() + { + testcase("Clawback"); + using namespace jtx; + + Env env(*this); + env.fund(XRP(2'000), gw, alice); + MPT const BTC = MPTTester( + {.env = env, .issuer = gw, .holders = {alice}, .transferFee = 1'500, .pay = 40'000}); + + // alice creates AMM + AMM const amm(env, alice, XRP(1'000), BTC(1'000)); + + // gw owns MPTIssuance, not allowed to set asfAllowTrustLineClawback + env(fset(gw, asfAllowTrustLineClawback), ter(tecOWNERS)); + } + + void + testClawbackFromAMMAccount(FeatureBitset features) + { + testcase("test clawback from AMM account"); + using namespace jtx; + + Env env(*this, features); + env.fund(XRP(1'000), gw); + env(fset(gw, asfAllowTrustLineClawback)); + fund(env, gw, {alice}, XRP(1'000), {USD(1'000)}, Fund::Acct); + + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + // to clawback from AMM account, must use AMMClawback instead of + // Clawback + auto const err = features[featureSingleAssetVault] ? tecPSEUDO_ACCOUNT : tecAMM_ACCOUNT; + AMM const amm(env, gw, XRP(100), BTC(100)); + auto amount = amountFromString(amm.lptIssue(), "10"); + env(claw(gw, amount), ter(err)); + + AMM const amm1(env, alice, USD(100), BTC(200)); + auto amount1 = amountFromString(amm1.lptIssue(), "10"); + env(claw(gw, amount1), ter(err)); + } + + void + testInvalidAMMPayment() + { + testcase("Invalid AMM Payment"); + using namespace jtx; + using namespace jtx::paychan; + using namespace std::chrono; + using namespace std::literals::chrono_literals; + + // Can't pay into AMM account. + // Can't pay out since there is no keys + for (auto const& acct : {gw, alice}) + { + { + Env env(*this); + fund(env, gw, {alice, carol}, XRP(1'000)); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = MPTDEXFlags}); + // XRP balance is below reserve + AMM const ammAlice(env, acct, XRP(10), BTC(10)); + // Pay below reserve + env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); + // Pay above reserve + env(pay(carol, ammAlice.ammAccount(), XRP(300)), ter(tecNO_PERMISSION)); + // Pay MPT + env(pay(carol, ammAlice.ammAccount(), BTC(10)), ter(tecNO_PERMISSION)); + } + + { + Env env(*this); + fund(env, gw, {alice, carol}, XRP(10'000'000)); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 20'000, + .flags = MPTDEXFlags}); + // XRP balance is above reserve + AMM const ammAlice(env, acct, XRP(1'000'000), BTC(10'000)); + // Pay below reserve + env(pay(carol, ammAlice.ammAccount(), XRP(10)), ter(tecNO_PERMISSION)); + // Pay above reserve + env(pay(carol, ammAlice.ammAccount(), XRP(1'000'000)), ter(tecNO_PERMISSION)); + // Pay MPT + env(pay(carol, ammAlice.ammAccount(), BTC(1'000)), ter(tecNO_PERMISSION)); + } + } + + // Can't pay into AMM with escrow. + testAMM( + [&](AMM& ammAlice, Env& env) { + env(escrow::create(carol, ammAlice.ammAccount(), MPT(ammAlice[1])(1)), + escrow::condition(escrow::cb1), + escrow::finish_time(env.now() + 1s), + escrow::cancel_time(env.now() + 2s), + fee(1'500), + ter(tecNO_PERMISSION)); + + env(escrow::create(carol, ammAlice.ammAccount(), XRP(1)), + escrow::condition(escrow::cb1), + escrow::finish_time(env.now() + 1s), + escrow::cancel_time(env.now() + 2s), + fee(1'500), + ter(tecNO_PERMISSION)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Can't pay into AMM with paychan. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const pk = carol.pk(); + auto const settleDelay = 10s; + NetClock::time_point const cancelAfter = + env.current()->header().parentCloseTime + 20s; + env(create( + carol, + ammAlice.ammAccount(), + MPT(ammAlice[1])(1'000), + settleDelay, + pk, + cancelAfter), + ter(telENV_RPC_FAILED)); + + env(create(carol, ammAlice.ammAccount(), XRP(1'000), settleDelay, pk, cancelAfter), + ter(tecNO_PERMISSION)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Can't pay into AMM with checks. + testAMM( + [&](AMM& ammAlice, Env& env) { + env(check::create(env.master.id(), ammAlice.ammAccount(), XRP(100)), + ter(tecNO_PERMISSION)); + + env(check::create(env.master.id(), ammAlice.ammAccount(), MPT(ammAlice[1])(100)), + ter(tecNO_PERMISSION)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + // Pay amounts close to one side of the pool + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const& BTC = MPT(ammAlice[1]); + // Can't consume whole pool + env(pay(alice, carol, USD(100)), + path(~USD), + sendmax(BTC(1'000'000'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, BTC(100'000'000)), + path(~BTC), + sendmax(USD(1'000'000'000)), + ter(tecPATH_PARTIAL)); + // Overflow + env(pay(alice, carol, STAmount{USD, UINT64_C(99'999999999), -9}), + path(~USD), + sendmax(BTC(1'000'000'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, STAmount{USD, UINT64_C(999'99999999), -8}), + path(~USD), + sendmax(BTC(1'000'000'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, BTC(99'999'999)), + path(~BTC), + sendmax(USD(1'000'000'000)), + ter(tecPATH_PARTIAL)); + // Sender doesn't have enough funds + env(pay(alice, carol, USD(99.99)), + path(~USD), + sendmax(BTC(1'000'000'000)), + ter(tecPATH_PARTIAL)); + env(pay(alice, carol, BTC(99'990'000)), + path(~BTC), + sendmax(USD(1'000'000'000)), + ter(tecPATH_PARTIAL)); + }, + {{USD(100), AMMMPT(100'000'000)}}); + + // Globally locked MPT. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + BTC.set({.flags = tfMPTLock}); + + env(pay(alice, carol, BTC(1)), + path(~static_cast(BTC)), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(XRP(10)), + ter(tecPATH_DRY)); + env(pay(alice, carol, XRP(1)), + path(~XRP), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(BTC(10)), + ter(tecPATH_DRY)); + } + + // Individually locked MPT destination account. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + BTC.set({.holder = carol, .flags = tfMPTLock}); + + env(pay(alice, carol, BTC(1)), + path(~static_cast(BTC)), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(XRP(10)), + ter(tecPATH_DRY)); + } + + // Individually locked MPT source account + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + BTC.set({.holder = alice, .flags = tfMPTLock}); + + env(pay(alice, carol, XRP(1)), + path(~XRP), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(BTC(10)), + ter(tecPATH_DRY)); + } + + // lock on both sides + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM const ammAlice(env, alice, ETH(10'000), BTC(10'000)); + BTC.set({.holder = carol, .flags = tfMPTLock}); + BTC.set({.holder = alice, .flags = tfMPTLock}); + ETH.set({.holder = carol, .flags = tfMPTLock}); + ETH.set({.holder = alice, .flags = tfMPTLock}); + + env(pay(alice, carol, ETH(1)), + path(~MPT(ETH)), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(BTC(10)), + ter(tecPATH_DRY)); + + env(pay(alice, carol, BTC(1)), + path(~MPT(BTC)), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(ETH(10)), + ter(tecPATH_DRY)); + } + + // Individually locked AMM MPT + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + BTC.set({.holder = ammAlice.ammAccount(), .flags = tfMPTLock}); + + env(pay(alice, carol, XRP(1)), + path(~XRP), + txflags(tfPartialPayment | tfNoRippleDirect), + sendmax(BTC(10)), + ter(tecPATH_DRY)); + } + } + + void + testBasicPaymentEngine() + { + testcase("Basic Payment"); + using namespace jtx; + + // Payment 100MPT for 100XRP. + // Force one path with tfNoRippleDirect. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + env.fund(XRP(30'000), bob); + env.close(); + env(pay(bob, carol, MPT(ammAlice[1])(100)), + path(~MPT(ammAlice[1])), + sendmax(XRP(100)), + txflags(tfNoRippleDirect)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'000), ammAlice.tokens())); + // Initial balance + 100 + env.require(balance(carol, carolMPT + MPT(ammAlice[1])(100))); + // Initial balance 30,000 - 100(sendmax) - 10(tx fee) + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + }, + {{XRP(10'000), AMMMPT(10'100)}}); + + // Payment 100IOU/MPT for 100IOU/MPT. Test IOU/MPT mix. + // Force one path with tfNoRippleDirect. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10100)); + auto carolBTC = env.balance(carol, BTC); + auto bobUSD = env.balance(bob, USD); + env(pay(bob, carol, BTC(100)), + path(~BTC), + sendmax(USD(100)), + txflags(tfNoRippleDirect | tfPartialPayment)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'100), BTC(10'000), ammAlice.tokens())); + env.require(balance(carol, carolBTC + BTC(100))); + env.require(balance(bob, bobUSD - USD(100))); + }; + testHelper2TokensMix(test); + } + + // Payment 100MPT for 100XRP, use default path. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + env.fund(XRP(30'000), bob); + env.close(); + env(pay(bob, carol, MPT(ammAlice[1])(100)), sendmax(XRP(100))); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'000), ammAlice.tokens())); + // Initial balance + 100 + env.require(balance(carol, carolMPT + MPT(ammAlice[1])(100))); + // Initial balance 30,000 - 100(sendmax) - 10(tx fee) + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + }, + {{XRP(10'000), AMMMPT(10'100)}}); + + // Payment 100IOU/MPT for 100IOU/MPT using default path. + // Test IOU/MPT mix. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10100)); + auto carolBTC = env.balance(carol, BTC); + auto bobUSD = env.balance(bob, USD); + env(pay(bob, carol, BTC(100)), sendmax(USD(100))); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'100), BTC(10'000), ammAlice.tokens())); + env.require(balance(carol, carolBTC + BTC(100))); + env.require(balance(bob, bobUSD - USD(100))); + }; + testHelper2TokensMix(test); + } + + // This payment is identical to above. While it has + // both default path and path, activeStrands has one path. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + env.fund(XRP(30'000), bob); + env.close(); + env(pay(bob, carol, MPT(ammAlice[1])(100)), + path(~MPT(ammAlice[1])), + sendmax(XRP(100))); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'000), ammAlice.tokens())); + // Initial balance + 100 + env.require(balance(carol, carolMPT + MPT(ammAlice[1])(100))); + // Initial balance 30,000 - 100(sendmax) - 10(tx fee) + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - txfee(env, 1))); + }, + {{XRP(10'000), AMMMPT(10'100)}}); + + // Test MPT/IOU combination for the case above. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10100)); + auto carolBTC = env.balance(carol, BTC); + auto bobUSD = env.balance(bob, USD); + env(pay(bob, carol, BTC(100)), path(~BTC), sendmax(USD(100))); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'100), BTC(10'000), ammAlice.tokens())); + env.require(balance(carol, carolBTC + BTC(100))); + env.require(balance(bob, bobUSD - USD(100))); + }; + testHelper2TokensMix(test); + } + + // Payment with limitQuality set. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto carolMPT = env.balance(carol, MPT(ammAlice[1])); + env.fund(jtx::XRP(30'000), bob); + env.close(); + // Pays 10MPT for 10XRP. A larger payment of ~99.11MPT/100XRP + // would have been sent has it not been for limitQuality. + env(pay(bob, carol, MPT(ammAlice[1])(100)), + path(~MPT(ammAlice[1])), + sendmax(XRP(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'010), MPT(ammAlice[1])(10'000), ammAlice.tokens())); + // Initial balance + 10(limited by limitQuality) + env.require(balance(carol, carolMPT + MPT(ammAlice[1])(10))); + // Initial balance 30,000 - 10(limited by limitQuality) - 10(tx + // fee) + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + + // Fails because of limitQuality. Would have sent + // ~98.91MPT/110XRP has it not been for limitQuality. + env(pay(bob, carol, MPT(ammAlice[1])(100)), + path(~MPT(ammAlice[1])), + sendmax(XRP(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality), + ter(tecPATH_DRY)); + env.close(); + }, + {{XRP(10'000), AMMMPT(10'010)}}); + + // Payment with limitQuality set. MPT/IOU combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10010)); + auto carolBTC = env.balance(carol, BTC); + auto bobUSD = env.balance(bob, USD); + env(pay(bob, carol, BTC(100)), + path(~BTC), + sendmax(USD(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(USD(10'010), BTC(10'000), ammAlice.tokens())); + env.require(balance(carol, carolBTC + BTC(10))); + env.require(balance(bob, bobUSD - USD(10))); + + env(pay(bob, carol, BTC(100)), + path(~BTC), + sendmax(USD(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality), + ter(tecPATH_DRY)); + env.close(); + }; + testHelper2TokensMix(test); + } + + // Payment with limitQuality and transfer fee set. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, bob, carol); + env.close(); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 10'000, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + auto ammAlice = AMM(env, alice, XRP(10'000), BTC(10'010'000'000'000'000)); + env.close(); + auto carolMPT = env.balance(carol, MPT(BTC)); + // Pays 10'000'000'000'000MPT for 10XRP. A larger payment of + // ~99'110'000'000'000MPT/100XRP would have been sent has it not + // been for limitQuality and the transfer fee. + env(pay(bob, carol, BTC(100'000'000'000'000)), + path(~MPT(BTC)), + sendmax(XRP(110)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'010), BTC(10'000'000'000'000'000), ammAlice.tokens())); + // 10'000'000'000'000MPT - 10% transfer fee + env.require(balance(carol, carolMPT + BTC(9'090'909'090'909))); + BEAST_EXPECT(expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(10) - txfee(env, 1))); + } + + // Payment with limitQuality and transfer fee set. MPT/IOU combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1({ + .env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000 + //.transferFee = 10'000 + }); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 300'000'000'000'000'000, + .transferFee = 10'000}); + + env(pay(gw, alice, BTC(30'000'000'000'000'000))); + env(pay(gw, bob, BTC(30'000'000'000'000'000))); + env(pay(gw, carol, BTC(30'000'000'000'000'000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10'000), BTC(10'010'000'000'000'000)); + auto carolBTC = env.balance(carol, BTC); + auto bobUSD = env.balance(bob, USD); + env(pay(bob, carol, BTC(100'000'000'000'000)), + path(~BTC), + sendmax(USD(110)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + USD(10'010), BTC(10'000'000'000'000'000), ammAlice.tokens())); + env.require(balance(carol, carolBTC + BTC(9'090'909'090'909))); + env.require(balance(bob, bobUSD - USD(10))); + }; + testHelper2TokensMix(test); + } + + // Fail when partial payment is not set. + testAMM( + [&](AMM& ammAlice, Env& env) { + env.fund(jtx::XRP(30'000), bob); + env.close(); + env(pay(bob, carol, MPT(ammAlice[1])(100)), + path(~MPT(ammAlice[1])), + sendmax(XRP(100)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + // Fail when partial payment is not set. MPT/IOU combination. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(30'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000'000}); + + env(pay(gw, alice, BTC(50000))); + env(pay(gw, bob, BTC(50000))); + env(pay(gw, carol, BTC(50000))); + env(pay(gw, alice, USD(50000))); + env(pay(gw, bob, USD(50000))); + env(pay(gw, carol, USD(50000))); + env.close(); + + auto ammAlice = AMM(env, alice, USD(10000), BTC(10000)); + env(pay(bob, carol, BTC(100)), + path(~BTC), + sendmax(USD(100)), + txflags(tfNoRippleDirect), + ter(tecPATH_PARTIAL)); + }; + testHelper2TokensMix(test); + } + + // Non-default path (with AMM) has a better quality than default path. + // The max possible liquidity is taken out of non-default + // path ~29.9e14XRP/29.9e14ETH, ~29.9e14ETH/~29.99e14btc. The rest + // is taken from the offer. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 3'000'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 3'000'000'000'000'000'000, + .flags = MPTDEXFlags}); + env.fund(XRP(1'000), bob); + env.close(); + auto ammETH_XRP = AMM(env, alice, XRP(10'000), ETH(1'000'000'000'000'000'000)); + auto ammBTC_ETH = + AMM(env, alice, ETH(1'000'000'000'000'000'000), BTC(1'000'000'000'000'000'000)); + env(offer(alice, XRP(101), BTC(10'000'000'000'000'000)), txflags(tfPassive)); + env.close(); + env(pay(bob, carol, BTC(10'000'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(XRP(102)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(ammETH_XRP.expectBalances( + XRPAmount(10'030'082'730), ETH(9'970'00749812546872), ammETH_XRP.tokens())); + + BEAST_EXPECT(ammBTC_ETH.expectBalances( + BTC(9'970'09727766213961), ETH(10'029'99250187453128), ammBTC_ETH.tokens())); + + Amounts const expectedAmounts = Amounts{XRPAmount(30'201'749), BTC(29'90272233786039)}; + + BEAST_EXPECT(expectOffers(env, alice, 1, {{expectedAmounts}})); + + // Initial (30,000 + 100)e14 + env.require(balance(carol, BTC(3'010'000'000'000'000'000))); + // Initial 1,000 - 30082730(AMM pool) - 70798251(offer) - 10(tx fee) + BEAST_EXPECT(expectLedgerEntryRoot( + env, + bob, + XRP(1'000) - XRPAmount{30'082'730} - XRPAmount{70'798'251} - txfee(env, 1))); + } + + // Default path (with AMM) has a better quality than a + // non-default path. + // The max possible liquidity is taken out of default + // path ~49XRP/49e14BTC. The rest is taken from the offer. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 3'000'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 1'000'000'000'000'000'000, + .flags = MPTDEXFlags}); + auto ammAlice = AMM(env, alice, XRP(10'000), BTC(1'000'000'000'000'000'000)); + env.fund(XRP(1'000), bob); + env.close(); + env(offer(alice, XRP(101), ETH(10'000'000'000'000'000)), txflags(tfPassive)); + env.close(); + env(offer(alice, ETH(10'000'000'000'000'000), BTC(10'000'000'000'000'000)), + txflags(tfPassive)); + env.close(); + env(pay(bob, carol, BTC(10'000'000'000'000'000)), + path(~MPT(ETH), ~MPT(BTC)), + sendmax(XRP(102)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount(10'050'238'637), BTC(9'950'01249687578120), ammAlice.tokens())); + BEAST_EXPECT(expectOffers( + env, + alice, + 2, + {{Amounts{XRPAmount(50'487'378), ETH(49'98750312421880)}, + Amounts{ETH(49'98750312421880), BTC(49'98750312421880)}}})); + // Initial (30,000 + 100)e14 + env.require(balance(carol, BTC(30'100'00000000000000))); + // Initial 1,000 - 50238637(AMM pool) - 50512622(offer) - 10(tx + // fee) + BEAST_EXPECT(expectLedgerEntryRoot( + env, + bob, + XRP(1'000) - XRPAmount{50'238'637} - XRPAmount{50'512'622} - txfee(env, 1))); + } + + // Default path with AMM and Order Book offer. AMM is consumed first, + // remaining amount is consumed by the offer. + { + Env env(*this); + fund(env, gw, {alice, bob, carol}, XRP(30'000)); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'100'000'000'000'000)); + env(offer(bob, XRP(100), MPT(ammAlice[1])(100'000'000'000'000)), txflags(tfPassive)); + env.close(); + env(pay(alice, carol, MPT(ammAlice[1])(200'000'000'000'000)), + sendmax(XRP(200)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'100), MPT(ammAlice[1])(10'000'000000000001), ammAlice.tokens())); + env.require(balance(carol, MPT(ammAlice[1])(30'199'999999999999))); + + // Initial 30,000 - 10000(AMM pool LP) - 100(AMMoffer) - + // - 100(offer) - 10(tx fee) - 10(tx fee of MPTTester init as + // holder) - one reserve + BEAST_EXPECT(expectLedgerEntryRoot( + env, + alice, + XRP(30'000) - XRP(10'000) - XRP(100) - XRP(100) - ammCrtFee(env) - + 2 * txfee(env, 1))); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + // Default path with AMM and Order Book offer. + // Order Book offer is consumed first. + // Remaining amount is consumed by AMM. + { + Env env(*this); + fund(env, gw, {alice, bob, carol}, XRP(20'000)); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 2'000, + .flags = MPTDEXFlags}); + env(offer(bob, XRP(50), BTC(150)), txflags(tfPassive)); + env.close(); + AMM const ammAlice(env, alice, XRP(1'000), BTC(1'050)); + env(pay(alice, carol, BTC(200)), sendmax(XRP(200)), txflags(tfPartialPayment)); + BEAST_EXPECT(ammAlice.expectBalances(XRP(1'050), BTC(1'000), ammAlice.tokens())); + env.require(balance(carol, BTC(2'200))); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + // Offer crossing XRP/MPT + { + Env env(*this); + fund(env, gw, {alice, bob, carol}, XRP(30'000)); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000, + .flags = MPTDEXFlags}); + AMM ammAlice(env, alice, XRP(10'000), BTC(10'100)); + env(offer(bob, MPT(ammAlice[1])(100), XRP(100))); + env.close(); + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'100), MPT(ammAlice[1])(10'000), ammAlice.tokens())); + // Initial 30,000 + 100 + env.require(balance(bob, MPT(ammAlice[1])(30'100))); + // Initial 30,000 - 100(offer) - 10(tx fee) - 1(tx fee for MPTTester + // holder) + BEAST_EXPECT( + expectLedgerEntryRoot(env, bob, XRP(30'000) - XRP(100) - 2 * txfee(env, 1))); + BEAST_EXPECT(expectOffers(env, bob, 0)); + } + + // Offer crossing MPT/MPT and transfer rate + // Single path AMM offer + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 25'000, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 25'000, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammAlice(env, alice, BTC(1'000'000'000'000'000), ETH(1'100'000'000'000'000)); + // This offer succeeds to cross pre- and post-amendment + // because the strand's out amount is small enough to match + // limitQuality value and limitOut() function in StrandFlow + // doesn't require an adjustment to out value. + env(offer(carol, ETH(100'000'000'000'000), BTC(100'000'000'000'000))); + env.close(); + // No transfer fee + BEAST_EXPECT(ammAlice.expectBalances( + BTC(1'100'000'000'000'000), ETH(1'000'000'000'000'000), ammAlice.tokens())); + // Initial 30,000'000'000'000'000 - 100'000'000'000'000(offer)-25 % + // transfer fee + env.require(balance(carol, BTC(29'875'000'000'000'000))); + // Initial 30,000'000'000'000'000 + 100'000'000'000'000(offer) + env.require(balance(carol, ETH(30'100'000'000'000'000))); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + // Single-path AMM offer + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, bob, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 100, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const amm(env, alice, XRP(1'000), BTC(500'000'000'000'000)); + env(offer(carol, XRP(100), BTC(55'000'000'000'000))); + env.close(); + + BEAST_EXPECT( + amm.expectBalances(XRPAmount(909'090'909), BTC(550'000000055001), amm.tokens())); + // Offer ~91XRP/49.99e12BTC + BEAST_EXPECT(expectOffers( + env, carol, 1, {{Amounts{XRPAmount{9'090'909}, BTC(4'999999950000)}}})); + // Carol pays 0.1% fee on 50'000000055000BTC = 50'000000055BTC + env.require(balance(carol, BTC(29'949'949'999'944'943))); + } + + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .transferFee = 100, + .pay = 3'000'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const amm(env, alice, XRP(1'000), BTC(50'000'000'000'000'000)); + env(offer(carol, XRP(10), BTC(5'500'000'000'000'000))); + env.close(); + + BEAST_EXPECT(amm.expectBalances(XRP(990), BTC(505'05050505050506), amm.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + // Multi-path AMM offer + { + Env env(*this); + Account const ed("ed"); + env.fund(XRP(30'000), gw, alice, bob, carol, ed); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 20'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = 25'000, + .pay = 20'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammAlice( + env, alice, BTC(10'000'000'000'000'000), ETH(11'000'000'000'000'000)); + + env(offer(bob, BTC(100'000'000'000'000), XRP(10)), txflags(tfPassive)); + env(offer(ed, XRP(10), ETH(100'000'000'000'000)), txflags(tfPassive)); + env.close(); + env(offer(carol, ETH(1'000'000'000'000'000), BTC(1'000'000'000'000'000))); + env.close(); + + BEAST_EXPECT(ammAlice.expectBalances( + BTC(1'060'6848287928033), ETH(1'037'0658372213574), ammAlice.tokens())); + // Consumed offer ~72.93e13ETH/72.93e13BTC + BEAST_EXPECT(expectOffers( + env, carol, 1, {Amounts{ETH(27'0658372213574), BTC(27'0658372213575)}})); + BEAST_EXPECT(expectOffers(env, bob, 0)); + BEAST_EXPECT(expectOffers(env, ed, 0)); + + env.require(balance(carol, BTC(19'116'439'640'089'955))); + env.require(balance(carol, ETH(20'729'341'627'786'426))); + env.require(balance(bob, BTC(20'100'000'000'000'000))); + env.require(balance(ed, ETH(19'875'000'000'000'000))); + } + + // Payment and transfer fee + // Scenario: + // Bob sends 125BTC to pay 80EUR to Carol + // Payment execution: + // bob's 125BTC/1.25 = 100BTC + // 100BTC/100EUR AMM offer + // 100EUR/1.25 = 80EUR paid to carol + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, bob, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 30'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .pay = 30'000, + .flags = MPTDEXFlags}); + AMM const ammAlice(env, alice, BTC(1'000), ETH(1'100)); + env(rate(gw, 1.25)); + env.close(); + env(pay(bob, carol, ETH(100)), + path(~MPT(ETH)), + sendmax(BTC(125)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'100), ETH(1'000), ammAlice.tokens())); + env.require(balance(bob, BTC(29'875))); + env.require(balance(carol, ETH(30'080))); + } + + // Payment and transfer fee, multiple steps + // Scenario: + // Dan's offer 200CAN/200GBP + // AMM 1000GBP/10125ETH + // Ed's offer 200ETH/BTC + // Bob sends 195.3125CAN to pay 100BTC to Carol + // Payment execution: + // bob's 195.3125CAN/1.25 = 156.25CAN -> dan's offer + // 156.25CAN/156.25GBP 156.25GBP/1.25 = 125GBP -> AMM's offer + // 125GBP/125ETH 125ETH/1.25 = 100ETH -> ed's offer + // 100ETH/100BTC 100BTC/1.25 = 80BTC paid to carol + { + Env env(*this); + Account const dan("dan"); + Account const ed("ed"); + env.fund(XRP(30'000), gw, alice, bob, carol, dan, ed); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .transferFee = 25'000, + .pay = 30'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .transferFee = 25'000, + .pay = 30'000, + .flags = MPTDEXFlags}); + MPTTester const CAN( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .transferFee = 25'000, + .pay = 2'000'000, + .flags = MPTDEXFlags}); + MPTTester const GBP( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, ed}, + .transferFee = 25'000, + .pay = 3'000'000, + .flags = MPTDEXFlags}); + AMM const ammAlice(env, alice, GBP(1'000'000), ETH(10'125)); + env(pay(gw, bob, CAN(1'953'125))); + env.close(); + env(offer(dan, CAN(2'000'000), GBP(20'000))); + env(offer(ed, ETH(200), BTC(200))); + env.close(); + env(pay(bob, carol, BTC(100)), + path(~MPT(GBP), ~MPT(ETH), ~MPT(BTC)), + sendmax(CAN(1'953'125)), + txflags(tfPartialPayment)); + env.close(); + env.require(balance(bob, CAN(2'000'000))); + env.require(balance(dan, CAN(3'562'500))); + env.require(balance(dan, GBP(2'984'375))); + + BEAST_EXPECT(ammAlice.expectBalances(GBP(1'012'500), ETH(10'000), ammAlice.tokens())); + env.require(balance(ed, ETH(30'100))); + env.require(balance(ed, BTC(29'900))); + env.require(balance(carol, BTC(30'080))); + } + + // Pay amounts close to one side of the pool + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const& BTC = MPT(ammAlice[1]); + env(pay(alice, carol, BTC(9999)), + path(~BTC), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(tesSUCCESS)); + env(pay(alice, carol, BTC(10'000)), + path(~BTC), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(tesSUCCESS)); + env(pay(alice, carol, XRP(100)), + path(~XRP), + sendmax(BTC(100)), + txflags(tfPartialPayment), + ter(tesSUCCESS)); + env(pay(alice, carol, STAmount{xrpIssue(), 99'999'900}), + path(~XRP), + sendmax(BTC(100)), + txflags(tfPartialPayment), + ter(tesSUCCESS)); + }, + {{XRP(100), AMMMPT(10'000)}}); + + // Multiple paths/steps + { + Env env(*this); + env.fund(XRP(100'000), gw, alice); + env.fund(XRP(1'000), bob, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 500'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 500'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 500'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const EUR( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 500'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const xrp_eur(env, alice, XRP(10'100), EUR(100'000'000'000'000'000)); + AMM const eur_btc( + env, alice, EUR(100'000'000'000'000'000), BTC(102'000'000'000'000'000)); + AMM const btc_usd( + env, alice, BTC(101'000'000'000'000'000), USD(100'000'000'000'000'000)); + AMM const xrp_usd(env, alice, XRP(10'150), USD(102'000'000'000'000'000)); + AMM const xrp_eth(env, alice, XRP(10'000), ETH(101'000'000'000'000'000)); + AMM const eth_eur( + env, alice, ETH(109'000'000'000'000'000), EUR(110'000'000'000'000'000)); + AMM const eur_usd( + env, alice, EUR(101'000'000'000'000'000), USD(100'000'000'000'000'000)); + env(pay(bob, carol, USD(1'000'000'000'000'000)), + path(~MPT(EUR), ~MPT(BTC), ~MPT(USD)), + path(~MPT(USD)), + path(~MPT(ETH), ~MPT(EUR), ~MPT(USD)), + sendmax(XRP(200))); + + BEAST_EXPECT(xrp_eth.expectBalances( + XRPAmount(10'026'208'900), ETH(10'073'6577924447994), xrp_eth.tokens())); + BEAST_EXPECT(eth_eur.expectBalances( + ETH(10'926'3422075552006), EUR(10'973'5423207873690), eth_eur.tokens())); + BEAST_EXPECT(eur_usd.expectBalances( + EUR(10'126'4576792126310), USD(9'973'9315171207179), eur_usd.tokens())); + // XRP-USD path + // This path provides ~73.9e12USD/74.1XRP + BEAST_EXPECT(xrp_usd.expectBalances( + XRPAmount(10'224'106'246), USD(10'126'0684828792821), xrp_usd.tokens())); + + // XRP-EUR-BTC-USD + // This path doesn't provide any liquidity due to how + // offers are generated in multi-path. + // Analytical solution shows a different distribution: + // XRP-EUR-BTC-USD 11.6e12USD/11.64XRP, + // XRP-USD 60.7e12USD/60.8XRP, + // XRP-ETH-EUR-USD 27.6e12USD/27.6XRP + BEAST_EXPECT(xrp_eur.expectBalances( + XRP(10'100), EUR(100'000'000'000'000'000), xrp_eur.tokens())); + BEAST_EXPECT(eur_btc.expectBalances( + EUR(100'000'000'000'000'000), BTC(102'000'000'000'000'000), eur_btc.tokens())); + BEAST_EXPECT(btc_usd.expectBalances( + BTC(101'000'000'000'000'000), USD(100'000'000'000'000'000), btc_usd.tokens())); + env.require(balance(carol, USD(501'000'000'000'000'000))); + } + + // Dependent AMM + { + Env env(*this); + env.fund(XRP(40'000), gw, alice); + env.fund(XRP(1'000), bob, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 50'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 50'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 50'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const EUR( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 50'000'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const xrp_eur(env, alice, XRP(10'100), EUR(10'000'000'000'000'000)); + AMM const eur_btc(env, alice, EUR(10'000'000'000'000'000), BTC(10'200'000'000'000'000)); + AMM const btc_usd(env, alice, BTC(10'100'000'000'000'000), USD(10'000'000'000'000'000)); + AMM const xrp_eth(env, alice, XRP(10'000), ETH(10'100'000'000'000'000)); + AMM const eth_eur(env, alice, ETH(10'900'000'000'000'000), EUR(11'000'000'000'000'000)); + env(pay(bob, carol, USD(100'000'000'000'000)), + path(~MPT(EUR), ~MPT(BTC), ~MPT(USD)), + path(~MPT(ETH), ~MPT(EUR), ~MPT(BTC), ~MPT(USD)), + sendmax(XRP(200))); + + BEAST_EXPECT(xrp_eur.expectBalances( + XRPAmount(10'118'738'472), EUR(9'981'544436337981), xrp_eur.tokens())); + BEAST_EXPECT(eur_btc.expectBalances( + EUR(10'101'160967851758), BTC(10'097'914269680647), eur_btc.tokens())); + BEAST_EXPECT(btc_usd.expectBalances( + BTC(10'202'085730319353), USD(9'900'000'000'000'000), btc_usd.tokens())); + BEAST_EXPECT(xrp_eth.expectBalances( + XRPAmount(10'082'446'397), ETH(10'017'410727780081), xrp_eth.tokens())); + BEAST_EXPECT(eth_eur.expectBalances( + ETH(10'982'589272219919), EUR(10'917'294595810261), eth_eur.tokens())); + env.require(balance(carol, USD(50'100'000'000'000'000))); + } + + // AMM offers limit + // Consuming 30 CLOB offers, results in hitting 30 AMM offers limit. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + env.fund(XRP(1'000), bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 400'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000'000'000'000'000)); + + for (int i = 0; i < 30; ++i) + env(offer(alice, ETH(1'000'000'000'000 + (10'000'000'000 * i)), XRP(1))); + // This is worse quality offer than 30 offers above. + // It will not be consumed because of AMM offers limit. + env(offer(alice, ETH(140'000'000'000'000), XRP(100))); + env(pay(bob, carol, BTC(100'000'000'000'000)), + path(~XRP, ~MPT(BTC)), + sendmax(ETH(400'000'000'000'000)), + txflags(tfPartialPayment | tfNoRippleDirect)); + + BEAST_EXPECT( + ammAlice.expectBalances(XRP(10'030), BTC(9'970'089730807592), ammAlice.tokens())); + + env.require(balance(carol, BTC(30'029'910269192408))); + BEAST_EXPECT(expectOffers(env, alice, 1, {{{ETH(140'000'000'000'000), XRP(100)}}})); + } + + // This payment is fulfilled + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + env.fund(XRP(1'000), bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 400'000'000'000'000, + .flags = MPTDEXFlags}); + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000'000'000'000'000)); + + for (int i = 0; i < 29; ++i) + env(offer(alice, ETH(1'000'000'000'000 + (10'000'000'000 * i)), XRP(1))); + // This is worse quality offer than 30 offers above. + // It will not be consumed because of AMM offers limit. + env(offer(alice, ETH(140'000'000'000'000), XRP(100))); + env(pay(bob, carol, BTC(100'000'000'000'000)), + path(~XRP, ~MPT(BTC)), + sendmax(ETH(400'000'000'000'000)), + txflags(tfPartialPayment | tfNoRippleDirect)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'101'010'102}, BTC(9'900'000'000'000'000), ammAlice.tokens())); + + env.require(balance(carol, BTC(30'100'000'000'000'000))); + BEAST_EXPECT( + expectOffers(env, alice, 1, {{{ETH(39'185857200000), XRPAmount{27'989'898}}}})); + } + + // Offer crossing with AMM and another offer. + // AMM has a better quality and is consumed first. + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + env.fund(XRP(1'000), bob); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000'000'000'000'000, + .flags = MPTDEXFlags}); + + env(offer(bob, XRP(100), BTC(100'001'000'000'000))); + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'100'000'000'000'000)); + env(offer(carol, BTC(100'000'000'000'000), XRP(100))); + + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'049'825'372}, BTC(10'049'925870493027), ammAlice.tokens())); + BEAST_EXPECT( + expectOffers(env, bob, 1, {{{XRPAmount{50'074'628}, BTC(50'075129506973)}}})); + + env.require(balance(carol, BTC(30'100'000'000'000'000))); + } + + // Individually locked MPT destination account + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + + BTC.set({.holder = carol, .flags = tfMPTLock}); + + env(pay(alice, carol, XRP(1)), + path(~XRP), + sendmax(BTC(10)), + txflags(tfNoRippleDirect | tfPartialPayment), + ter(tesSUCCESS)); + } + + // Individually locked MPT source account + { + Env env(*this); + env.fund(XRP(30'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + AMM const ammAlice(env, alice, XRP(10'000), BTC(10'000)); + + BTC.set({.holder = alice, .flags = tfMPTLock}); + + env(pay(alice, carol, BTC(1)), + path(~MPT(BTC)), + sendmax(XRP(10)), + txflags(tfNoRippleDirect | tfPartialPayment), + ter(tesSUCCESS)); + } + } + + void + testAMMTokens() + { + testcase("AMM Tokens"); + using namespace jtx; + + // Offer crossing with AMM LPTokens and XRP. + // AMM LPTokens come from MPT/XRP pool. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const token1 = ammAlice.lptIssue(); + auto priceXRP = ammAssetOut( + STAmount{XRPAmount{10'000'000'000}}, + STAmount{token1, 10'000'000}, + STAmount{token1, 5'000'000}, + 0); + // Carol places an order to buy LPTokens + env(offer(carol, STAmount{token1, 5'000'000}, priceXRP)); + // Alice places an order to sell LPTokens + env(offer(alice, priceXRP, STAmount{token1, 5'000'000})); + // Pool's LPTokens balance doesn't change + BEAST_EXPECT(ammAlice.expectBalances( + XRP(10'000), MPT(ammAlice[1])(10'000), IOUAmount{10'000'000})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{5'000'000})); + BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); + // Carol votes + ammAlice.vote(carol, 1'000); + BEAST_EXPECT(ammAlice.expectTradingFee(500)); + ammAlice.vote(carol, 0); + BEAST_EXPECT(ammAlice.expectTradingFee(0)); + // Carol bids + auto const baseFee = env.current()->fees().base; + auto const carolXRP = env.balance(carol); + env(ammAlice.bid({.account = carol, .bidMin = 100})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{4'999'900})); + BEAST_EXPECT(ammAlice.expectAuctionSlot(0, 0, IOUAmount{100})); + BEAST_EXPECT(env.balance(carol) == (carolXRP - baseFee)); + priceXRP = ammAssetOut( + STAmount{XRPAmount{10'000'000'000}}, + STAmount{token1, 9'999'900}, + STAmount{token1, 4'999'900}, + 0); + // Carol withdraws + ammAlice.withdrawAll(carol, XRP(0)); + BEAST_EXPECT(env.balance(carol) == (carolXRP - baseFee * 2 + priceXRP)); + BEAST_EXPECT(ammAlice.expectBalances( + XRPAmount{10'000'000'000} - priceXRP, + MPT(ammAlice[1])(10'000), + IOUAmount{5'000'000})); + BEAST_EXPECT(ammAlice.expectLPTokens(alice, IOUAmount{5'000'000})); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + }, + {{XRP(10000), AMMMPT(10000)}}); + + // Offer crossing with two AMM LPTokens. + // token1 comes from MPT/XRP pool. + // token2 comes from XRP/IOU pool. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + fund(env, gw, {alice, carol}, {EUR(10'000)}, Fund::TokenOnly); + AMM ammAlice1(env, alice, XRP(10'000), EUR(10'000)); + ammAlice1.deposit(carol, 1'000'000); + auto const token1 = ammAlice.lptIssue(); + auto const token2 = ammAlice1.lptIssue(); + env(offer(alice, STAmount{token1, 100}, STAmount{token2, 100}), txflags(tfPassive)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + env(offer(carol, STAmount{token2, 100}, STAmount{token1, 100})); + env.close(); + BEAST_EXPECT( + expectHolding(env, alice, STAmount{token1, 10'000'100}) && + expectHolding(env, alice, STAmount{token2, 9'999'900})); + BEAST_EXPECT( + expectHolding(env, carol, STAmount{token2, 1'000'100}) && + expectHolding(env, carol, STAmount{token1, 999'900})); + BEAST_EXPECT(expectOffers(env, alice, 0) && expectOffers(env, carol, 0)); + }, + {{XRP(10000), AMMMPT(10000)}}); + + // LPs pay LPTokens directly. Must trust set because the trust line + // is checked for the limit, which is 0 in the AMM auto-created + // trust line. + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const token1 = ammAlice.lptIssue(); + env.trust(STAmount{token1, 2'000'000}, carol); + env.close(); + ammAlice.deposit(carol, 1'000'000); + BEAST_EXPECT( + ammAlice.expectLPTokens(alice, IOUAmount{10'000'000, 0}) && + ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); + // Pool balance doesn't change, only tokens moved from + // one line to another. + env(pay(alice, carol, STAmount{token1, 100})); + env.close(); + BEAST_EXPECT( + // Alice initial token1 10,000,000 - 100 + ammAlice.expectLPTokens(alice, IOUAmount{9'999'900, 0}) && + // Carol initial token1 1,000,000 + 100 + ammAlice.expectLPTokens(carol, IOUAmount{1'000'100, 0})); + + env.trust(STAmount{token1, 20'000'000}, alice); + env.close(); + env(pay(carol, alice, STAmount{token1, 100})); + env.close(); + // Back to the original balance + BEAST_EXPECT( + ammAlice.expectLPTokens(alice, IOUAmount{10'000'000, 0}) && + ammAlice.expectLPTokens(carol, IOUAmount{1'000'000, 0})); + }, + {{XRP(10000), AMMMPT(10000)}}); + } + + void + testAmendment() + { + testcase("Amendment"); + using namespace jtx; + FeatureBitset const feature{testable_amendments() - featureMPTokensV2}; + Env env{*this, feature}; + + env.fund(XRP(30'000), gw, alice); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 10'000, + .flags = tfMPTCanClawback | tfMPTCanTransfer}); + + AMM amm(env, alice, XRP(1'000), BTC(1'000), ter(temDISABLED)); + + env(amm.bid({.bidMax = 1000}), ter(temMALFORMED)); + env(amm.bid({}), ter(temDISABLED)); + amm.vote(VoteArg{.tfee = 100, .err = ter(temDISABLED)}); + amm.withdraw(WithdrawArg{.tokens = 100, .err = ter(temMALFORMED)}); + amm.withdraw(WithdrawArg{.err = ter(temDISABLED)}); + amm.deposit(DepositArg{.asset1In = USD(100), .err = ter(temDISABLED)}); + amm.ammDelete(alice, ter(temDISABLED)); + } + + void + testAMMAndCLOB(FeatureBitset features) + { + testcase("AMMAndCLOB, offer quality change"); + using namespace jtx; + auto const gw = Account("gw"); + auto const LP1 = Account("LP1"); + auto const LP2 = Account("LP2"); + + auto prep = [&](auto const& offerCb, auto const& expectCb) { + Env env(*this, features); + env.fund(XRP(30'000'000'000), gw); + env.fund(XRP(10'000), LP1); + env.fund(XRP(10'000), LP2); + MPTTester const TST( + {.env = env, .issuer = gw, .holders = {LP1, LP2}, .flags = MPTDEXFlags}); + + env(offer(gw, XRP(11'500'000'000), TST(1'000'000'000'000'000))); + + env(offer(LP1, TST(25'000'000), XRPAmount(287'500'000))); + + // Either AMM or CLOB offer + offerCb(env, TST); + + env(offer(LP2, TST(25'000'000), XRPAmount(287'500'000))); + + expectCb(env, TST); + }; + + // If we replace AMM with an equivalent CLOB offer, which AMM generates + // when it is consumed, then the result must be equivalent, too. + STAmount lp2TSTBalance; + std::string lp2TakerGets; + std::string lp2TakerPays; + // Execute with AMM first + prep( + [&](Env& env, MPTTester TST) { AMM const amm(env, LP1, TST(25'000'000), XRP(250)); }, + [&](Env& env, MPTTester TST) { + lp2TSTBalance = env.balance(LP2, MPT(TST)); + auto const offer = getAccountOffers(env, LP2)["offers"][0u]; + lp2TakerGets = offer["taker_gets"].asString(); + lp2TakerPays = offer["taker_pays"]["value"].asString(); + }); + // Execute with CLOB offer + prep( + [&](Env& env, MPTTester TST) { + env(offer(LP1, XRPAmount{18'095'131}, TST(1'687'379)), txflags(tfPassive)); + }, + [&](Env& env, MPTTester TST) { + BEAST_EXPECT(lp2TSTBalance == env.balance(LP2, MPT(TST))); + auto const offer = getAccountOffers(env, LP2)["offers"][0u]; + BEAST_EXPECT(lp2TakerGets == offer["taker_gets"].asString()); + BEAST_EXPECT(lp2TakerPays == offer["taker_pays"]["value"].asString()); + }); + } + + void + testTradingFee(FeatureBitset features) + { + testcase("Trading Fee"); + using namespace jtx; + + // Single Deposit, 1% fee + testAMM( + [&](AMM& ammAlice, Env& env) { + // No fee + ammAlice.deposit(carol, MPT(ammAlice[1])(3'000)); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1'000})); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(3'000)); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{0})); + env.require(balance(carol, MPT(ammAlice[1])(30'000))); + // Set fee to 1% + ammAlice.vote(alice, 1'000); + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + + // Carol gets fewer LPToken ~994, because of the single deposit + // fee + ammAlice.deposit(carol, MPT(ammAlice[1])(3'000)); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{994'981155689671, -12})); + env.require(balance(carol, MPT(ammAlice[1])(27'000))); + + // Set fee to 0 + ammAlice.vote(alice, 0); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + + // Carol gets back less than the original deposit + if (!features[fixAMMv1_3]) + { + env.require(balance(carol, MPT(ammAlice[1])(29'995))); + } + else + { + env.require(balance(carol, MPT(ammAlice[1])(29'994))); + } + }, + {{USD(1000), AMMMPT(1000)}}, + 0, + std::nullopt, + {features}); + + // Single deposit with EP not exceeding specified: + // 100MPT with EP not to exceed 0.1 (AssetIn/TokensOut). 1% fee. + testAMM( + [&](AMM& ammAlice, Env& env) { + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + auto const balance = env.balance(carol, MPT(ammAlice[1])); + auto const tokensFee = ammAlice.deposit( + carol, + MPT(ammAlice[1])(1000), + std::nullopt, + STAmount{ammAlice.lptIssue(), 1, -1}); + auto const deposit = balance - env.balance(carol, MPT(ammAlice[1])); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + ammAlice.vote(alice, 0); + BEAST_EXPECT(ammAlice.expectTradingFee(0)); + auto const tokensNoFee = ammAlice.deposit(carol, deposit); + BEAST_EXPECT(tokensFee == IOUAmount(485636'0611129, -7)); + if (!features[fixAMMv1_3]) + { + BEAST_EXPECT(tokensNoFee == IOUAmount(487659'8005807, -7)); + } + else + { + BEAST_EXPECT(tokensNoFee == IOUAmount(487612'21584827, -8)); + } + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 1'000, + std::nullopt, + {features}); + + // Single deposit with EP not exceeding specified: + // 200MPT with EP not to exceed 0.002020 (AssetIn/TokensOut). 1% fee + testAMM( + [&](AMM& ammAlice, Env& env) { + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + auto const balance = env.balance(carol, MPT(ammAlice[1])); + auto const tokensFee = ammAlice.deposit( + carol, + MPT(ammAlice[1])(200), + std::nullopt, + STAmount{ammAlice.lptIssue(), 2020, -6}); + auto const deposit = balance - env.balance(carol, MPT(ammAlice[1])); + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + ammAlice.vote(alice, 0); + BEAST_EXPECT(ammAlice.expectTradingFee(0)); + auto const tokensNoFee = ammAlice.deposit(carol, deposit); + if (!features[fixAMMv1_3]) + { + BEAST_EXPECT(tokensFee == IOUAmount(98'019'80198019, -8)); + BEAST_EXPECT(tokensNoFee == IOUAmount(98'495'13933556, -8)); + } + else + { + BEAST_EXPECT(tokensFee == IOUAmount(97527'05893345, -8)); + BEAST_EXPECT(tokensNoFee == IOUAmount(98000'10293049, -8)); + } + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 1'000, + std::nullopt, + {features}); + + // Single Withdrawal, 1% fee + testAMM( + [&](AMM& ammAlice, Env& env) { + // No fee + ammAlice.deposit(carol, MPT(ammAlice[1])(3'000)); + BEAST_EXPECT(ammAlice.expectLPTokens(carol, IOUAmount{1'000})); + env.require(balance(carol, MPT(ammAlice[1])(27'000))); + // Set fee to 1% + ammAlice.vote(alice, 1'000); + BEAST_EXPECT(ammAlice.expectTradingFee(1'000)); + // Single withdrawal. Carol gets ~5USD less than deposited. + ammAlice.withdrawAll(carol, MPT(ammAlice[1])(0)); + if (!features[fixAMMv1_3]) + { + env.require(balance(carol, MPT(ammAlice[1])(29'995))); + } + else + { + env.require(balance(carol, MPT(ammAlice[1])(29'994))); + } + }, + {{USD(1000), AMMMPT(1000)}}, + 0, + std::nullopt, + {features}); + + // Withdraw with EPrice limit, 1% fee. + testAMM( + [&](AMM& ammAlice, Env& env) { + ammAlice.deposit(carol, 1'000'000); + auto const tokensFee = ammAlice.withdraw( + carol, MPT(ammAlice[1])(100), std::nullopt, IOUAmount{520, 0}); + env.require(balance(carol, MPT(ammAlice[1])(30443))); + + // Set to original pool size + auto const deposit = + env.balance(carol, MPT(ammAlice[1])) - MPT(ammAlice[1])(29'000); + ammAlice.deposit(carol, deposit); + // fee 0% + ammAlice.vote(alice, 0); + BEAST_EXPECT(ammAlice.expectTradingFee(0)); + auto const tokensNoFee = ammAlice.withdraw(carol, deposit); + if (!features[fixAMMv1_3]) + { + env.require(balance(carol, MPT(ammAlice[1])(30443))); + } + else + { + env.require(balance(carol, MPT(ammAlice[1])(30442))); + } + BEAST_EXPECT(tokensNoFee == IOUAmount(746'327'46496649, -8)); + BEAST_EXPECT(tokensFee == IOUAmount(750'588'23529411, -8)); + }, + {{XRP(10'000), AMMMPT(10'000)}}, + 1'000, + std::nullopt, + {features}); + + // Payment, 1% fee + { + Env env{*this, features}; + env.fund(XRP(30'000), gw, alice, bob, carol); + env.close(); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .pay = 30'000, + .flags = MPTDEXFlags}); + + auto const USD = gw["USD"]; + env.trust(USD(30'000), alice); + env(pay(gw, alice, USD(30'000))); + env.trust(USD(30'000), bob); + env(pay(gw, bob, USD(1'000))); + env.trust(USD(30'000), carol); + env(pay(gw, carol, USD(30'000))); + env.close(); + + AMM amm(env, alice, BTC(1000), USD(1010)); + + env.require(balance(alice, BTC(29'000))); + env.require(balance(alice, USD(28'990))); + env.require(balance(carol, BTC(30'000))); + + // Carol pays to Alice with no fee + env(pay(carol, alice, USD(10)), + path(~USD), + sendmax(BTC(10)), + txflags(tfNoRippleDirect)); + env.close(); + + // Alice has 10USD more and Carol has 10BTC less + env.require(balance(alice, BTC(29'000))); + env.require(balance(alice, USD(29'000))); + env.require(balance(carol, BTC(29'990))); + + // Set fee to 1% + amm.vote(alice, 1'000); + BEAST_EXPECT(amm.expectTradingFee(1'000)); + // Bob pays to Carol with 1% fee + env(pay(bob, carol, BTC(10)), path(~BTC), sendmax(USD(15)), txflags(tfNoRippleDirect)); + env.close(); + // Bob sends 10.1~USD to pay 10BTC + env.require(balance(bob, STAmount{USD, UINT64_C(989'8989898989899), -13})); + // Carol got 10BTC + env.require(balance(carol, BTC(30'000))); + BEAST_EXPECT(amm.expectBalances( + BTC(1'000), STAmount{USD, UINT64_C(1'010'10101010101), -11}, amm.tokens())); + } + + // Offer crossing, 0.05% fee MPT/XRP + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const BTC = MPT(ammAlice[1]); + auto const carolXRP = env.balance(carol); + auto const baseFee = env.current()->fees().base; + env(offer(carol, BTC(10), XRP(10))); + env.close(); + env.require(balance(carol, BTC(30'010))); + env.require(balance(carol, carolXRP - baseFee - XRP(10))); + + // Change pool composition back + env(offer(carol, XRP(10), BTC(10))); + env.close(); + env.require(balance(carol, BTC(30'000))); + env.require(balance(carol, carolXRP - baseFee * 2)); + + // set fee to 0.05% + ammAlice.vote(alice, 50); + BEAST_EXPECT(ammAlice.expectTradingFee(50)); + env(offer(carol, BTC(10), XRP(10))); + env.close(); + env.require(balance(carol, BTC(30'009))); + env.require(balance(carol, carolXRP - baseFee * 3 - XRPAmount(8'995'507))); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{BTC(1), XRP(1)}}})); + }, + {{XRP(1000), AMMMPT(1010)}}, + 0, + std::nullopt, + {features}); + + // Offer crossing, 0.5% fee MPT/IOU + testAMM( + [&](AMM& ammAlice, Env& env) { + auto const BTC = MPT(ammAlice[1]); + env(offer(carol, BTC(10'000'000), USD(10))); + env.close(); + env.require(balance(carol, BTC(1'020'001'000))); + env.require(balance(carol, USD(29'990))); + + // Change pool composition back + env(offer(carol, USD(10), BTC(10'000'000))); + env.close(); + env.require(balance(carol, BTC(1'010'001'000))); + env.require(balance(carol, USD(30'000))); + + // set fee to 0.5% + ammAlice.vote(alice, 500); + BEAST_EXPECT(ammAlice.expectTradingFee(500)); + env(offer(carol, BTC(10'000'000), USD(10))); + env.close(); + env.require(balance(carol, BTC(1'014'975'874))); + env.require(balance(carol, STAmount{USD, UINT64_C(29'995'02512600184), -11})); + BEAST_EXPECT(expectOffers( + env, + carol, + 1, + {{Amounts{BTC(5'025126), STAmount{USD, UINT64_C(5'025126), -6}}}})); + }, + {{USD(1000), AMMMPT(1010000000)}}, + 0, + std::nullopt, + {features}); + + // Payment with AMM and CLOB offer, 0 fee + // AMM liquidity is consumed first up to CLOB offer quality + // CLOB offer is fully consumed next + // Remaining amount is consumed via AMM liquidity + { + Env env{*this, features}; + Account const ed("ed"); + fund(env, gw, {alice, bob, carol, ed}, XRP(30'000), {USD(2'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .pay = 30'000'000000, + .flags = MPTDEXFlags}); + + env(offer(carol, BTC(5'000000), USD(5))); + AMM const ammAlice(env, alice, USD(1'005), BTC(1'000'000000)); + env(pay(bob, ed, USD(10)), + path(~USD), + sendmax(BTC(15'000000)), + txflags(tfNoRippleDirect)); + + env.require(balance(ed, USD(2'010))); + env.require(balance(bob, BTC(29'989'999999))); + BEAST_EXPECT(ammAlice.expectBalances( + BTC(1'005'000001), + STAmount{USD, UINT64_C(999'9999999999999), -13}, + ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + // Payment with AMM and CLOB offer. Same as above but with 0.25% + // fee. + { + Env env{*this, features}; + Account const ed("ed"); + fund(env, gw, {alice, bob, carol, ed}, XRP(30'000), {USD(2'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .pay = 30'000'000000, + .flags = MPTDEXFlags}); + + env(offer(carol, BTC(5'000000), USD(5))); + // Set 0.25% fee + AMM const ammAlice(env, alice, USD(1'005), BTC(1'000'000000), false, 250); + env(pay(bob, ed, USD(10)), + path(~USD), + sendmax(BTC(15'000000)), + txflags(tfNoRippleDirect)); + env.require(balance(ed, USD(2'010))); + env.require(balance(bob, BTC(29'989'987453))); + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'005'012547), USD(1'000), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + // Payment with AMM and CLOB offer. AMM has a better + // spot price quality, but 1% fee offsets that. As the result + // the entire trade is executed via LOB. + { + Env env{*this, features}; + Account const ed("ed"); + fund(env, gw, {alice, bob, carol, ed}, XRP(30'000), {USD(2'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .pay = 30'000'000000, + .flags = MPTDEXFlags}); + + env(offer(carol, BTC(10'000000), USD(10))); + // Set 1% fee + AMM const ammAlice(env, alice, USD(1'005), BTC(1'000'000000), false, 1'000); + env(pay(bob, ed, USD(10)), + path(~USD), + sendmax(BTC(15'000000)), + txflags(tfNoRippleDirect)); + env.require(balance(ed, USD(2'010))); + env.require(balance(bob, BTC(29'990'000000))); + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'000'000000), USD(1'005), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + + // Payment with AMM and CLOB offer. AMM has a better + // spot price quality, but 1% fee offsets that. + // The CLOB offer is consumed first and the remaining + // amount is consumed via AMM liquidity. + { + Env env{*this, features}; + Account const ed("ed"); + fund(env, gw, {alice, bob, carol, ed}, XRP(30'000), {USD(2'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .pay = 30'000'000000, + .flags = MPTDEXFlags}); + + env(offer(carol, BTC(9'000000), USD(9))); + // Set 1% fee + AMM const ammAlice(env, alice, USD(1'005), BTC(1'000'000000), false, 1'000); + env(pay(bob, ed, USD(10)), + path(~USD), + sendmax(BTC(15'000000)), + txflags(tfNoRippleDirect)); + env.require(balance(ed, USD(2'010))); + env.require(balance(bob, BTC(29'989'993923))); + BEAST_EXPECT(ammAlice.expectBalances(BTC(1'001'006077), USD(1'004), ammAlice.tokens())); + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + } + + void + testAdjustedTokens(FeatureBitset features) + { + testcase("Adjusted Deposit/Withdraw Tokens"); + using namespace jtx; + + // Deposit/Withdraw USD from USD/MPT pool + { + Env env(*this); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob("bob"); + Account const carol("carol"); + Account const ed("ed"); + Account const paul("paul"); + Account const dan("dan"); + Account const chris("chris"); + Account const simon("simon"); + Account const ben("ben"); + Account const natalie("natalie"); + std::vector const holders{ + alice, bob, carol, ed, paul, dan, chris, simon, ben, natalie}; + env.fund(XRP(100000), gw, alice, bob, carol, ed, paul, dan, chris, simon, ben, natalie); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = holders, + .pay = 40'000'000000, + .flags = MPTDEXFlags}); + + auto const USD = gw["USD"]; + for (auto const& holder : holders) + { + env.trust(USD(1'500'000), holder); + env(pay(gw, holder, USD(1'500'000))); + } + env.close(); + + auto aliceUSD = env.balance(alice, USD); + auto bobUSD = env.balance(bob, USD); + auto carolUSD = env.balance(carol, USD); + auto edUSD = env.balance(ed, USD); + auto paulUSD = env.balance(paul, USD); + auto danUSD = env.balance(dan, USD); + auto chrisUSD = env.balance(chris, USD); + auto simonUSD = env.balance(simon, USD); + auto benUSD = env.balance(ben, USD); + auto natalieUSD = env.balance(natalie, USD); + + AMM ammAlice(env, alice, BTC(10'000'000000), USD(10000)); + BEAST_EXPECT( + ammAlice.expectBalances(BTC(10'000'000000), USD(10'000), IOUAmount{10'000'000})); + + for (int i = 0; i < 10; ++i) + { + ammAlice.deposit(ben, STAmount{USD, 1, -10}); + ammAlice.withdrawAll(ben, USD(0)); + ammAlice.deposit(simon, USD(0.1)); + ammAlice.withdrawAll(simon, USD(0)); + ammAlice.deposit(chris, USD(1)); + ammAlice.withdrawAll(chris, USD(0)); + ammAlice.deposit(dan, USD(10)); + ammAlice.withdrawAll(dan, USD(0)); + ammAlice.deposit(bob, USD(100)); + ammAlice.withdrawAll(bob, USD(0)); + ammAlice.deposit(carol, USD(1'000)); + ammAlice.withdrawAll(carol, USD(0)); + ammAlice.deposit(ed, USD(10'000)); + ammAlice.withdrawAll(ed, USD(0)); + ammAlice.deposit(paul, USD(100'000)); + ammAlice.withdrawAll(paul, USD(0)); + ammAlice.deposit(natalie, USD(1'000'000)); + ammAlice.withdrawAll(natalie, USD(0)); + } + + BEAST_EXPECT(ammAlice.expectBalances( + BTC(10'000'000000), + STAmount{USD, UINT64_C(10000'0000000001), -10}, + IOUAmount{10'000'000})); + + env.require(balance(bob, bobUSD)); + env.require(balance(carol, carolUSD)); + env.require(balance(ed, edUSD)); + env.require(balance(paul, paulUSD)); + env.require(balance(dan, danUSD)); + env.require(balance(chris, chrisUSD)); + env.require(balance(simon, simonUSD)); + env.require(balance(ben, benUSD)); + env.require(balance(natalie, natalieUSD)); + + ammAlice.withdrawAll(alice); + BEAST_EXPECT(!ammAlice.ammExists()); + env.require(balance(alice, aliceUSD)); + } + + // Same as above but deposit/withdraw MPT from USD/MPT pool + { + Env env(*this); + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob("bob"); + Account const carol("carol"); + Account const ed("ed"); + Account const paul("paul"); + Account const dan("dan"); + Account const chris("chris"); + Account const simon("simon"); + Account const ben("ben"); + Account const natalie("natalie"); + std::vector const holders{ + alice, bob, carol, ed, paul, dan, chris, simon, ben, natalie}; + env.fund(XRP(100000), gw, alice, bob, carol, ed, paul, dan, chris, simon, ben, natalie); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = holders, + .pay = 40'000'000000, + .flags = MPTDEXFlags}); + + auto const USD = gw["USD"]; + for (auto const& holder : holders) + { + env.trust(USD(1'500'000), holder); + env(pay(gw, holder, USD(1'500'000))); + } + env.close(); + + auto aliceBTC = env.balance(alice, BTC); + auto bobBTC = env.balance(bob, BTC); + auto carolBTC = env.balance(carol, BTC); + auto edBTC = env.balance(ed, BTC); + auto paulBTC = env.balance(paul, BTC); + auto danBTC = env.balance(dan, BTC); + auto chrisBTC = env.balance(chris, BTC); + auto simonBTC = env.balance(simon, BTC); + auto benBTC = env.balance(ben, BTC); + auto natalieBTC = env.balance(natalie, BTC); + + AMM ammAlice(env, alice, BTC(10'000'000000), USD(10000)); + BEAST_EXPECT( + ammAlice.expectBalances(BTC(10'000'000000), USD(10'000), IOUAmount{10'000'000})); + + for (int i = 0; i < 10; ++i) + { + ammAlice.deposit(ben, BTC(1)); + ammAlice.withdrawAll(ben, BTC(0)); + ammAlice.deposit(simon, BTC(1'000)); + ammAlice.withdrawAll(simon, BTC(0)); + ammAlice.deposit(chris, BTC(1)); + ammAlice.withdrawAll(chris, BTC(0)); + ammAlice.deposit(dan, BTC(10)); + ammAlice.withdrawAll(dan, BTC(0)); + ammAlice.deposit(bob, BTC(100)); + ammAlice.withdrawAll(bob, BTC(0)); + ammAlice.deposit(carol, BTC(1'000)); + ammAlice.withdrawAll(carol, BTC(0)); + ammAlice.deposit(ed, BTC(10'000)); + ammAlice.withdrawAll(ed, BTC(0)); + ammAlice.deposit(paul, BTC(100'000)); + ammAlice.withdrawAll(paul, BTC(0)); + ammAlice.deposit(natalie, BTC(1'000'000)); + ammAlice.withdrawAll(natalie, BTC(0)); + } + + BEAST_EXPECT( + ammAlice.expectBalances(BTC(10'000'000090), USD(10'000), IOUAmount{10'000'000})); + + env.require(balance(bob, bobBTC - BTC(10))); + env.require(balance(carol, carolBTC - BTC(10))); + env.require(balance(ed, edBTC - BTC(10))); + env.require(balance(paul, paulBTC - BTC(10))); + env.require(balance(dan, danBTC - BTC(10))); + env.require(balance(chris, chrisBTC - BTC(10))); + env.require(balance(simon, simonBTC - BTC(10))); + env.require(balance(ben, benBTC - BTC(10))); + env.require(balance(natalie, natalieBTC - BTC(10))); + + ammAlice.withdrawAll(alice); + BEAST_EXPECT(!ammAlice.ammExists()); + env.require(balance(alice, aliceBTC + BTC(90))); + } + } + + void + testAMMID() + { + testcase("AMMID"); + using namespace jtx; + + // MPT/XRP + testAMM( + [&](AMM& amm, Env& env) { + amm.setClose(false); + auto const info = env.rpc( + "json", + "account_info", + std::string("{\"account\": \"" + to_string(amm.ammAccount()) + "\"}")); + try + { + BEAST_EXPECT( + info[jss::result][jss::account_data][jss::AMMID].asString() == + to_string(amm.ammID())); + } + catch (...) + { + fail(); + } + + amm.deposit(carol, 1'000); + + auto affected = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; + try + { + bool found = false; + for (auto const& node : affected) + { + if (node.isMember(sfModifiedNode.fieldName) && + node[sfModifiedNode.fieldName][sfLedgerEntryType.fieldName] + .asString() == "AccountRoot" && + node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::Account] + .asString() == to_string(amm.ammAccount())) + { + found = + node[sfModifiedNode.fieldName][sfFinalFields.fieldName][jss::AMMID] + .asString() == to_string(amm.ammID()); + break; + } + } + BEAST_EXPECT(found); + } + catch (...) + { + fail(); + } + }, + {{XRP(1000), AMMMPT(1000'000)}}); + } + + void + testSelection(FeatureBitset features) + { + testcase("Offer/Strand Selection"); + using namespace jtx; + Account const ed("ed"); + Account const gw1("gw1"); + + // These tests are expected to fail if the OwnerPaysFee feature + // is ever supported. Updates will need to be made to AMM handling + // in the payment engine, and these tests will need to be updated. + + struct MPTList + { + MPTTester const USD; + MPTTester const ETH; + MPTTester const CAN; + }; + + auto prep = [&](Env& env, uint16_t gwTransferFee, uint16_t gw1TransferFee) -> MPTList { + env.fund(XRP(2'000), gw, gw1, alice, bob, carol, ed); + MPTTester USD( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, ed}, + .transferFee = gwTransferFee, + .pay = 2'000'000'000, + .flags = MPTDEXFlags}); + MPTTester ETH( + {.env = env, + .issuer = gw1, + .holders = {alice, bob, carol, ed}, + .transferFee = gw1TransferFee, + .pay = 2'000'000'000, + .flags = MPTDEXFlags}); + MPTTester CAN( + {.env = env, + .issuer = gw1, + .holders = {alice, bob, carol, ed}, + .transferFee = gw1TransferFee, + .pay = 2'000'000'000, + .flags = MPTDEXFlags}); + env.close(); + + return MPTList{ + .USD = std::move(USD), + .ETH = std::move(ETH), + .CAN = std::move(CAN), + }; + }; + + std::uint32_t constexpr lowRate = 10'000; + std::uint32_t constexpr highRate = 50'000; + for (auto const& rates : + {std::make_pair(lowRate, highRate), std::make_pair(highRate, lowRate)}) + { + // Offer Selection + + // Cross-currency payment: AMM has the same spot price quality + // as CLOB's offer and can't generate a better quality offer. + // The transfer fee in this case doesn't change the CLOB quality + // because trIn is ignored on adjustment and trOut on payment is + // also ignored because ownerPaysTransferFee is false in this + // case. Run test for 0) offer, 1) AMM, 2) offer and AMM to + // verify that the quality is better in the first case, and CLOB + // is selected in the second case. + { + std::array q{}; + for (auto i = 0; i < 3; ++i) + { + Env env(*this, features); + auto mpts = prep(env, rates.first, rates.second); + auto USD = mpts.USD; + auto ETH = mpts.ETH; + auto CAN = mpts.CAN; + std::optional amm; + + if (i == 0 || i == 2) + { + env(offer(ed, ETH(400'000'000), USD(400'000'000)), txflags(tfPassive)); + env.close(); + } + if (i > 0) + amm.emplace(env, ed, USD(1'000'000'000), ETH(1'000'000'000)); + env(pay(carol, bob, USD(100'000'000)), + path(~MPT(USD)), + sendmax(ETH(500'000'000))); + env.close(); + // CLOB and AMM, AMM is not selected + if (i == 2) + { + BEAST_EXPECT(amm->expectBalances( + USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + } + env.require(balance(bob, USD(2'100'000'000))); + q[i] = Quality( + Amounts{ + ETH(2'000'000'000) - env.balance(carol, MPT(ETH)), + env.balance(bob, MPT(USD)) - USD(2'000'000'000)}); + } + // CLOB is better quality than AMM + BEAST_EXPECT(q[0] > q[1]); + // AMM is not selected with CLOB + BEAST_EXPECT(q[0] == q[2]); + } + // Offer crossing: AMM has the same spot price quality + // as CLOB's offer and can't generate a better quality offer. + // The transfer fee in this case doesn't change the CLOB quality + // because the quality adjustment is ignored for the offer + // crossing. + for (auto i = 0; i < 3; ++i) + { + Env env(*this, features); + auto mpts = prep(env, rates.first, rates.second); + auto USD = mpts.USD; + auto ETH = mpts.ETH; + auto CAN = mpts.CAN; + std::optional amm; + if (i == 0 || i == 2) + { + env(offer(ed, ETH(400'000'000), USD(400'000'000)), txflags(tfPassive)); + env.close(); + } + if (i > 0) + amm.emplace(env, ed, USD(1'000'000'000), ETH(1'000'000'000)); + env(offer(alice, USD(400'000'000), ETH(400'000'000))); + env.close(); + // AMM is not selected + if (i > 0) + { + BEAST_EXPECT( + amm->expectBalances(USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + } + if (i == 0 || i == 2) + { + // Fully crosses + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + // Fails to cross because AMM is not selected + else + { + BEAST_EXPECT( + expectOffers(env, alice, 1, {Amounts{USD(400'000'000), ETH(400'000'000)}})); + } + BEAST_EXPECT(expectOffers(env, ed, 0)); + } + + // Show that the CLOB quality reduction + // results in AMM offer selection. + + // Same as the payment but reduced offer quality + { + std::array q{}; + for (auto i = 0; i < 3; ++i) + { + Env env(*this, features); + auto mpts = prep(env, rates.first, rates.second); + auto USD = mpts.USD; + auto ETH = mpts.ETH; + auto CAN = mpts.CAN; + std::optional amm; + if (i == 0 || i == 2) + { + env(offer(ed, ETH(400'000'000), USD(330'000'000)), txflags(tfPassive)); + env.close(); + } + if (i > 0) + amm.emplace(env, ed, USD(1'000'000'000), ETH(1'000'000'000)); + env(pay(carol, bob, USD(100'000'000)), + path(~MPT(USD)), + sendmax(ETH(500'000'000))); + env.close(); + // AMM and CLOB are selected + if (i > 0) + { + BEAST_EXPECT(!amm->expectBalances( + USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + } + + if (i == 2) + { + if (rates.first == lowRate) + { + BEAST_EXPECT(expectOffers( + env, + ed, + 1, + {{Amounts{ + ETH(377'824'111), + USD(311'704'892), + }}})); + } + else + { + BEAST_EXPECT(expectOffers( + env, + ed, + 1, + {{Amounts{ + ETH(329'339'263), + USD(271'704'892), + }}})); + } + } + env.require(balance(bob, USD(2'100'000'000))); + q[i] = Quality( + Amounts{ + ETH(2'000'000'000) - env.balance(carol, MPT(ETH)), + env.balance(bob, MPT(USD)) - USD(2'000'000'000)}); + } + // AMM is better quality + BEAST_EXPECT(q[1] > q[0]); + // AMM and CLOB produce better quality + BEAST_EXPECT(q[2] > q[1]); + } + + // Same as the offer-crossing but reduced offer quality + for (auto i = 0; i < 3; ++i) + { + Env env(*this, features); + auto mpts = prep(env, rates.first, rates.second); + auto USD = mpts.USD; + auto ETH = mpts.ETH; + auto CAN = mpts.CAN; + std::optional amm; + if (i == 0 || i == 2) + { + env(offer(ed, ETH(400'000'000), USD(325'000'002)), txflags(tfPassive)); + env.close(); + } + if (i > 0) + amm.emplace(env, ed, USD(1'000'000'000), ETH(1'000'000'000)); + env(offer(alice, USD(325'000'000), ETH(400'000'000))); + env.close(); + // AMM is selected in both cases + if (i > 0) + { + BEAST_EXPECT(!amm->expectBalances( + USD(1'000'000'000), ETH(1'000'000'000), amm->tokens())); + } + // Partially crosses, AMM is selected, CLOB fails + // limitQuality + if (i == 2) + { + if (rates.first == lowRate) + { + // Ed offer is partially crossed. + // The updated rounding makes limitQuality + // work if both amendments are enabled + BEAST_EXPECT(expectOffers( + env, + ed, + 1, + {{Amounts{ + ETH(121'368'836), + USD(98'612'180), + }}})); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + else + { + // Ed offer is partially crossed. + BEAST_EXPECT(expectOffers( + env, + ed, + 1, + {{Amounts{ + ETH(121'368'836), + USD(98'612'180), + }}})); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + } + } + + // Strand selection + + // Two book steps strand quality is 1. + // AMM strand's best quality is equal to AMM's spot price + // quality, which is 1. Both strands (steps) are adjusted + // for the transfer fee in qualityUpperBound. In case + // of two strands, AMM offers have better quality and are + // consumed first, remaining liquidity is generated by CLOB + // offers. Liquidity from two strands is better in this case + // than in case of one strand with two book steps. Liquidity + // from one strand with AMM has better quality than either one + // strand with two book steps or two strands. It may appear + // unintuitive, but one strand with AMM is optimized and + // generates one AMM offer, while in case of two strands, + // multiple AMM offers are generated, which results in slightly + // worse overall quality. + { + std::array q{}; + for (auto i = 0; i < 3; ++i) + { + Env env(*this, features); + auto mpts = prep(env, rates.first, rates.second); + auto USD = mpts.USD; + auto ETH = mpts.ETH; + auto CAN = mpts.CAN; + std::optional amm; + + if (i == 0 || i == 2) + { + env(offer(ed, ETH(400'000'000), CAN(375'000'000)), txflags(tfPassive)); + env(offer(ed, CAN(375'000'000), USD(338'000'000))), txflags(tfPassive); + } + + if (i > 0) + amm.emplace(env, ed, ETH(1'000'000'000), USD(1'000'000'000)); + + env(pay(carol, bob, USD(100'000'000)), + path(~MPT(USD)), + path(~MPT(CAN), ~MPT(USD)), + sendmax(ETH(600'000'000))); + env.close(); + + env.require(balance(bob, USD(2'100'000'000))); + + if (i == 2) + { + if (rates.first == lowRate) + { + // Liquidity is consumed from AMM strand only + BEAST_EXPECT(amm->expectBalances( + ETH(1'124'584'936), USD(889'999'993), amm->tokens())); + } + else + { + BEAST_EXPECT(amm->expectBalances( + ETH(1'103'723'909), USD(906'023'688), amm->tokens())); + BEAST_EXPECT(expectOffers( + env, + ed, + 2, + {{Amounts{ + ETH(327'069'745), + CAN(306'627'886), + }, + Amounts{ + CAN(312'843'533), + USD(281'976'305), + }}})); + } + } + q[i] = Quality( + Amounts{ + ETH(2'000'000'000) - env.balance(carol, MPT(ETH)), + env.balance(bob, MPT(USD)) - USD(2'000'000'000)}); + } + BEAST_EXPECT(q[1] > q[0]); + BEAST_EXPECT(q[2] > q[0] && q[2] < q[1]); + } + } + } + + void + testMalformed() + { + testcase("Malformed"); + using namespace jtx; + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .flags = tfSingleAsset, + .err = ter(temMALFORMED), + }; + ammAlice.withdraw(args); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .flags = tfOneAssetLPToken, + .err = ter(temMALFORMED), + }; + ammAlice.withdraw(args); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .flags = tfLimitLPToken, + .err = ter(temMALFORMED), + }; + ammAlice.withdraw(args); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + WithdrawArg const args{ + .asset1Out = MPT(ammAlice[1])(100), + .asset2Out = MPT(ammAlice[1])(100), + .err = ter(temBAD_AMM_TOKENS), + }; + ammAlice.withdraw(args); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 2'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + WithdrawArg const args{ + .asset1Out = XRP(100), + .asset2Out = BTC(100), + .err = ter(temBAD_AMM_TOKENS), + }; + ammAlice.withdraw(args); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + + testAMM( + [&](AMM& ammAlice, Env& env) { + Json::Value jv; + jv[jss::TransactionType] = jss::AMMWithdraw; + jv[jss::Flags] = tfLimitLPToken; + jv[jss::Account] = alice.human(); + ammAlice.setTokens(jv); + XRP(100).value().setJson(jv[jss::Amount]); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 2'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + BTC(100).value().setJson(jv[jss::EPrice]); + env(jv, ter(telENV_RPC_FAILED)); + }, + {{XRP(10'000), AMMMPT(10'000)}}); + } + + void + testFixAMMOfferBlockedByLOB(FeatureBitset features) + { + testcase("AMM Offer Blocked By LOB"); + using namespace jtx; + + // Low quality LOB offer blocks AMM liquidity + + // USD/MPT crosses AMM despite of low quality LOB + { + Env env(*this, features); + + fund(env, gw, {alice, carol}, XRP(1'000'000), {USD(1'000'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 40'000'000000, + .flags = MPTDEXFlags}); + + env(offer(alice, BTC(1), USD(0.01))); + env.close(); + AMM const amm(env, gw, BTC(200'000), USD(100'000)); + env(offer(carol, USD(0.49), BTC(1))); + env.close(); + + if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { + BEAST_EXPECT(amm.expectBalances(BTC(200'000), USD(100'000), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{BTC(1), USD(0.01)}}})); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{USD(0.49), BTC(1)}}})); + } + + if (features[fixAMMv1_1] && features[fixAMMv1_3]) + { + BEAST_EXPECT(amm.expectBalances(BTC(200'001), USD(99'999.51), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{BTC(1), USD(0.01)}}})); + // Carol's offer crosses AMM + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + } + + // XRP/MPT crosses AMM despite of low quality LOB + { + Env env(*this, features); + + fund(env, gw, {alice, carol}, XRP(1'000'000), {USD(1'000'000)}); + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 40'000'000000, + .flags = MPTDEXFlags}); + + env(offer(alice, BTC(1), XRP(0.01))); + env.close(); + AMM const amm(env, gw, BTC(200'000), XRP(100'000)); + env(offer(carol, XRP(0.49), BTC(1))); + env.close(); + + if (!features[fixAMMv1_1] && !features[fixAMMv1_3]) + { + BEAST_EXPECT(amm.expectBalances(BTC(200'000), XRP(100'000), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{BTC(1), XRP(0.01)}}})); + BEAST_EXPECT(expectOffers(env, carol, 1, {{Amounts{XRP(0.49), BTC(1)}}})); + } + + if (features[fixAMMv1_1] && features[fixAMMv1_3]) + { + BEAST_EXPECT(amm.expectBalances(BTC(200'001), XRP(99'999.51), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{BTC(1), XRP(0.01)}}})); + // Carol's offer crosses AMM + BEAST_EXPECT(expectOffers(env, carol, 0)); + } + } + } + + void + testLPTokenBalance(FeatureBitset features) + { + testcase("LPToken Balance"); + using namespace jtx; + + Env env(*this, features); + Account const gw{"gateway"}, alice{"alice"}, bob{"bob"}; + env.fund(XRP(100000), gw, alice, bob); + env.close(); + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto const USD = gw["USD"]; + env.trust(USD(100000), alice); + env(pay(gw, alice, USD(50000))); + env.trust(USD(100000), bob); + env(pay(gw, bob, USD(40000))); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .pay = 40'000'000000, + .flags = tfMPTCanClawback | tfMPTCanLock | MPTDEXFlags}); + + AMM amm(env, alice, BTC(2), USD(1)); + amm.deposit(alice, IOUAmount{1'876123487565916, -15}); + amm.deposit(bob, IOUAmount{1'000}); + amm.withdraw(alice, IOUAmount{1'876123487565916, -15}); + amm.withdrawAll(bob); + + auto const lpToken = + getAccountLines(env, alice, amm.lptIssue())[jss::lines][0u][jss::balance].asString(); + auto const lpTokenBalance = + amm.ammRpcInfo()[jss::amm][jss::lp_token][jss::value].asString(); + + BEAST_EXPECT(lpToken == "1.414213562374011" && lpTokenBalance == "1.4142135623741"); + + auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), alice); + BEAST_EXPECT(res && res.value()); + + amm.withdrawAll(alice); + BEAST_EXPECT(!amm.ammExists()); + } + + void + testAMMDepositWithFrozenAssets() + { + testcase("test AMMDeposit with frozen assets"); + using namespace jtx; + + // This lambda function is used to create trustline, MPT. + // and create an AMM account. + // And also test the callback function. + auto testAMMDeposit = [&](Env& env, std::function cb) { + env.fund(XRP(1'000), gw, alice); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 30'000, + .flags = tfMPTCanLock | MPTDEXFlags}); + + AMM amm(env, alice, BTC(100), XRP(100)); + env.close(); + BTC.set({.holder = alice, .flags = tfMPTLock}); + cb(amm, BTC); + }; + + // Deposit two assets, one of which is frozen, + // then we should get tecFROZEN error. + { + Env env(*this); + testAMMDeposit(env, [&](AMM& amm, MPTTester& BTC) { + amm.deposit(alice, BTC(100), XRP(100), std::nullopt, tfTwoAsset, ter(tecFROZEN)); + }); + } + + // Deposit one asset, which is the frozen token, + // then we should get tecFROZEN error. + { + Env env(*this); + testAMMDeposit(env, [&](AMM& amm, MPTTester& BTC) { + amm.deposit( + alice, BTC(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); + }); + } + + // Deposit one asset which is not the frozen token, + // but the other asset is frozen. We should get tecFROZEN error + // when feature AMMClawback is enabled. + { + Env env(*this); + testAMMDeposit(env, [&](AMM& amm, MPTTester& BTC) { + amm.deposit( + alice, XRP(100), std::nullopt, std::nullopt, tfSingleAsset, ter(tecFROZEN)); + }); + } + } + + void + testAutoDelete() + { + testcase("Auto Delete"); + + using namespace jtx; + FeatureBitset const all{testable_amendments()}; + + { + Env env( + *this, + envconfig([](std::unique_ptr cfg) { + cfg->FEES.reference_fee = XRPAmount(1); + return cfg; + }), + all); + env.fund(XRP(1'000), gw, alice); + MPTTester const USD({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + MPTTester const BTC({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + AMM amm(env, gw, USD(10'000), BTC(10'000)); + for (auto i = 0; i < maxDeletableAMMTrustLines + 10; ++i) + { + Account const a{std::to_string(i)}; + env.fund(XRP(1'000), a); + env(trust(a, STAmount{amm.lptIssue(), 10'000})); + env.close(); + } + // The trustlines are partially deleted, + // AMM is set to an empty state. + amm.withdrawAll(gw); + BEAST_EXPECT(amm.ammExists()); + + // Bid,Vote,Deposit,Withdraw,SetTrust failing with + // tecAMM_EMPTY. Deposit succeeds with tfTwoAssetIfEmpty option. + env(amm.bid({ + .account = alice, + .bidMin = 1000, + }), + ter(tecAMM_EMPTY)); + amm.vote({.account = alice, .tfee = 100, .err = ter(tecAMM_EMPTY)}); + amm.withdraw({.account = alice, .tokens = 100, .err = ter(tecAMM_EMPTY)}); + amm.deposit({.account = alice, .asset1In = USD(100), .err = ter(tecAMM_EMPTY)}); + env(trust(alice, STAmount{amm.lptIssue(), 10'000}), ter(tecAMM_EMPTY)); + + // Can deposit with tfTwoAssetIfEmpty option + amm.deposit( + {.account = alice, + .asset1In = USD(1'000), + .asset2In = BTC(1'000), + .flags = tfTwoAssetIfEmpty, + .tfee = 1'000}); + BEAST_EXPECT(amm.expectBalances(USD(1'000), BTC(1'000), IOUAmount{1'000})); + BEAST_EXPECT(amm.expectTradingFee(1'000)); + BEAST_EXPECT(amm.expectAuctionSlot(100, 0, IOUAmount{0})); + + // Withdrawing all tokens deletes AMM since the number + // of remaining trustlines is less than max + amm.withdrawAll(alice); + BEAST_EXPECT(!amm.ammExists()); + BEAST_EXPECT(!env.le(keylet::ownerDir(amm.ammAccount()))); + } + + { + Env env( + *this, + envconfig([](std::unique_ptr cfg) { + cfg->FEES.reference_fee = XRPAmount(1); + return cfg; + }), + all); + env.fund(XRP(1'000), gw, alice); + MPTTester const USD({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + MPTTester const BTC({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + AMM amm(env, gw, USD(10'000), BTC(10'000)); + for (auto i = 0; i < (maxDeletableAMMTrustLines * 2) + 10; ++i) + { + Account const a{std::to_string(i)}; + env.fund(XRP(1'000), a); + env(trust(a, STAmount{amm.lptIssue(), 10'000})); + env.close(); + } + // The trustlines are partially deleted. + amm.withdrawAll(gw); + BEAST_EXPECT(amm.ammExists()); + + // AMMDelete has to be called twice to delete AMM. + amm.ammDelete(alice, ter(tecINCOMPLETE)); + BEAST_EXPECT(amm.ammExists()); + // Deletes remaining trustlines and deletes AMM. + amm.ammDelete(alice); + BEAST_EXPECT(!amm.ammExists()); + BEAST_EXPECT(!env.le(keylet::ownerDir(amm.ammAccount()))); + + // Try redundant delete + amm.ammDelete(alice, ter(terNO_AMM)); + } + + { + Env env( + *this, + envconfig([](std::unique_ptr cfg) { + cfg->FEES.reference_fee = XRPAmount(1); + return cfg; + }), + all); + env.fund(XRP(1'000), gw, alice, carol); + MPTTester const USD( + {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 20'000}); + MPTTester const BTC( + {.env = env, .issuer = gw, .holders = {alice, carol}, .pay = 20'000}); + AMM amm(env, gw, USD(10'000), BTC(10'000)); + amm.deposit({.account = alice, .tokens = 1'000}); + amm.deposit({.account = carol, .tokens = 1'000}); + amm.withdrawAll(alice); + amm.withdrawAll(carol); + amm.withdrawAll(gw); + BEAST_EXPECT(!amm.ammExists()); + } + + // This test validates both invariant changes work together for + // the specific case of MPT/MPT pools with > maxDeletableAMMTrustLines. + { + Env env( + *this, + envconfig([](std::unique_ptr cfg) { + cfg->FEES.reference_fee = XRPAmount(1); + return cfg; + }), + all); + + env.fund(XRP(1'000), gw, alice); + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + MPT const BTC = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 20'000}); + + // MPT/MPT pool with MANY trustlines + AMM amm(env, gw, USD(10'000), BTC(10'000)); + for (auto i = 0; i < (maxDeletableAMMTrustLines * 2) + 10; ++i) + { + Account const a{std::to_string(i)}; + env.fund(XRP(1'000), a); + env(trust(a, STAmount{amm.lptIssue(), 10'000})); + env.close(); + } + + amm.withdrawAll(gw); + // AMM is in empty state, but can't be auto-deleted because of the LPTokens trustlines. + BEAST_EXPECT(amm.expectBalances(USD(0), BTC(0), IOUAmount(0))); + BEAST_EXPECT(amm.ammExists()); + + // Critical: MPT/MPT pool + tecINCOMPLETE + amm.ammDelete(alice, ter(tecINCOMPLETE)); + BEAST_EXPECT(amm.ammExists()); + + amm.ammDelete(alice); + BEAST_EXPECT(!amm.ammExists()); + } + } + + void + run() override + { + FeatureBitset const all{jtx::testable_amendments()}; + testInstanceCreate(); + testInvalidInstance(); + testInvalidDeposit(all); + testInvalidDeposit(all - featureAMMClawback); + testDeposit(); + testInvalidWithdraw(); + testWithdraw(); + testInvalidFeeVote(); + testFeeVote(); + testInvalidBid(); + testBid(all); + testClawback(); + testClawbackFromAMMAccount(all); + testClawbackFromAMMAccount(all - featureSingleAssetVault); + testInvalidAMMPayment(); + testBasicPaymentEngine(); + testAMMTokens(); + testAmendment(); + testAMMAndCLOB(all); + testTradingFee(all); + testTradingFee(all - fixAMMv1_3); + testAdjustedTokens(all); + testAMMID(); + testSelection(all); + testMalformed(); + testFixAMMOfferBlockedByLOB(all - fixAMMv1_1 - fixAMMv1_3); + testFixAMMOfferBlockedByLOB(all); + testLPTokenBalance(all); + testLPTokenBalance(all - fixAMMv1_3); + testAMMDepositWithFrozenAssets(); + testAutoDelete(); + } +}; + +BEAST_DEFINE_TESTSUITE_PRIO(AMMMPT, app, xrpl, 1); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/AMM_test.cpp b/src/test/app/AMM_test.cpp index 75b29fb79d..8a56e841d6 100644 --- a/src/test/app/AMM_test.cpp +++ b/src/test/app/AMM_test.cpp @@ -135,11 +135,11 @@ private: // Make sure asset comparison works. BEAST_EXPECT( - STIssue(sfAsset, STAmount(XRP(2'000)).issue()) == - STIssue(sfAsset, STAmount(XRP(2'000)).issue())); + STIssue(sfAsset, STAmount(XRP(2'000)).asset()) == + STIssue(sfAsset, STAmount(XRP(2'000)).asset())); BEAST_EXPECT( - STIssue(sfAsset, STAmount(XRP(2'000)).issue()) != - STIssue(sfAsset, STAmount(USD(2'000)).issue())); + STIssue(sfAsset, STAmount(XRP(2'000)).asset()) != + STIssue(sfAsset, STAmount(USD(2'000)).asset())); } void @@ -288,8 +288,11 @@ private: env.close(); env(trust(gw, alice["USD"](30'000))); env.close(); - AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); - BEAST_EXPECT(!ammAlice.ammExists()); + for (auto const& account : {alice, gw}) + { + AMM const amm(env, account, XRP(10'000), USD(10'000), ter(tecFROZEN)); + BEAST_EXPECT(!amm.ammExists()); + } } // Individually frozen @@ -303,6 +306,8 @@ private: env.close(); AMM const ammAlice(env, alice, XRP(10'000), USD(10'000), ter(tecFROZEN)); BEAST_EXPECT(!ammAlice.ammExists()); + // issuer can create + AMM const amm(env, gw, XRP(10'000), USD(10'000)); } // Insufficient reserve, XRP/IOU @@ -359,7 +364,7 @@ private: // AMM with one LPToken from another AMM. testAMM([&](AMM& ammAlice, Env& env) { - fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); + fund(env, gw, {alice}, {EUR(10'000)}, Fund::TokenOnly); AMM const ammAMMToken( env, alice, @@ -376,7 +381,7 @@ private: // AMM with two LPTokens from other AMMs. testAMM([&](AMM& ammAlice, Env& env) { - fund(env, gw, {alice}, {EUR(10'000)}, Fund::IOUOnly); + fund(env, gw, {alice}, {EUR(10'000)}, Fund::TokenOnly); AMM const ammAlice1(env, alice, XRP(10'000), EUR(10'000)); auto const token1 = ammAlice.lptIssue(); auto const token2 = ammAlice1.lptIssue(); @@ -585,7 +590,7 @@ private: alice, BAD(100), std::nullopt, std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); // Invalid Account - Account bad("bad"); + Account const bad("bad"); env.memoize(bad); ammAlice.deposit( bad, @@ -713,11 +718,20 @@ private: ammAlice.deposit( carol, XRP(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); } - ammAlice.deposit( - carol, USD(100), std::nullopt, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit(carol, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.deposit( - carol, XRP(100), USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + for (auto const& account : {carol, gw}) + { + ammAlice.deposit( + account, + USD(100), + std::nullopt, + std::nullopt, + std::nullopt, + ter(tecFROZEN)); + ammAlice.deposit( + account, 1'000'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.deposit( + account, XRP(100), USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + } }, std::nullopt, 0, @@ -1579,7 +1593,7 @@ private: ammAlice.withdraw(alice, BAD(100), std::nullopt, std::nullopt, ter(temBAD_CURRENCY)); // Invalid Account - Account bad("bad"); + Account const bad("bad"); env.memoize(bad); ammAlice.withdraw( bad, @@ -1678,12 +1692,16 @@ private: // Globally frozen asset testAMM([&](AMM& ammAlice, Env& env) { + ammAlice.deposit({.account = gw, .asset1In = USD(1'000), .asset2In = XRP(1'000)}); env(fset(gw, asfGlobalFreeze)); env.close(); // Can withdraw non-frozen token - ammAlice.withdraw(alice, XRP(100)); - ammAlice.withdraw(alice, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); - ammAlice.withdraw(alice, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + for (auto const& account : {alice, gw}) + { + ammAlice.withdraw(account, XRP(100)); + ammAlice.withdraw(account, USD(100), std::nullopt, std::nullopt, ter(tecFROZEN)); + ammAlice.withdraw(account, 1'000, std::nullopt, std::nullopt, ter(tecFROZEN)); + } }); // Individually frozen (AMM) account @@ -2192,7 +2210,7 @@ private: BEAST_EXPECT(ammAlice.expectTradingFee(0)); // Invalid Account - Account bad("bad"); + Account const bad("bad"); env.memoize(bad); ammAlice.vote(bad, 1'000, std::nullopt, seq(1), std::nullopt, ter(terNO_ACCOUNT)); @@ -2426,7 +2444,7 @@ private: ter(tecAMM_INVALID_TOKENS)); // Invalid Account - Account bad("bad"); + Account const bad("bad"); env.memoize(bad); env(ammAlice.bid({ .account = bad, @@ -2489,10 +2507,10 @@ private: // More than four Auth accounts. testAMM([&](AMM& ammAlice, Env& env) { - Account ed("ed"); - Account bill("bill"); - Account scott("scott"); - Account james("james"); + Account const ed("ed"); + Account const bill("bill"); + Account const scott("scott"); + Account const james("james"); env.fund(XRP(1'000), bob, ed, bill, scott, james); env.close(); ammAlice.deposit(carol, 1'000'000); @@ -3026,8 +3044,8 @@ private: BEAST_EXPECT(ammAlice.expectAuctionSlot({carol})); env(ammAlice.bid({.account = alice, .bidMin = IOUAmount{100}})); BEAST_EXPECT(ammAlice.expectAuctionSlot({})); - Account bob("bob"); - Account dan("dan"); + Account const bob("bob"); + Account const dan("dan"); fund(env, {bob, dan}, XRP(1'000)); env(ammAlice.bid({ .account = alice, @@ -4046,7 +4064,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { env.fund(XRP(1'000), bob); - fund(env, gw, {bob}, {EUR(400)}, Fund::IOUOnly); + fund(env, gw, {bob}, {EUR(400)}, Fund::TokenOnly); env(trust(alice, EUR(200))); for (int i = 0; i < 30; ++i) env(offer(alice, EUR(1.0 + (0.01 * i)), XRP(1))); @@ -4086,7 +4104,7 @@ private: testAMM( [&](AMM& ammAlice, Env& env) { env.fund(XRP(1'000), bob); - fund(env, gw, {bob}, {EUR(400)}, Fund::IOUOnly); + fund(env, gw, {bob}, {EUR(400)}, Fund::TokenOnly); env(trust(alice, EUR(200))); for (int i = 0; i < 29; ++i) env(offer(alice, EUR(1.0 + (0.01 * i)), XRP(1))); @@ -4224,7 +4242,7 @@ private: // Offer crossing with two AMM LPTokens. testAMM([&](AMM& ammAlice, Env& env) { ammAlice.deposit(carol, 1'000'000); - fund(env, gw, {alice, carol}, {EUR(10'000)}, Fund::IOUOnly); + fund(env, gw, {alice, carol}, {EUR(10'000)}, Fund::TokenOnly); AMM ammAlice1(env, alice, XRP(10'000), EUR(10'000)); ammAlice1.deposit(carol, 1'000'000); auto const token1 = ammAlice.lptIssue(); @@ -5194,7 +5212,7 @@ private: auto prep = [&](Env& env, auto gwRate, auto gw1Rate) { fund(env, gw, {alice, carol, bob, ed}, XRP(2'000), {USD(2'000)}); env.fund(XRP(2'000), gw1); - fund(env, gw1, {alice, carol, bob, ed}, {ETH(2'000), CAN(2'000)}, Fund::IOUOnly); + fund(env, gw1, {alice, carol, bob, ed}, {ETH(2'000), CAN(2'000)}, Fund::TokenOnly); env(rate(gw, gwRate)); env(rate(gw1, gw1Rate)); env.close(); @@ -5824,7 +5842,7 @@ private: takerGets}; } auto const takerPays = - toAmount(getIssue(poolIn), Number{1, -10} * poolIn); + toAmount(getAsset(poolIn), Number{1, -10} * poolIn); return Amounts{ takerPays, swapAssetIn(Amounts{poolIn, poolOut}, takerPays, tfee)}; }(); @@ -6472,7 +6490,7 @@ private: Account const gw1("gw1"); auto const YAN = gw1["YAN"]; fund(env, gw, {gw1}, XRP(1'000), {USD(1'000)}); - fund(env, gw1, {gw}, XRP(1'000), {YAN(1'000)}, Fund::IOUOnly); + fund(env, gw1, {gw}, XRP(1'000), {YAN(1'000)}, Fund::TokenOnly); AMM amm(env, gw1, YAN(10), USD(10)); amm.deposit(gw, 1'000); auto res = isOnlyLiquidityProvider(*env.current(), amm.lptIssue(), gw); @@ -6652,7 +6670,7 @@ private: STAmount const amount = XRP(10'000); STAmount const amount2 = USD(10'000); - auto const keylet = keylet::amm(amount.issue(), amount2.issue()); + auto const keylet = keylet::amm(amount.asset(), amount2.asset()); for (int i = 0; i < 256; ++i) { AccountID const accountId = xrpl::pseudoAccountAddress(*env.current(), keylet.key); @@ -6930,7 +6948,7 @@ private: // tfSingleAsset withdraw mode // Note: This test fails with 0 trading fees, but doesn't fail if // trading fees is set to 1'000 -- I suspect the compound operations - // in AMMHelpers.cpp:withdrawByTokens compensate for the rounding + // in AMMHelpers.cpp:ammAssetOut compensate for the rounding // errors testAMM( [&](AMM& ammAlice, Env& env) { diff --git a/src/test/app/CheckMPT_test.cpp b/src/test/app/CheckMPT_test.cpp new file mode 100644 index 0000000000..a1f35d0507 --- /dev/null +++ b/src/test/app/CheckMPT_test.cpp @@ -0,0 +1,2156 @@ +#include + +#include +#include +#include + +namespace xrpl { + +class CheckMPT_test : public beast::unit_test::suite +{ + // Helper function that returns the Checks on an account. + static std::vector> + checksOnAccount(test::jtx::Env& env, test::jtx::Account account) + { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle && sle->getType() == ltCHECK) + result.push_back(sle); + }); + return result; + } + + // Helper function that verifies the expected DeliveredAmount is present. + // + // NOTE: the function _infers_ the transaction to operate on by calling + // env.tx(), which returns the result from the most recent transaction. + void + verifyDeliveredAmount(test::jtx::Env& env, STAmount const& amount) + { + // Get the hash for the most recent transaction. + std::string const txHash{env.tx()->getJson(JsonOptions::none)[jss::hash].asString()}; + + // Verify DeliveredAmount and delivered_amount metadata are correct. + env.close(); + Json::Value const meta = env.rpc("tx", txHash)[jss::result][jss::meta]; + + // Expect there to be a DeliveredAmount field. + if (!BEAST_EXPECT(meta.isMember(sfDeliveredAmount.jsonName))) + return; + + // DeliveredAmount and delivered_amount should both be present and + // equal amount. + BEAST_EXPECT(meta[sfDeliveredAmount.jsonName] == amount.getJson(JsonOptions::none)); + BEAST_EXPECT(meta[jss::delivered_amount] == amount.getJson(JsonOptions::none)); + } + + void + testCreateValid(FeatureBitset features) + { + // Explore many of the valid ways to create a check. + testcase("Create valid"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, features}; + + STAmount const startBalance{XRP(1'000).value()}; + env.fund(startBalance, gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw}); + + // Note that no MPToken has been set up for alice, but alice can + // still write a check for USD. You don't have to have the funds + // necessary to cover a check in order to write a check. + auto writeTwoChecks = [&env, &USD, this](Account const& from, Account const& to) { + std::uint32_t const fromOwnerCount{ownerCount(env, from)}; + std::uint32_t const toOwnerCount{ownerCount(env, to)}; + + std::size_t const fromCkCount{checksOnAccount(env, from).size()}; + std::size_t const toCkCount{checksOnAccount(env, to).size()}; + + env(check::create(from, to, XRP(2000))); + env.close(); + + env(check::create(from, to, USD(50))); + env.close(); + + BEAST_EXPECT(checksOnAccount(env, from).size() == fromCkCount + 2); + BEAST_EXPECT(checksOnAccount(env, to).size() == toCkCount + 2); + + env.require(owners(from, fromOwnerCount + 2)); + env.require(owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); + }; + // from to + writeTwoChecks(alice, bob); + writeTwoChecks(gw, alice); + writeTwoChecks(alice, gw); + + // Now try adding the various optional fields. There's no + // expected interaction between these optional fields; other than + // the expiration, they are just plopped into the ledger. So I'm + // not looking at interactions. + using namespace std::chrono_literals; + std::size_t const aliceCount{checksOnAccount(env, alice).size()}; + std::size_t const bobCount{checksOnAccount(env, bob).size()}; + env(check::create(alice, bob, USD(50)), expiration(env.now() + 1s)); + env.close(); + + env(check::create(alice, bob, USD(50)), source_tag(2)); + env.close(); + env(check::create(alice, bob, USD(50)), dest_tag(3)); + env.close(); + env(check::create(alice, bob, USD(50)), invoice_id(uint256{4})); + env.close(); + env(check::create(alice, bob, USD(50)), + expiration(env.now() + 1s), + source_tag(12), + dest_tag(13), + invoice_id(uint256{4})); + env.close(); + + BEAST_EXPECT(checksOnAccount(env, alice).size() == aliceCount + 5); + BEAST_EXPECT(checksOnAccount(env, bob).size() == bobCount + 5); + + // Use a regular key and also multisign to create a check. + Account const alie{"alie", KeyType::ed25519}; + env(regkey(alice, alie)); + env.close(); + + Account const bogie{"bogie", KeyType::secp256k1}; + Account const demon{"demon", KeyType::ed25519}; + env(signers(alice, 2, {{bogie, 1}, {demon, 1}}), sig(alie)); + env.close(); + + // alice uses her regular key to create a check. + env(check::create(alice, bob, USD(50)), sig(alie)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == aliceCount + 6); + BEAST_EXPECT(checksOnAccount(env, bob).size() == bobCount + 6); + + // alice uses multisigning to create a check. + XRPAmount const baseFeeDrops{env.current()->fees().base}; + env(check::create(alice, bob, USD(50)), msig(bogie, demon), fee(3 * baseFeeDrops)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == aliceCount + 7); + BEAST_EXPECT(checksOnAccount(env, bob).size() == bobCount + 7); + } + + void + testCreateDisallowIncoming(FeatureBitset features) + { + testcase("Create valid with disallow incoming"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, features}; + + STAmount const startBalance{XRP(1'000).value()}; + env.fund(startBalance, gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw}); + + /* + * Attempt to create two checks from `from` to `to` and + * require they both result in error/success code `expected` + */ + auto writeTwoChecksDI = [&env, &USD, this]( + Account const& from, Account const& to, TER expected) { + std::uint32_t const fromOwnerCount{ownerCount(env, from)}; + std::uint32_t const toOwnerCount{ownerCount(env, to)}; + + std::size_t const fromCkCount{checksOnAccount(env, from).size()}; + std::size_t const toCkCount{checksOnAccount(env, to).size()}; + + env(check::create(from, to, XRP(2000)), ter(expected)); + env.close(); + + env(check::create(from, to, USD(50)), ter(expected)); + env.close(); + + if (expected == tesSUCCESS) + { + BEAST_EXPECT(checksOnAccount(env, from).size() == fromCkCount + 2); + BEAST_EXPECT(checksOnAccount(env, to).size() == toCkCount + 2); + + env.require(owners(from, fromOwnerCount + 2)); + env.require(owners(to, to == from ? fromOwnerCount + 2 : toOwnerCount)); + return; + } + + BEAST_EXPECT(checksOnAccount(env, from).size() == fromCkCount); + BEAST_EXPECT(checksOnAccount(env, to).size() == toCkCount); + + env.require(owners(from, fromOwnerCount)); + env.require(owners(to, to == from ? fromOwnerCount : toOwnerCount)); + }; + + // enable the DisallowIncoming flag on both bob and alice + env(fset(bob, asfDisallowIncomingCheck)); + env(fset(alice, asfDisallowIncomingCheck)); + env.close(); + + // both alice and bob can't receive checks + writeTwoChecksDI(alice, bob, tecNO_PERMISSION); + writeTwoChecksDI(gw, alice, tecNO_PERMISSION); + + // remove the flag from alice but not from bob + env(fclear(alice, asfDisallowIncomingCheck)); + env.close(); + + // now bob can send alice a cheque but not visa-versa + writeTwoChecksDI(bob, alice, tesSUCCESS); + writeTwoChecksDI(alice, bob, tecNO_PERMISSION); + + // remove bob's flag too + env(fclear(bob, asfDisallowIncomingCheck)); + env.close(); + + // now they can send checks freely + writeTwoChecksDI(bob, alice, tesSUCCESS); + writeTwoChecksDI(alice, bob, tesSUCCESS); + } + + void + testCreateInvalid(FeatureBitset features) + { + // Explore many of the invalid ways to create a check. + testcase("Create invalid"); + + using namespace test::jtx; + + Account const gw1{"gateway1"}; + Account const gwF{"gatewayFrozen"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, features}; + + STAmount const startBalance{XRP(1'000).value()}; + env.fund(startBalance, gw1, gwF, alice, bob); + + auto USDM = MPTTester({.env = env, .issuer = gw1, .flags = MPTDEXFlags | tfMPTCanLock}); + MPT const USD = USDM; + + // Bad fee. + env(check::create(alice, bob, USD(50)), fee(drops(-10)), ter(temBAD_FEE)); + env.close(); + + // Bad flags. + env(check::create(alice, bob, USD(50)), txflags(tfImmediateOrCancel), ter(temINVALID_FLAG)); + env.close(); + + // Check to self. + env(check::create(alice, alice, XRP(10)), ter(temREDUNDANT)); + env.close(); + + // Bad amount. + env(check::create(alice, bob, drops(-1)), ter(temBAD_AMOUNT)); + env.close(); + + env(check::create(alice, bob, drops(0)), ter(temBAD_AMOUNT)); + env.close(); + + env(check::create(alice, bob, drops(1))); + env.close(); + + env(check::create(alice, bob, USD(-1)), ter(temBAD_AMOUNT)); + env.close(); + + env(check::create(alice, bob, USD(0)), ter(temBAD_AMOUNT)); + env.close(); + + env(check::create(alice, bob, USD(1))); + env.close(); + { + MPT const BAD(makeMptID(0, xrpAccount())); + env(check::create(alice, bob, BAD(2)), ter(temBAD_CURRENCY)); + env.close(); + } + + // Bad expiration. + env(check::create(alice, bob, USD(50)), + expiration(NetClock::time_point{}), + ter(temBAD_EXPIRATION)); + env.close(); + + // Destination does not exist. + Account const bogie{"bogie"}; + env(check::create(alice, bogie, USD(50)), ter(tecNO_DST)); + env.close(); + + // Require destination tag. + env(fset(bob, asfRequireDest)); + env.close(); + + env(check::create(alice, bob, USD(50)), ter(tecDST_TAG_NEEDED)); + env.close(); + + env(check::create(alice, bob, USD(50)), dest_tag(11)); + env.close(); + + env(fclear(bob, asfRequireDest)); + env.close(); + { + // Globally frozen asset. + env.close(); + auto USFM = MPTTester({.env = env, .issuer = gwF, .flags = MPTDEXFlags | tfMPTCanLock}); + MPT const USF = USFM; + USFM.set({.flags = tfMPTLock}); + + env(check::create(alice, bob, USF(50)), ter(tecLOCKED)); + env.close(); + + USFM.set({.flags = tfMPTUnlock}); + + env(check::create(alice, bob, USF(50))); + env.close(); + } + { + // Frozen MPT. Check creation should be similar to payment + // behavior in the face of locked MPT. + USDM.authorizeHolders({alice, bob}); + env(pay(gw1, alice, USD(25))); + env(pay(gw1, bob, USD(25))); + env.close(); + + USDM.set({.holder = alice, .flags = tfMPTLock}); + // Setting MPT locked prevents alice from + // creating a check for USD ore receiving a check. This is different + // from IOU where alice can receive checks from bob or gw. + env.close(); + env(check::create(alice, bob, USD(50)), ter(tecLOCKED)); + env.close(); + // Note that IOU returns tecPATH_DRY in this case. + // IOU's internal error is terNO_LINE, which is + // considered ter re-triable and changed to tecPATH_DRY. + env(pay(alice, bob, USD(1)), ter(tecPATH_DRY)); + env.close(); + env(check::create(bob, alice, USD(50)), ter(tecLOCKED)); + env.close(); + env(pay(bob, alice, USD(1)), ter(tecPATH_DRY)); + env.close(); + env(check::create(gw1, alice, USD(50)), ter(tecLOCKED)); + env.close(); + env(pay(gw1, alice, USD(1))); + env.close(); + + // Clear that lock. Now check creation works. + USDM.set({.holder = alice, .flags = tfMPTUnlock}); + env(check::create(alice, bob, USD(50))); + env.close(); + env(check::create(bob, alice, USD(50))); + env.close(); + env(check::create(gw1, alice, USD(50))); + env.close(); + } + + // Expired expiration. + env(check::create(alice, bob, USD(50)), expiration(env.now()), ter(tecEXPIRED)); + env.close(); + + using namespace std::chrono_literals; + env(check::create(alice, bob, USD(50)), expiration(env.now() + 1s)); + env.close(); + + // Insufficient reserve. + Account const cheri{"cheri"}; + env.fund(env.current()->fees().accountReserve(1) - drops(1), cheri); + + env(check::create(cheri, bob, USD(50)), + fee(drops(env.current()->fees().base)), + ter(tecINSUFFICIENT_RESERVE)); + env.close(); + + env(pay(bob, cheri, drops(env.current()->fees().base + 1))); + env.close(); + + env(check::create(cheri, bob, USD(50))); + env.close(); + } + + void + testCashMPT(FeatureBitset features) + { + // Explore many of the valid ways to cash a check for an MPT. + testcase("Cash MPT"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + { + // Simple MPT check cashed with Amount (with failures). + Env env{*this, features}; + + env.fund(XRP(1'000), gw, alice, bob); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 105}); + + // alice writes the check before she gets the funds. + uint256 const chkId1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(100))); + env.close(); + + // bob attempts to cash the check. Should fail. + env(check::cash(bob, chkId1, USD(100)), ter(tecPATH_PARTIAL)); + env.close(); + + // alice gets almost enough funds. bob tries and fails again. + env(pay(gw, alice, USD(95))); + env.close(); + env(check::cash(bob, chkId1, USD(100)), ter(tecPATH_PARTIAL)); + env.close(); + + // alice gets the last of the necessary funds. + env(pay(gw, alice, USD(5))); + env.close(); + + // bob for more than the check's SendMax. + env.close(); + env(check::cash(bob, chkId1, USD(105)), ter(tecPATH_PARTIAL)); + env.close(); + + // bob asks for exactly the check amount and the check clears. + // MPT is authorized automatically + env(check::cash(bob, chkId1, USD(100))); + env.close(); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(100))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // bob tries to cash the same check again, which fails. + env(check::cash(bob, chkId1, USD(100)), ter(tecNO_ENTRY)); + env.close(); + + // bob pays alice USD(70) so he can try another case. + env(pay(bob, alice, USD(70))); + env.close(); + + uint256 const chkId2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(70))); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 1); + + // bob cashes the check for less than the face amount. That works, + // consumes the check, and bob receives as much as he asked for. + env(check::cash(bob, chkId2, USD(50))); + env.close(); + env.require(balance(alice, USD(20))); + env.require(balance(bob, USD(80))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // alice writes two checks for USD(20), although she only has + // USD(20). + uint256 const chkId3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(20))); + env.close(); + uint256 const chkId4{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(20))); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 2); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 2); + + // bob cashes the second check for the face amount. + env(check::cash(bob, chkId4, USD(20))); + env.close(); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(100))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 1); + BEAST_EXPECT(ownerCount(env, alice) == 2); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // bob is not allowed to cash the last check for USD(0), he must + // use check::cancel instead. + env(check::cash(bob, chkId3, USD(0)), ter(temBAD_AMOUNT)); + env.close(); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(100))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 1); + BEAST_EXPECT(ownerCount(env, alice) == 2); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + { + // Unlike IOU, cashing a check exceeding the MPT limit doesn't + // work. Show that at work. + // + // MPT limit is USD(105). Show that + // neither a payment to bob or caching can exceed that limit. + + // Payment of 200 USD fails. + env(pay(gw, bob, USD(200)), ter(tecPATH_PARTIAL)); + env.close(); + + uint256 const chkId20{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, bob, USD(200))); + env.close(); + + // Cashing a check for 200 USD fails. + env(check::cash(bob, chkId20, USD(200)), ter(tecPATH_PARTIAL)); + env.close(); + env.require(balance(bob, USD(100))); + + // Clean up this most recent experiment so the rest of the + // tests work. + env(pay(bob, gw, USD(100))); + env(check::cancel(bob, chkId20)); + } + + // ... so bob cancels alice's remaining check. + env(check::cancel(bob, chkId3)); + env.close(); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(0))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == 1); + } + { + // Simple MPT check cashed with DeliverMin (with failures). + Env env{*this, features}; + + env.fund(XRP(1'000), gw, alice, bob); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20}); + + env(pay(gw, alice, USD(8))); + env.close(); + + // alice creates several checks ahead of time. + uint256 const chkId9{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(9))); + env.close(); + uint256 const chkId8{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(8))); + env.close(); + uint256 const chkId7{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(7))); + env.close(); + uint256 const chkId6{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(6))); + env.close(); + + // bob attempts to cash a check for the amount on the check. + // Should fail, since alice doesn't have the funds. + env(check::cash(bob, chkId9, check::DeliverMin(USD(9))), ter(tecPATH_PARTIAL)); + env.close(); + + // bob sets a DeliverMin of 7 and gets all that alice has. + env(check::cash(bob, chkId9, check::DeliverMin(USD(7)))); + verifyDeliveredAmount(env, USD(8)); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(8))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 3); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 3); + BEAST_EXPECT(ownerCount(env, alice) == 4); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // bob pays alice USD(7) so he can use another check. + env(pay(bob, alice, USD(7))); + env.close(); + + // Using DeliverMin for the SendMax value of the check (and no + // transfer fees) should work just like setting Amount. + env(check::cash(bob, chkId7, check::DeliverMin(USD(7)))); + verifyDeliveredAmount(env, USD(7)); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(8))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 2); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 2); + BEAST_EXPECT(ownerCount(env, alice) == 3); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // bob pays alice USD(8) so he can use the last two checks. + env(pay(bob, alice, USD(8))); + env.close(); + + // alice has USD(8). If bob uses the check for USD(6) and uses a + // DeliverMin of 4, he should get the SendMax value of the check. + env(check::cash(bob, chkId6, check::DeliverMin(USD(4)))); + verifyDeliveredAmount(env, USD(6)); + env.require(balance(alice, USD(2))); + env.require(balance(bob, USD(6))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 1); + BEAST_EXPECT(ownerCount(env, alice) == 2); + BEAST_EXPECT(ownerCount(env, bob) == 1); + + // bob cashes the last remaining check setting a DeliverMin. + // of exactly alice's remaining USD. + env(check::cash(bob, chkId8, check::DeliverMin(USD(2)))); + verifyDeliveredAmount(env, USD(2)); + env.require(balance(alice, USD(0))); + env.require(balance(bob, USD(8))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == 1); + } + { + // Examine the effects of the asfRequireAuth flag. + Env env(*this, features); + + env.fund(XRP(1000), gw, alice, bob); + auto USDM = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .flags = MPTDEXFlags | tfMPTRequireAuth, + .maxAmt = 20}); + MPT const USD = USDM; + USDM.authorize({.holder = alice}); + env.close(); + env(pay(gw, alice, USD(8))); + env.close(); + + // alice writes a check to bob for USD. bob can't cash it + // because he is not authorized to hold gw["USD"]. + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(7))); + env.close(); + + env(check::cash(bob, chkId, USD(7)), ter(tecNO_AUTH)); + env.close(); + + // Now give bob MPT for USD. bob still can't cash the + // check because he is not authorized. + USDM.authorize({.account = bob}); + env.close(); + + env(check::cash(bob, chkId, USD(7)), ter(tecNO_AUTH)); + env.close(); + + // bob gets authorization to hold USD. + USDM.authorize({.holder = bob}); + env.close(); + + env(check::cash(bob, chkId, check::DeliverMin(USD(4)))); + STAmount const bobGot = USD(7); + verifyDeliveredAmount(env, bobGot); + env.require(balance(alice, USD(8) - bobGot)); + env.require(balance(bob, bobGot)); + + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == 1); + } + + { + Env env{*this, features}; + + env.fund(XRP(1'000), gw, alice, bob); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20}); + + // alice creates her checks ahead of time. + uint256 const chkId1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(1))); + env.close(); + + uint256 const chkId2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(2))); + env.close(); + + env(pay(gw, alice, USD(8))); + env.close(); + + // Give bob a regular key and signers + Account const bobby{"bobby", KeyType::secp256k1}; + env(regkey(bob, bobby)); + env.close(); + + Account const bogie{"bogie", KeyType::secp256k1}; + Account const demon{"demon", KeyType::ed25519}; + env(signers(bob, 2, {{bogie, 1}, {demon, 1}}), sig(bobby)); + env.close(); + + int const signersCount = 1; + BEAST_EXPECT(ownerCount(env, bob) == signersCount + 1); + + // bob uses his regular key to cash a check. + env(check::cash(bob, chkId1, (USD(1))), sig(bobby)); + env.close(); + env.require(balance(alice, USD(7))); + env.require(balance(bob, USD(1))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 1); + BEAST_EXPECT(ownerCount(env, alice) == 2); + BEAST_EXPECT(ownerCount(env, bob) == signersCount + 1); + + // bob uses multisigning to cash a check. + XRPAmount const baseFeeDrops{env.current()->fees().base}; + env(check::cash(bob, chkId2, (USD(2))), msig(bogie, demon), fee(3 * baseFeeDrops)); + env.close(); + env.require(balance(alice, USD(5))); + env.require(balance(bob, USD(3))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + BEAST_EXPECT(ownerCount(env, alice) == 1); + BEAST_EXPECT(ownerCount(env, bob) == signersCount + 1); + } + } + + void + testCashXferFee(FeatureBitset features) + { + // Look at behavior when the issuer charges a transfer fee. + testcase("Cash with transfer fee"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, features}; + + env.fund(XRP(1'000), gw, alice, bob); + + // Set gw's transfer rate and see the consequences when cashing a check. + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 25'000, + .maxAmt = 1'000}); + + env.close(); + env(pay(gw, alice, USD(1'000))); + env.close(); + + // alice writes a check with a SendMax of USD(125). The most bob + // can get is USD(100) because of the transfer rate. + uint256 const chkId125{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(125))); + env.close(); + + // alice writes another check that won't get cashed until the transfer + // rate changes so we can see the rate applies when the check is + // cashed, not when it is created. +#if 0 + uint256 const chkId120{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(120))); + env.close(); +#endif + + // bob attempts to cash the check for face value. Should fail. + env(check::cash(bob, chkId125, USD(125)), ter(tecPATH_PARTIAL)); + env.close(); + env(check::cash(bob, chkId125, check::DeliverMin(USD(101))), ter(tecPATH_PARTIAL)); + env.close(); + + // bob decides that he'll accept anything USD(75) or up. + // He gets USD(100). + env(check::cash(bob, chkId125, check::DeliverMin(USD(75)))); + verifyDeliveredAmount(env, USD(100)); + env.require(balance(alice, USD(1'000 - 125))); + env.require(balance(bob, USD(0 + 100))); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(checksOnAccount(env, bob).empty()); + +#if 0 + // Adjust gw's rate... + env(rate(gw, 1.2)); + env.close(); + + // bob cashes the second check for less than the face value. The new + // rate applies to the actual value transferred. + env(check::cash(bob, chkId120, USD(50))); + env.close(); + env.require(balance(alice, USD(1000 - 125 - 60))); + env.require(balance(bob, USD(0 + 100 + 50))); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 0); + BEAST_EXPECT(checksOnAccount(env, bob).size() == 0); +#endif + } + + void + testCashInvalid(FeatureBitset features) + { + // Explore many of the ways to fail at cashing a check. + testcase("Cash invalid"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const zoe{"zoe"}; + std::int64_t maxAmt{20}; + + Env env(*this, features); + + env.fund(XRP(1000), gw, alice, bob, zoe); + + auto USDM = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .flags = MPTDEXFlags | tfMPTCanLock, + .maxAmt = maxAmt}); + MPT const USD = USDM; + + env(pay(gw, alice, USD(20))); + env.close(); + + USDM.authorize({.account = bob}); + + // bob tries to cash a non-existent check from alice. + { + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::cash(bob, chkId, USD(20)), ter(tecNO_ENTRY)); + env.close(); + } + + // alice creates her checks ahead of time. + uint256 const chkIdU{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(20))); + env.close(); + + uint256 const chkIdX{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10))); + env.close(); + + using namespace std::chrono_literals; + uint256 const chkIdExp{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 1s)); + env.close(); + + uint256 const chkIdFroz1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(1))); + env.close(); + + uint256 const chkIdFroz2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(2))); + env.close(); + + uint256 const chkIdFroz3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(3))); + env.close(); + + uint256 const chkIdNoDest1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(1))); + env.close(); + + uint256 const chkIdHasDest2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(2)), dest_tag(7)); + env.close(); + + // Same set of failing cases for both MPT and XRP check cashing. + auto failingCases = [&env, &gw, &alice, &bob]( + uint256 const& chkId, STAmount const& amount) { + // Bad fee. + env(check::cash(bob, chkId, amount), fee(drops(-10)), ter(temBAD_FEE)); + env.close(); + + // Bad flags. + env(check::cash(bob, chkId, amount), + txflags(tfImmediateOrCancel), + ter(temINVALID_FLAG)); + env.close(); + + // Missing both Amount and DeliverMin. + { + Json::Value tx{check::cash(bob, chkId, amount)}; + tx.removeMember(sfAmount.jsonName); + env(tx, ter(temMALFORMED)); + env.close(); + } + // Both Amount and DeliverMin present. + { + Json::Value tx{check::cash(bob, chkId, amount)}; + tx[sfDeliverMin.jsonName] = amount.getJson(JsonOptions::none); + env(tx, ter(temMALFORMED)); + env.close(); + } + + // Negative or zero amount. + { + STAmount neg{amount}; + neg.negate(); + env(check::cash(bob, chkId, neg), ter(temBAD_AMOUNT)); + env.close(); + env(check::cash(bob, chkId, amount.zeroed()), ter(temBAD_AMOUNT)); + env.close(); + } + + // Bad currency. + if (!amount.native()) + { + Issue const badIssue{badCurrency(), amount.getIssuer()}; + STAmount badAmount{amount}; + badAmount.setIssue(Issue{badCurrency(), amount.getIssuer()}); + env(check::cash(bob, chkId, badAmount), ter(temBAD_CURRENCY)); + env.close(); + } + + // Not destination cashing check. + env(check::cash(alice, chkId, amount), ter(tecNO_PERMISSION)); + env.close(); + env(check::cash(gw, chkId, amount), ter(tecNO_PERMISSION)); + env.close(); + + // Currency mismatch. + { + MPT const EUR = MPTTester({.env = env, .issuer = gw}); + STAmount const badAmount{EUR, amount}; + env(check::cash(bob, chkId, badAmount), ter(temMALFORMED)); + env.close(); + } + + // Issuer mismatch. + // Every MPT is unique. There is no USD MPT with different issuers. + + // Amount bigger than SendMax. + env(check::cash(bob, chkId, amount + amount), ter(tecPATH_PARTIAL)); + env.close(); + + // DeliverMin bigger than SendMax. + env(check::cash(bob, chkId, check::DeliverMin(amount + amount)), ter(tecPATH_PARTIAL)); + env.close(); + }; + + failingCases(chkIdX, XRP(10)); + failingCases(chkIdU, USD(20)); + + // Verify that those two checks really were cashable. + env(check::cash(bob, chkIdU, USD(20))); + env.close(); + env(check::cash(bob, chkIdX, check::DeliverMin(XRP(10)))); + verifyDeliveredAmount(env, XRP(10)); + + // Try to cash an expired check. + env(check::cash(bob, chkIdExp, XRP(10)), ter(tecEXPIRED)); + env.close(); + + // Cancel the expired check. Anyone can cancel an expired check. + env(check::cancel(zoe, chkIdExp)); + env.close(); + + // Can we cash a check with frozen MPT? + { + env(pay(bob, alice, USD(20))); + env.close(); + env.require(balance(alice, USD(20))); + env.require(balance(bob, USD(0))); + + // Global freeze + USDM.set({.flags = tfMPTLock}); + + // MPTLocked flag is set and the account is not the issuer of MPT + env(check::cash(bob, chkIdFroz1, USD(1)), ter(tecPATH_PARTIAL)); + env.close(); + env(check::cash(bob, chkIdFroz1, check::DeliverMin(USD(1))), ter(tecPATH_PARTIAL)); + env.close(); + + USDM.set({.flags = tfMPTUnlock}); + + // No longer frozen. Success. + env(check::cash(bob, chkIdFroz1, USD(1))); + env.close(); + env.require(balance(alice, USD(19))); + env.require(balance(bob, USD(1))); + + // Freeze individual MPT. + USDM.set({.holder = alice, .flags = tfMPTLock}); + env(check::cash(bob, chkIdFroz2, USD(2)), ter(tecPATH_PARTIAL)); + env.close(); + env(check::cash(bob, chkIdFroz2, check::DeliverMin(USD(1))), ter(tecPATH_PARTIAL)); + env.close(); + + // Clear that freeze. Now check cashing works. + USDM.set({.holder = alice, .flags = tfMPTUnlock}); + env(check::cash(bob, chkIdFroz2, USD(2))); + env.close(); + env.require(balance(alice, USD(17))); + env.require(balance(bob, USD(3))); + + // Freeze bob's MPT. bob can't cash the check. + USDM.set({.holder = bob, .flags = tfMPTLock}); + env(check::cash(bob, chkIdFroz3, USD(3)), ter(tecLOCKED)); + env.close(); + env(check::cash(bob, chkIdFroz3, check::DeliverMin(USD(1))), ter(tecLOCKED)); + env.close(); + + // Clear that freeze. Now check cashing works again. + USDM.set({.holder = bob, .flags = tfMPTUnlock}); + env.close(); + env(check::cash(bob, chkIdFroz3, check::DeliverMin(USD(1)))); + verifyDeliveredAmount(env, USD(3)); + env.require(balance(alice, USD(14))); + env.require(balance(bob, USD(6))); + } + { + // Set the RequireDest flag on bob's account (after the check + // was created) then cash a check without a destination tag. + env(fset(bob, asfRequireDest)); + env.close(); + env(check::cash(bob, chkIdNoDest1, USD(1)), ter(tecDST_TAG_NEEDED)); + env.close(); + env(check::cash(bob, chkIdNoDest1, check::DeliverMin(USD(1))), ter(tecDST_TAG_NEEDED)); + env.close(); + + // bob can cash a check with a destination tag. + env(check::cash(bob, chkIdHasDest2, USD(2))); + env.close(); + + env.require(balance(alice, USD(12))); + env.require(balance(bob, USD(8))); + + // Clear the RequireDest flag on bob's account so he can + // cash the check with no DestinationTag. + env(fclear(bob, asfRequireDest)); + env.close(); + env(check::cash(bob, chkIdNoDest1, USD(1))); + env.close(); + env.require(balance(alice, USD(11))); + env.require(balance(bob, USD(9))); + } + + // OutstandingAmount exceeds MaximumAmount + { + // Already at maximum + BEAST_EXPECT(env.balance(gw, USDM) == USDM(-maxAmt)); + + uint256 const chkId{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, bob, USDM(10))); + env.close(); + + // Exceeds MaximumAmount (20 + 10) = 30 > 20 + env(check::cash(bob, chkId, USDM(10)), ter(tecPATH_PARTIAL)); + env.close(); + + // Redeem some tokens (20 - 9) = 11 + env(pay(alice, gw, USDM(9))); + env.close(); + + // Still exceeds MaximumAmount (11 + 10) = 21 > 20 + env(check::cash(bob, chkId, USDM(10)), ter(tecPATH_PARTIAL)); + env.close(); + } + } + + void + testCancelValid(FeatureBitset features) + { + // Explore many of the ways to cancel a check. + testcase("Cancel valid"); + + using namespace test::jtx; + + Account const gw{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const zoe{"zoe"}; + + { + Env env{*this, features}; + + env.fund(XRP(1'000), gw, alice, bob, zoe); + + MPT const USD = MPTTester({.env = env, .issuer = gw}); + + // alice creates her checks ahead of time. + // Three ordinary checks with no expiration. + uint256 const chkId1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10))); + env.close(); + + uint256 const chkId2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10))); + env.close(); + + uint256 const chkId3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10))); + env.close(); + + // Three checks that expire in 10 minutes. + using namespace std::chrono_literals; + uint256 const chkIdNotExp1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 600s)); + env.close(); + + uint256 const chkIdNotExp2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10)), expiration(env.now() + 600s)); + env.close(); + + uint256 const chkIdNotExp3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 600s)); + env.close(); + + // Three checks that expire in one second. + uint256 const chkIdExp1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10)), expiration(env.now() + 1s)); + env.close(); + + uint256 const chkIdExp2{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10)), expiration(env.now() + 1s)); + env.close(); + + uint256 const chkIdExp3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10)), expiration(env.now() + 1s)); + env.close(); + + // Two checks to cancel using a regular key and using multisigning. + uint256 const chkIdReg{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, USD(10))); + env.close(); + + uint256 const chkIdMSig{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, XRP(10))); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 11); + BEAST_EXPECT(ownerCount(env, alice) == 11); + + // Creator, destination, and an outsider cancel the checks. + env(check::cancel(alice, chkId1)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 10); + BEAST_EXPECT(ownerCount(env, alice) == 10); + + env(check::cancel(bob, chkId2)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 9); + BEAST_EXPECT(ownerCount(env, alice) == 9); + + env(check::cancel(zoe, chkId3), ter(tecNO_PERMISSION)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 9); + BEAST_EXPECT(ownerCount(env, alice) == 9); + + // Creator, destination, and an outsider cancel unexpired checks. + env(check::cancel(alice, chkIdNotExp1)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 8); + BEAST_EXPECT(ownerCount(env, alice) == 8); + + env(check::cancel(bob, chkIdNotExp2)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 7); + BEAST_EXPECT(ownerCount(env, alice) == 7); + + env(check::cancel(zoe, chkIdNotExp3), ter(tecNO_PERMISSION)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 7); + BEAST_EXPECT(ownerCount(env, alice) == 7); + + // Creator, destination, and an outsider cancel expired checks. + env(check::cancel(alice, chkIdExp1)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 6); + BEAST_EXPECT(ownerCount(env, alice) == 6); + + env(check::cancel(bob, chkIdExp2)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 5); + BEAST_EXPECT(ownerCount(env, alice) == 5); + + env(check::cancel(zoe, chkIdExp3)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 4); + BEAST_EXPECT(ownerCount(env, alice) == 4); + + // Use a regular key and also multisign to cancel checks. + Account const alie{"alie", KeyType::ed25519}; + env(regkey(alice, alie)); + env.close(); + + Account const bogie{"bogie", KeyType::secp256k1}; + Account const demon{"demon", KeyType::ed25519}; + env(signers(alice, 2, {{bogie, 1}, {demon, 1}}), sig(alie)); + env.close(); + + int const signersCount{1}; + + // alice uses her regular key to cancel a check. + env(check::cancel(alice, chkIdReg), sig(alie)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 3); + BEAST_EXPECT(ownerCount(env, alice) == signersCount + 3); + + // alice uses multisigning to cancel a check. + XRPAmount const baseFeeDrops{env.current()->fees().base}; + env(check::cancel(alice, chkIdMSig), msig(bogie, demon), fee(3 * baseFeeDrops)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 2); + BEAST_EXPECT(ownerCount(env, alice) == signersCount + 2); + + // Creator and destination cancel the remaining unexpired checks. + env(check::cancel(alice, chkId3), sig(alice)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 1); + BEAST_EXPECT(ownerCount(env, alice) == signersCount + 1); + + env(check::cancel(bob, chkIdNotExp3)); + env.close(); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(ownerCount(env, alice) == signersCount + 0); + } + } + + void + testWithTickets(FeatureBitset features) + { + testcase("With Tickets"); + + using namespace test::jtx; + + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, bob); + env.close(); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 1'000}); + + // alice and bob grab enough tickets for all the following + // transactions. Note that once the tickets are acquired alice's + // and bob's account sequence numbers should not advance. + std::uint32_t aliceTicketSeq{env.seq(alice) + 1}; + env(ticket::create(alice, 10)); + std::uint32_t const aliceSeq{env.seq(alice)}; + + std::uint32_t bobTicketSeq{env.seq(bob) + 1}; + env(ticket::create(bob, 10)); + std::uint32_t const bobSeq{env.seq(bob)}; + + env.close(); + // MPT + 10 tickets + env.require(owners(alice, 11)); + env.require(owners(bob, 11)); + + env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); + BEAST_EXPECT(env.seq(alice) == aliceSeq); + + env.require(tickets(bob, env.seq(bob) - bobTicketSeq)); + BEAST_EXPECT(env.seq(bob) == bobSeq); + + env(pay(gw, alice, USD(900))); + env.close(); + + // alice creates four checks; two XRP, two MPT. Bob will cash + // one of each and cancel one of each. + uint256 const chkIdXrp1{getCheckIndex(alice, aliceTicketSeq)}; + env(check::create(alice, bob, XRP(200)), ticket::use(aliceTicketSeq++)); + + uint256 const chkIdXrp2{getCheckIndex(alice, aliceTicketSeq)}; + env(check::create(alice, bob, XRP(300)), ticket::use(aliceTicketSeq++)); + + uint256 const chkIdUsd1{getCheckIndex(alice, aliceTicketSeq)}; + env(check::create(alice, bob, USD(200)), ticket::use(aliceTicketSeq++)); + + uint256 const chkIdUsd2{getCheckIndex(alice, aliceTicketSeq)}; + env(check::create(alice, bob, USD(300)), ticket::use(aliceTicketSeq++)); + + env.close(); + // Alice used four tickets but created four checks. + env.require(owners(alice, 11)); + env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 4); + BEAST_EXPECT(env.seq(alice) == aliceSeq); + + env.require(owners(bob, 11)); + BEAST_EXPECT(env.seq(bob) == bobSeq); + + // Bob cancels two of alice's checks. + env(check::cancel(bob, chkIdXrp1), ticket::use(bobTicketSeq++)); + env(check::cancel(bob, chkIdUsd2), ticket::use(bobTicketSeq++)); + env.close(); + + env.require(owners(alice, 9)); + env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); + BEAST_EXPECT(checksOnAccount(env, alice).size() == 2); + BEAST_EXPECT(env.seq(alice) == aliceSeq); + + env.require(owners(bob, 9)); + BEAST_EXPECT(env.seq(bob) == bobSeq); + + // Bob cashes alice's two remaining checks. + env(check::cash(bob, chkIdXrp2, XRP(300)), ticket::use(bobTicketSeq++)); + env(check::cash(bob, chkIdUsd1, USD(200)), ticket::use(bobTicketSeq++)); + env.close(); + + auto const baseFee = env.current()->fees().base; + env.require(owners(alice, 7)); + env.require(tickets(alice, env.seq(alice) - aliceTicketSeq)); + BEAST_EXPECT(checksOnAccount(env, alice).empty()); + BEAST_EXPECT(env.seq(alice) == aliceSeq); + env.require(balance(alice, USD(700))); + env.require(balance(alice, XRP(700) - 6 * baseFee)); + env.require(owners(bob, 7)); + BEAST_EXPECT(env.seq(bob) == bobSeq); + env.require(balance(bob, USD(200))); + env.require(balance(bob, XRP(1'300) - 6 * baseFee)); + } + + void + testMPTCreation(FeatureBitset features) + { + // Explore automatic MPT creation when a check is cashed. + + testcase("MPT Creation"); + + using namespace test::jtx; + + Env env{*this, features}; + + // An account that independently tracks its owner count. + struct AccountOwns + { + using iterator = hash_map::iterator; + beast::unit_test::suite& suite; + Env& env; + Account const acct; + std::size_t owners{0}; + hash_map mpts; + bool const isIssuer; + bool const requireAuth; + + AccountOwns( + beast::unit_test::suite& s, + Env& e, + Account const& a, + bool isIssuer_, + bool requireAuth_ = false) + : suite(s), env(e), acct(a), isIssuer(isIssuer_), requireAuth(requireAuth_) + { + } + + void + verifyOwners(std::uint32_t line, bool print = false) const + { + if (print) + { + std::cout << acct.name() << " " << ownerCount(env, acct) << " " << owners + << std::endl; + } + suite.expect( + ownerCount(env, acct) == owners, "Owner count mismatch", __FILE__, line); + } + + // Operators to make using the class more convenient. + operator Account() const + { + return acct; + } + + operator xrpl::AccountID() const + { + return acct.id(); + } + + /** Create MPTTester if it doesn't exist for the given MPT. + * Increment owners if created since it creates MPTokenIssuance + */ + MPT + operator[](std::string const& s) + { + if (!isIssuer) + Throw("AccountOwns: must be issuer"); + if (auto const& it = mpts.find(s); it != mpts.end()) + return it->second[s]; + auto flags = MPTDEXFlags | tfMPTCanLock; + if (requireAuth) + flags |= tfMPTRequireAuth; + auto [it, _] = + mpts.emplace(s, MPTTester({.env = env, .issuer = acct, .flags = flags})); + (void)_; + ++owners; + + return it->second[s]; + } + + iterator + getIt(MPT const& mpt) + { + if (!isIssuer) + Throw("AccountOwns::set must be issuer"); + auto it = mpts.find(mpt.name); + if (it == mpts.end()) + Throw("AccountOwns::set mpt doesn't exist"); + return it; + } + + void + set(MPT const& mpt, std::uint32_t flag) + { + auto it = getIt(mpt); + it->second.set({.flags = flag}); + } + + void + authorize(MPT const& mpt, AccountOwns& id) + { + auto it = getIt(mpt); + it->second.authorize({.account = id}); + ++id.owners; + } + + void + cleanup(MPT const& mpt, AccountOwns& id) + { + auto it = getIt(mpt); + // redeem to the issuer + if (auto const redeem = it->second.getBalance(id)) + pay(it, id, acct, redeem); + // delete mptoken + it->second.authorize({.account = id, .flags = tfMPTUnauthorize}); + --id.owners; + } + + void + pay(iterator& it, Account const& src, Account const& dst, std::uint64_t amount) + { + if (env.le(keylet::account(dst))->isFlag(lsfDepositAuth)) + { + env(fclear(dst, asfDepositAuth)); + it->second.pay(src, dst, amount); + env(fset(dst, asfDepositAuth)); + } + else + { + it->second.pay(src, dst, amount); + } + } + + void + pay(Account const& src, Account const& dst, PrettyAmount amount) + { + auto it = getIt(amount.name()); + pay(it, src, dst, amount.value().mpt().value()); + } + }; + + AccountOwns alice{*this, env, "alice", false}; + AccountOwns bob{*this, env, "bob", false}; + AccountOwns gw1{*this, env, "gw1", true}; + + // Fund with noripple so the accounts do not have any flags set. + env.fund(XRP(5000), noripple(alice, bob)); + env.close(); + + // Automatic MPT creation should fail if the check destination + // can't afford the reserve for the trust line. + { + // Fund gw1 with noripple (even though that's atypical for a + // gateway) so it does not have any flags set. We'll set flags + // on gw1 later. + env.fund(XRP(5'000), noripple(gw1)); + env.close(); + + MPT const CK8 = gw1["CK8"]; + gw1.verifyOwners(__LINE__); + + Account const yui{"yui"}; + + // Note the reserve in unit tests is 200 XRP, not 20. So here + // we're just barely giving yui enough XRP to meet the + // account reserve. + env.fund(XRP(200), yui); + env.close(); + + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, yui, CK8(99))); + env.close(); + + env(check::cash(yui, chkId, CK8(99)), ter(tecINSUFFICIENT_RESERVE)); + env.close(); + alice.verifyOwners(__LINE__); + + // Give yui enough XRP to meet the trust line's reserve. Cashing + // the check succeeds and creates the trust line. + env(pay(env.master, yui, XRP(51))); + env.close(); + env(check::cash(yui, chkId, CK8(99))); + verifyDeliveredAmount(env, CK8(99)); + env.close(); + BEAST_EXPECT(ownerCount(env, yui) == 1); + + // The automatic trust line does not take a reserve from gw1. + // Since gw1's check was consumed it has no owners. + gw1.verifyOwners(__LINE__); + } + + // We'll be looking at the effects of various account root flags and + // MPT flags. + + // Automatically create MPT using + // o Offers and + // o Check cashing + + //----------- No account root flags, check written by issuer ----------- + { + // No account root flags on any participant. + // Automatic trust line from issuer to destination. + + BEAST_EXPECT((*env.le(gw1))[sfFlags] == 0); + BEAST_EXPECT((*env.le(alice))[sfFlags] == 0); + BEAST_EXPECT((*env.le(bob))[sfFlags] == 0); + + // Use offers to automatically create MPT + MPT const OF1 = gw1["OF1"]; + env(offer(gw1, XRP(98), OF1(98))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF1.issuanceID, alice)) == nullptr); + env(offer(alice, OF1(98), XRP(98))); + ++alice.owners; + env.close(); + + // Both offers should be consumed. + // Since gw1's offer was consumed and the trust line was not + // created by gw1, gw1's owner count should be 0. + gw1.verifyOwners(__LINE__); + + // alice's automatically created MPT bumps her owner count. + alice.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK1 = gw1["CK1"]; + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, alice, CK1(98))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK1.issuanceID, alice)) == nullptr); + env(check::cash(alice, chkId, CK1(98))); + ++alice.owners; + verifyDeliveredAmount(env, CK1(98)); + env.close(); + + // gw1's check should be consumed. + // Since gw1's check was consumed and the trust line was not + // created by gw1, gw1's owner count should be 0. + gw1.verifyOwners(__LINE__); + + // alice's automatically created trust line bumps her owner count. + alice.verifyOwners(__LINE__); + + // cmpTrustLines(gw1, alice, OF1, CK1); + } + //--------- No account root flags, check written by non-issuer --------- + { + // No account root flags on any participant. + + // Use offers to automatically create MPT. + // Transfer of assets using offers does not require rippling. + // So bob's offer is successfully crossed which creates MPT. + MPT const OF1 = gw1["OF1"]; + env(offer(alice, XRP(97), OF1(97))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF1, bob)) == nullptr); + env(offer(bob, OF1(97), XRP(97))); + ++bob.owners; + env.close(); + + // Both offers should be consumed. + env.require(balance(alice, OF1(1))); + env.require(balance(bob, OF1(97))); + + // bob now has an owner count of 1 due to new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + // + // Unlike IOU where cashing a check (unlike crossing offers) + // requires rippling through the currency's issuer, rippling doesn't + // impact MPT. Even though gw1 does not have rippling enabled, the + // check cash succeeds for MPT and MPT is created. + MPT const CK1 = gw1["CK1"]; + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK1(97))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK1, bob)) == nullptr); + env(check::cash(bob, chkId, CK1(97))); + ++bob.owners; + env.close(); + + BEAST_EXPECT(env.le(keylet::mptoken(OF1, bob)) != nullptr); + + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + } + + //------------- lsfDefaultRipple, check written by issuer -------------- + { + // gw1 enables rippling. + // This doesn't impact automatic MPT creation. + env(fset(gw1, asfDefaultRipple)); + env.close(); + + // Use offers to automatically create the trust line. + MPT const OF2 = gw1["OF2"]; + env(offer(gw1, XRP(96), OF2(96))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF2, alice)) == nullptr); + env(offer(alice, OF2(96), XRP(96))); + ++alice.owners; + env.close(); + + // Both offers should be consumed. + // Since gw1's offer was consumed, gw1 owner count doesn't change. + gw1.verifyOwners(__LINE__); + + // alice's automatically created MPT bumps her owner count. + alice.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK2 = gw1["CK2"]; + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, alice, CK2(96))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK2, alice)) == nullptr); + env(check::cash(alice, chkId, CK2(96))); + ++alice.owners; + verifyDeliveredAmount(env, CK2(96)); + env.close(); + + // gw1's check should be consumed. + // Since gw1's check was consumed and MPT was not + // created by gw1, gw1's owner count doesn't change. + gw1.verifyOwners(__LINE__); + + // alice's automatically created trust line bumps her owner count. + alice.verifyOwners(__LINE__); + } + + //----------- lsfDefaultRipple, check written by non-issuer ------------ + { + // gw1 enabled rippling doesn't impact MPT, so automatic MPT from + // non-issuer to non-issuer should work. + + // Use offers to automatically create MPT. + MPT const OF2 = gw1["OF2"]; + env(offer(alice, XRP(95), OF2(95))); + env.close(); + // alice already has OF2 MPT + BEAST_EXPECT(env.le(keylet::mptoken(OF2, alice)) != nullptr); + env(offer(bob, OF2(95), XRP(95))); + ++bob.owners; + env.close(); + + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK2 = gw1["CK2"]; + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK2(95))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK2, bob)) == nullptr); + env(check::cash(bob, chkId, CK2(95))); + ++bob.owners; + verifyDeliveredAmount(env, CK2(95)); + env.close(); + + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + } + + //-------------- lsfDepositAuth, check written by issuer --------------- + { + // Both offers and checks ignore the lsfDepositAuth flag, since + // the destination signs the transaction that delivers their funds. + // So setting lsfDepositAuth on all the participants should not + // change any outcomes. + // + // Automatic MPT from issuer to non-issuer should still work. + env(fset(gw1, asfDepositAuth)); + env(fset(alice, asfDepositAuth)); + env(fset(bob, asfDepositAuth)); + env.close(); + + // Use offers to automatically create MPT. + MPT const OF3 = gw1["OF3"]; + env(offer(gw1, XRP(94), OF3(94))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF3, alice)) == nullptr); + env(offer(alice, OF3(94), XRP(94))); + ++alice.owners; + env.close(); + + // Both offers should be consumed. + // Since gw1's offer was consumed and MPT was not + // created by gw1, gw1's owner count doesn't change. + gw1.verifyOwners(__LINE__); + + // alice's automatically created MPT bumps her owner count. + alice.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK3 = gw1["CK3"]; + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, alice, CK3(94))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK3, alice)) == nullptr); + env(check::cash(alice, chkId, CK3(94))); + ++alice.owners; + verifyDeliveredAmount(env, CK3(94)); + env.close(); + + // gw1's check should be consumed. + // Since gw1's check was consumed and MPT was not + // created by gw1, gw1's owner count doesn't change. + gw1.verifyOwners(__LINE__); + + // alice's automatically created trust line bumps her owner count. + alice.verifyOwners(__LINE__); + } + + //------------ lsfDepositAuth, check written by non-issuer ------------- + { + // The presence of the lsfDepositAuth flag should not affect + // automatic MPT creation. + + // Use offers to automatically create MPT. + MPT const OF3 = gw1["OF3"]; + env(offer(alice, XRP(93), OF3(93))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF3, alice)) != nullptr); + env(offer(bob, OF3(93), XRP(93))); + ++bob.owners; + env.close(); + + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK3 = gw1["CK3"]; + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK3(93))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK3, bob)) == nullptr); + env(check::cash(bob, chkId, CK3(93))); + ++bob.owners; + verifyDeliveredAmount(env, CK3(93)); + env.close(); + + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + } + + //-------------- lsfGlobalFreeze, check written by issuer -------------- + { + // Set lsfGlobalFreeze on gw1. That should not stop any automatic + // MPT from being created. + env(fset(gw1, asfGlobalFreeze)); + env.close(); + + // Use offers to automatically create MPT. + MPT const OF4 = gw1["OF4"]; + env(offer(gw1, XRP(92), OF4(92))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF4, alice)) == nullptr); + env(offer(alice, OF4(92), XRP(92))); + ++alice.owners; + env.close(); + + // alice's owner count should increase do to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK4 = gw1["CK4"]; + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, bob, CK4(92))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, bob)) == nullptr); + env(check::cash(bob, chkId, CK4(92))); + verifyDeliveredAmount(env, CK4(92)); + ++bob.owners; + env.close(); + + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // clean up + gw1.cleanup(OF4, alice); + gw1.cleanup(CK4, bob); + } + + //-------------- lsfMPTLock, check written by issuer -------------- + { + // Set lsfMPTLock on gw1. That should stop any automatic + // MPT from being created. + + // Use offers to automatically create MPT. + MPT const OF4 = gw1["OF4"]; + gw1.set(OF4, tfMPTLock); + env(offer(gw1, XRP(92), OF4(92)), ter(tecFROZEN)); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF4, alice)) == nullptr); + env(offer(alice, OF4(92), XRP(92)), ter(tecFROZEN)); + env.close(); + + // No one's owner count should have changed. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK4 = gw1["CK4"]; + gw1.set(CK4, tfMPTLock); + uint256 const chkId{getCheckIndex(gw1, env.seq(gw1))}; + env(check::create(gw1, alice, CK4(92)), ter(tecLOCKED)); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, alice)) == nullptr); + env(check::cash(alice, chkId, CK4(92)), ter(tecNO_ENTRY)); + env.close(); + + // No one's owner count should have changed. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Because gw1 has set tfMPTLock, neither MPT + // is created. + BEAST_EXPECT(env.le(keylet::mptoken(OF4, alice)) == nullptr); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, alice)) == nullptr); + + // clear global freeze + gw1.set(OF4, tfMPTUnlock); + gw1.set(CK4, tfMPTUnlock); + } + + //------------ lsfGlobalFreeze, check written by non-issuer ------------ + { + // lsfGlobalFreeze flag set on gw1 should not stop + // automatic MPT creation between non-issuers. + + // Use offers to automatically create MPT. + MPT const OF4 = gw1["OF4"]; + gw1.authorize(OF4, alice); + gw1.pay(gw1, alice, OF4(91)); + env(offer(alice, XRP(91), OF4(91))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF4, alice)) != nullptr); + env(offer(bob, OF4(91), XRP(91))); + ++bob.owners; + env.close(); + + // alice's owner count should increase since it created MPT. + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK4 = gw1["CK4"]; + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK4(91))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, bob)) == nullptr); + gw1.authorize(CK4, alice); + gw1.pay(gw1, alice, CK4(91)); + env(check::cash(bob, chkId, CK4(91))); + ++bob.owners; + env.close(); + + // alice's owner count should increase since it created MPT. + // bob's owner count should increase due to the new MPT. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // cleanup + gw1.cleanup(OF4, alice); + gw1.cleanup(CK4, alice); + gw1.cleanup(OF4, bob); + gw1.cleanup(CK4, bob); + } + + //------------ lsfMPTLock, check written by non-issuer ------------ + { + // Since gw1 has the lsfMPTLock flag set, there should be + // no automatic MPT creation between non-issuers. + + // Use offers to automatically create MPT. + MPT const OF4 = gw1["OF4"]; + gw1.set(OF4, tfMPTLock); + env(offer(alice, XRP(91), OF4(91)), ter(tecFROZEN)); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF4, alice)) == nullptr); + env(offer(bob, OF4(91), XRP(91)), ter(tecFROZEN)); + env.close(); + + // No one's owner count should have changed. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK4 = gw1["CK4"]; + gw1.set(CK4, tfMPTLock); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK4(91)), ter(tecLOCKED)); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, bob)) == nullptr); + env(check::cash(bob, chkId, CK4(91)), ter(tecNO_ENTRY)); + env.close(); + + // No one's owner count should have changed. + gw1.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Because gw1 has set lsfGlobalFreeze, neither trust line + // is created. + BEAST_EXPECT(env.le(keylet::mptoken(OF4, bob)) == nullptr); + BEAST_EXPECT(env.le(keylet::mptoken(CK4, bob)) == nullptr); + + gw1.set(OF4, tfMPTUnlock); + gw1.set(CK4, tfMPTUnlock); + } + + //-------------- lsfRequireAuth, check written by issuer --------------- + + // We want to test the lsfRequireAuth flag, but we can't set that + // flag on an account that already has MPT. So we'll fund + // a new gateway and use that. + AccountOwns gw2{*this, env, "gw2", true}; + { + env.fund(XRP(5'000), gw2); + env.close(); + + // Set lsfRequireAuth on gw2. That should not stop any automatic + // MPT from being created. + env(fset(gw2, asfRequireAuth)); + env.close(); + + // Use offers to automatically create MPT. + MPT const OF5 = gw2["OF5"]; + env(offer(gw2, XRP(92), OF5(92))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF5, alice)) == nullptr); + env(offer(alice, OF5(92), XRP(92))); + ++alice.owners; + env.close(); + + // alice's owner count should increase due to the new MPT. + gw2.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create MPT. + MPT const CK5 = gw2["CK5"]; + uint256 const chkId{getCheckIndex(gw2, env.seq(gw2))}; + env(check::create(gw2, alice, CK5(92))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, alice)) == nullptr); + env(check::cash(alice, chkId, CK5(92))); + verifyDeliveredAmount(env, CK5(92)); + ++alice.owners; + env.close(); + + // alice's owner count should increase due to the new MPT. + gw2.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // cleanup + gw2.cleanup(OF5, alice); + gw2.cleanup(CK5, alice); + } + + // Fund new gw to test since gw2 has MPTokenIssuance already created. + // Set RequireAuth flag. + AccountOwns gw3{*this, env, "gw3", true, true}; + { + env.fund(XRP(5'000), gw3); + env.close(); + // Use offers to automatically create the trust line. + MPT const OF5 = gw3["OF5"]; + std::uint32_t const gw3OfferSeq = {env.seq(gw3)}; + env(offer(gw3, XRP(92), OF5(92))); + ++gw3.owners; + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(OF5, alice)) == nullptr); + env(offer(alice, OF5(92), XRP(92)), ter(tecNO_AUTH)); + env.close(); + + // gw3 should still own the offer, but no one else's owner + // count should have changed. + gw3.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Since we don't need it anymore, remove gw3's offer. + env(offer_cancel(gw3, gw3OfferSeq)); + --gw3.owners; + env.close(); + gw3.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK5 = gw3["CK5"]; + uint256 const chkId{getCheckIndex(gw3, env.seq(gw3))}; + env(check::create(gw3, alice, CK5(92))); + ++gw3.owners; + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, alice)) == nullptr); + env(check::cash(alice, chkId, CK5(92)), ter(tecNO_AUTH)); + env.close(); + + // gw3 should still own the check, but no one else's owner + // count should have changed. + gw3.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Because gw3 has set lsfRequireAuth, neither trust line + // is created. + BEAST_EXPECT(env.le(keylet::mptoken(OF5, alice)) == nullptr); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, alice)) == nullptr); + + // Since we don't need it anymore, remove gw3's check. + env(check::cancel(gw3, chkId)); + --gw3.owners; + env.close(); + gw3.verifyOwners(__LINE__); + } + + //------------ lsfRequireAuth, check written by non-issuer ------------- + { + // gw2 lsfRequireAuth flag set should not affect + // automatic MPT creation between non-issuers. + + // Use offers to automatically create MPT. + MPT const OF5 = gw2["OF5"]; + gw2.authorize(OF5, alice); + gw2.pay(gw2, alice, OF5(91)); + env(offer(alice, XRP(91), OF5(91))); + env.close(); + env(offer(bob, OF5(91), XRP(91))); + ++bob.owners; + env.close(); + + // bob's owner count should increase due to the new MPT. + gw2.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK5 = gw2["CK5"]; + gw2.authorize(CK5, alice); + gw2.pay(gw2, alice, CK5(91)); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK5(91))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, bob)) == nullptr); + env(check::cash(bob, chkId, CK5(91))); + ++bob.owners; + env.close(); + + // bob's owner count should increase due to the new MPT. + gw2.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + } + + //------------ lsfMPTRequireAuth, check written by non-issuer + //------------- + { + // Since gw3 has the lsfMPTRequireAuth flag set, there should be + // no automatic MPT creation between non-issuers. + + // Use offers to automatically create the trust line. + MPT const OF5 = gw3["OF5"]; + env(offer(alice, XRP(91), OF5(91)), ter(tecUNFUNDED_OFFER)); + env.close(); + env(offer(bob, OF5(91), XRP(91)), ter(tecNO_AUTH)); + BEAST_EXPECT(env.le(keylet::mptoken(OF5, bob)) == nullptr); + env.close(); + + gw3.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Use check cashing to automatically create the trust line. + MPT const CK5 = gw3["CK5"]; + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, bob, CK5(91))); + env.close(); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, bob)) == nullptr); + env(check::cash(bob, chkId, CK5(91)), ter(tecPATH_PARTIAL)); + env.close(); + + // Delete alice's check since it is no longer needed. + env(check::cancel(alice, chkId)); + env.close(); + + // No one's owner count should have changed. + gw3.verifyOwners(__LINE__); + alice.verifyOwners(__LINE__); + bob.verifyOwners(__LINE__); + + // Because gw3 has set lsfRequireAuth, neither trust line + // is created. + BEAST_EXPECT(env.le(keylet::mptoken(OF5, bob)) == nullptr); + BEAST_EXPECT(env.le(keylet::mptoken(CK5, bob)) == nullptr); + } + } + + void + testWithFeats(FeatureBitset features) + { + testCreateValid(features); + testCreateDisallowIncoming(features); + testCreateInvalid(features); + testCashMPT(features); + testCashXferFee(features); + testCashInvalid(features); + testCancelValid(features); + testWithTickets(features); + } + +public: + void + run() override + { + using namespace test::jtx; + auto const sa = testable_amendments(); + testWithFeats(sa); + + testMPTCreation(sa); + } +}; + +BEAST_DEFINE_TESTSUITE(CheckMPT, tx, xrpl); + +} // namespace xrpl diff --git a/src/test/app/Check_test.cpp b/src/test/app/Check_test.cpp index 1e5d90f650..e062bd8e72 100644 --- a/src/test/app/Check_test.cpp +++ b/src/test/app/Check_test.cpp @@ -5,66 +5,6 @@ #include namespace xrpl { -namespace test { -namespace jtx { - -/** Set Expiration on a JTx. */ -class expiration -{ -private: - std::uint32_t const expiry_; - -public: - explicit expiration(NetClock::time_point const& expiry) - : expiry_{expiry.time_since_epoch().count()} - { - } - - void - operator()(Env&, JTx& jt) const - { - jt[sfExpiration.jsonName] = expiry_; - } -}; - -/** Set SourceTag on a JTx. */ -class source_tag -{ -private: - std::uint32_t const tag_; - -public: - explicit source_tag(std::uint32_t tag) : tag_{tag} - { - } - - void - operator()(Env&, JTx& jt) const - { - jt[sfSourceTag.jsonName] = tag_; - } -}; - -/** Set DestinationTag on a JTx. */ -class dest_tag -{ -private: - std::uint32_t const tag_; - -public: - explicit dest_tag(std::uint32_t tag) : tag_{tag} - { - } - - void - operator()(Env&, JTx& jt) const - { - jt[sfDestinationTag.jsonName] = tag_; - } -}; - -} // namespace jtx -} // namespace test class Check_test : public beast::unit_test::suite { @@ -404,11 +344,17 @@ class Check_test : public beast::unit_test::suite env(check::create(alice, bob, USF(50)), ter(tecFROZEN)); env.close(); + env(check::create(gwF, bob, USF(50)), ter(tecFROZEN)); + env.close(); + env(fclear(gwF, asfGlobalFreeze)); env.close(); env(check::create(alice, bob, USF(50))); env.close(); + + env(check::create(gwF, bob, USF(50))); + env.close(); } { // Frozen trust line. Check creation should be similar to payment @@ -1064,8 +1010,8 @@ class Check_test : public beast::unit_test::suite double pct, double amount) { // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + STAmount const aliceStart{env.balance(alice, USD).value()}; + STAmount const bobStart{env.balance(bob, USD).value()}; // Set the modified quality. env(trust(truster, iou(1000)), inOrOut(pct)); @@ -1089,8 +1035,8 @@ class Check_test : public beast::unit_test::suite double pct, double amount) { // Capture bob's and alice's balances so we can test at the end. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; - STAmount const bobStart{env.balance(bob, USD.issue()).value()}; + STAmount const aliceStart{env.balance(alice, USD).value()}; + STAmount const bobStart{env.balance(bob, USD).value()}; // Set the modified quality. env(trust(truster, iou(1000)), inOrOut(pct)); @@ -1153,7 +1099,7 @@ class Check_test : public beast::unit_test::suite double max2) { // Capture alice's balance so we can test at the end. It doesn't // make any sense to look at the balance of a gateway. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const aliceStart{env.balance(alice, USD).value()}; // Set the modified quality. env(trust(truster, iou(1000)), inOrOut(pct)); @@ -1186,7 +1132,7 @@ class Check_test : public beast::unit_test::suite double max2) { // Capture alice's balance so we can test at the end. It doesn't // make any sense to look at the balance of the issuer. - STAmount const aliceStart{env.balance(alice, USD.issue()).value()}; + STAmount const aliceStart{env.balance(alice, USD).value()}; // Set the modified quality. env(trust(truster, iou(1000)), inOrOut(pct)); @@ -1297,6 +1243,14 @@ class Check_test : public beast::unit_test::suite env(check::create(alice, bob, USD(4))); env.close(); + uint256 const chkIdFroz4ToIssuer{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, gw, USD(4))); + env.close(); + + uint256 const chkIdFroz4Issuer{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, alice, USD(4))); + env.close(); + uint256 const chkIdNoDest1{getCheckIndex(alice, env.seq(alice))}; env(check::create(alice, bob, USD(1))); env.close(); @@ -1363,7 +1317,7 @@ class Check_test : public beast::unit_test::suite { IOU const wrongCurrency{gw["EUR"]}; STAmount badAmount{amount}; - badAmount.setIssue(wrongCurrency.issue()); + badAmount.setIssue(wrongCurrency); env(check::cash(bob, chkId, badAmount), ter(temMALFORMED)); env.close(); } @@ -1372,7 +1326,7 @@ class Check_test : public beast::unit_test::suite { IOU const wrongIssuer{alice["USD"]}; STAmount badAmount{amount}; - badAmount.setIssue(wrongIssuer.issue()); + badAmount.setIssue(wrongIssuer); env(check::cash(bob, chkId, badAmount), ter(temMALFORMED)); env.close(); } @@ -1419,6 +1373,17 @@ class Check_test : public beast::unit_test::suite env(check::cash(bob, chkIdFroz1, check::DeliverMin(USD(0.5))), ter(tecPATH_PARTIAL)); env.close(); + env(check::cash(gw, chkIdFroz4ToIssuer, USD(1)), ter(tecPATH_PARTIAL)); + env.close(); + env(check::cash(gw, chkIdFroz4ToIssuer, check::DeliverMin(USD(0.5))), + ter(tecPATH_PARTIAL)); + env.close(); + + env(check::cash(alice, chkIdFroz4Issuer, USD(1)), ter(tecFROZEN)); + env.close(); + env(check::cash(alice, chkIdFroz4Issuer, check::DeliverMin(USD(0.5))), ter(tecFROZEN)); + env.close(); + env(fclear(gw, asfGlobalFreeze)); env.close(); @@ -1428,6 +1393,9 @@ class Check_test : public beast::unit_test::suite env.require(balance(alice, USD(19))); env.require(balance(bob, USD(1))); + env(check::cash(gw, chkIdFroz4ToIssuer, USD(1))); + env.close(); + // Freeze individual trustlines. env(trust(gw, alice["USD"](0), tfSetFreeze)); env.close(); @@ -1441,7 +1409,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz2, USD(2))); env.close(); - env.require(balance(alice, USD(17))); + env.require(balance(alice, USD(16))); env.require(balance(bob, USD(3))); // Freeze bob's trustline. bob can't cash the check. @@ -1457,7 +1425,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz3, check::DeliverMin(USD(1)))); verifyDeliveredAmount(env, USD(3)); - env.require(balance(alice, USD(14))); + env.require(balance(alice, USD(13))); env.require(balance(bob, USD(6))); // Set bob's freeze bit in the other direction. Check @@ -1474,7 +1442,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdFroz4, USD(4))); env.close(); - env.require(balance(alice, USD(10))); + env.require(balance(alice, USD(9))); env.require(balance(bob, USD(10))); } { @@ -1491,7 +1459,7 @@ class Check_test : public beast::unit_test::suite // bob can cash a check with a destination tag. env(check::cash(bob, chkIdHasDest2, USD(2))); env.close(); - env.require(balance(alice, USD(8))); + env.require(balance(alice, USD(7))); env.require(balance(bob, USD(12))); // Clear the RequireDest flag on bob's account so he can @@ -1500,7 +1468,7 @@ class Check_test : public beast::unit_test::suite env.close(); env(check::cash(bob, chkIdNoDest1, USD(1))); env.close(); - env.require(balance(alice, USD(7))); + env.require(balance(alice, USD(6))); env.require(balance(bob, USD(13))); } } @@ -1960,7 +1928,7 @@ class Check_test : public beast::unit_test::suite if (!BEAST_EXPECT(!offerAmount.native() && !checkAmount.native())) return; - BEAST_EXPECT(offerAmount.issue().account == checkAmount.issue().account); + BEAST_EXPECT(offerAmount.getIssuer() == checkAmount.getIssuer()); BEAST_EXPECT(offerAmount.negative() == checkAmount.negative()); BEAST_EXPECT(offerAmount.mantissa() == checkAmount.mantissa()); BEAST_EXPECT(offerAmount.exponent() == checkAmount.exponent()); diff --git a/src/test/app/CrossingLimitsMPT_test.cpp b/src/test/app/CrossingLimitsMPT_test.cpp new file mode 100644 index 0000000000..6e977a6e68 --- /dev/null +++ b/src/test/app/CrossingLimitsMPT_test.cpp @@ -0,0 +1,431 @@ +#include + +#include +#include + +namespace xrpl { +namespace test { + +class CrossingLimitsMPT_test : public beast::unit_test::suite +{ +public: + void + testStepLimit(FeatureBitset features) + { + testcase("Step Limit"); + + using namespace jtx; + Env env(*this, features); + + auto const gw = Account("gateway"); + + env.fund(XRP(100'000'000), gw, "alice", "bob", "carol", "dan"); + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {"bob", "dan"}, .maxAmt = 2}); + env(pay(gw, "bob", USD(1))); + env(pay(gw, "dan", USD(1))); + n_offers(env, 2'000, "bob", XRP(1), USD(1)); + n_offers(env, 1, "dan", XRP(1), USD(1)); + + // Alice offers to buy 1000 XRP for 1000 USD. She takes Bob's first + // offer, removes 999 more as unfunded, then hits the step limit. + env(offer("alice", USD(1'000), XRP(1'000))); + env.require(balance("alice", USD(1))); + env.require(owners("alice", 2)); + env.require(balance("bob", USD(0))); + env.require(owners("bob", 1'001)); + env.require(balance("dan", USD(1))); + env.require(owners("dan", 2)); + + // Carol offers to buy 1000 XRP for 1000 USD. She removes Bob's next + // 1000 offers as unfunded and hits the step limit. + env(offer("carol", USD(1'000), XRP(1'000))); + env.require(balance("carol", USD(none))); + env.require(owners("carol", 1)); + env.require(balance("bob", USD(0))); + env.require(owners("bob", 1)); + env.require(balance("dan", USD(1))); + env.require(owners("dan", 2)); + } + + void + testCrossingLimit(FeatureBitset features) + { + testcase("Crossing Limit"); + + using namespace jtx; + Env env(*this, features); + + auto const gw = Account("gateway"); + + int const maxConsumed = 1'000; + + env.fund(XRP(100'000'000), gw, "alice", "bob", "carol"); + int const bobsOfferCount = maxConsumed + 150; + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {"bob"}, .maxAmt = bobsOfferCount}); + env(pay(gw, "bob", USD(bobsOfferCount))); + env.close(); + n_offers(env, bobsOfferCount, "bob", XRP(1), USD(1)); + + // Alice offers to buy Bob's offers. However, she hits the offer + // crossing limit, so she can't buy them all at once. + env(offer("alice", USD(bobsOfferCount), XRP(bobsOfferCount))); + env.close(); + env.require(balance("alice", USD(maxConsumed))); + env.require(balance("bob", USD(150))); + env.require(owners("bob", 150 + 1)); + + // Carol offers to buy 1000 XRP for 1000 USD. She takes Bob's + // remaining 150 offers without hitting a limit. + env(offer("carol", USD(1'000), XRP(1'000))); + env.close(); + env.require(balance("carol", USD(150))); + env.require(balance("bob", USD(0))); + env.require(owners("bob", 1)); + } + + void + testStepAndCrossingLimit(FeatureBitset features) + { + testcase("Step And Crossing Limit"); + + using namespace jtx; + Env env(*this, features); + + auto const gw = Account("gateway"); + + env.fund(XRP(100'000'000), gw, "alice", "bob", "carol", "dan", "evita"); + + int const maxConsumed = 1'000; + int const evitaOfferCount{maxConsumed + 49}; + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {"bob", "alice", "carol", "evita"}, + .maxAmt = 2'000 + evitaOfferCount + 1}); + + env(pay(gw, "alice", USD(1000))); + env(pay(gw, "carol", USD(1))); + env(pay(gw, "evita", USD(evitaOfferCount + 1))); + + // Give carol an extra 150 (unfunded) offers when we're using Taker + // to accommodate that difference. + int const carolOfferCount{700}; + n_offers(env, 400, "alice", XRP(1), USD(1)); + n_offers(env, carolOfferCount, "carol", XRP(1), USD(1)); + n_offers(env, evitaOfferCount, "evita", XRP(1), USD(1)); + + // Bob offers to buy 1000 XRP for 1000 USD. He takes all 400 USD from + // Alice's offers, 1 USD from Carol's and then removes 599 of Carol's + // offers as unfunded, before hitting the step limit. + env(offer("bob", USD(1000), XRP(1000))); + env.require(balance("bob", USD(401))); + env.require(balance("alice", USD(600))); + env.require(owners("alice", 1)); + env.require(balance("carol", USD(0))); + env.require(owners("carol", carolOfferCount - 599)); + env.require(balance("evita", USD(evitaOfferCount + 1))); + env.require(owners("evita", evitaOfferCount + 1)); + + // Dan offers to buy maxConsumed + 50 XRP USD. He removes all of + // Carol's remaining offers as unfunded, then takes + // (maxConsumed - 100) USD from Evita's, hitting the crossing limit. + env(offer("dan", USD(maxConsumed + 50), XRP(maxConsumed + 50))); + env.require(balance("dan", USD(maxConsumed - 100))); + env.require(owners("dan", 2)); + env.require(balance("alice", USD(600))); + env.require(owners("alice", 1)); + env.require(balance("carol", USD(0))); + env.require(owners("carol", 1)); + env.require(balance("evita", USD(150))); + env.require(owners("evita", 150)); + } + + void + testAutoBridgedLimits(FeatureBitset features) + { + testcase("Auto Bridged Limits"); + + // Extracts as much as possible in one book at one Quality + // before proceeding to the other book. This reduces the number of + // times we change books. + + // If any book step in a payment strand consumes 1000 offers, the + // liquidity from the offers is used, but that strand will be marked as + // dry for the remainder of the transaction. + + using namespace jtx; + + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + + // There are two almost identical tests. There is a strand with a large + // number of unfunded offers that will cause the strand to be marked dry + // even though there will still be liquidity available on that strand. + // In the first test, the strand has the best initial quality. In the + // second test the strand does not have the best quality (the + // implementation has to handle this case correct and not mark the + // strand dry until the liquidity is actually used) + + // The implementation allows any single step to consume at most 1000 + // offers. With the `FlowSortStrands` feature enabled, if the total + // number of offers consumed by all the steps combined exceeds 1500, the + // payment stops. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(100'000'000), gw, alice, bob, carol); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = maxMPTokenAmount}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {bob}, + .limit = maxMPTokenAmount}); + + env(pay(gw, alice, USD(4'000))); + env(pay(gw, carol, USD(3))); + + // Notice the strand with the 800 unfunded offers has the + // initial best quality + n_offers(env, 2'000, alice, EUR(2), XRP(1)); + n_offers(env, 100, alice, XRP(1), USD(4)); + n_offers(env, 801, carol, XRP(1), + USD(3)); // only one offer is funded + n_offers(env, 1'000, alice, XRP(1), USD(3)); + + n_offers(env, 1, alice, EUR(500), USD(500)); + + // Bob offers to buy 2000 USD for 2000 EUR; He starts with 2000 + // EUR + // 1. The best quality is the autobridged offers that take 2 + // EUR and give 4 USD. + // Bob spends 200 EUR and receives 400 USD. + // 100 EUR->XRP offers consumed. + // 100 XRP->USD offers consumed. + // 200 total offers consumed. + // + // 2. The best quality is the autobridged offers that take 2 + // EUR and give 3 USD. + // a. One of Carol's offers is taken. This leaves her other + // offers unfunded. + // b. Carol's remaining 800 offers are consumed as unfunded. + // c. 199 of alice's XRP(1) to USD(3) offers are consumed. + // A book step is allowed to consume a maximum of 1000 + // offers at a given quality, and that limit is now + // reached. + // d. Now the strand is dry, even though there are still + // funded XRP(1) to USD(3) offers available. + // Bob has spent 400 EUR and received 600 USD in this + // step. 200 EUR->XRP offers consumed 800 unfunded + // XRP->USD offers consumed 200 funded XRP->USD offers + // consumed (1 carol, 199 alice) 1400 total offers + // consumed so far (100 left before the limit) + // 3. The best is the non-autobridged offers that takes 500 EUR + // and gives 500 USD. + // Bob started with 2000 EUR + // Bob spent 500 EUR (100+400) + // Bob has 1500 EUR left + // In this step: + // Bob spends 500 EUR and receives 500 USD. + // In total: + // Bob spent 1100 EUR (200 + 400 + 500) + // Bob has 900 EUR remaining (2000 - 1100) + // Bob received 1500 USD (400 + 600 + 500) + // Alice spent 1497 USD (100*4 + 199*3 + 500) + // Alice has 2503 remaining (4000 - 1497) + // Alice received 1100 EUR (200 + 400 + 500) + env(pay(gw, bob, EUR(2'000))); + env.close(); + env(offer(bob, USD(4'000), EUR(4'000))); + env.close(); + + env.require(balance(bob, USD(1'500))); + env.require(balance(bob, EUR(900))); + env.require(offers(bob, 1)); + env.require(owners(bob, 3)); + + env.require(balance(alice, USD(2'503))); + env.require(balance(alice, EUR(1'100))); + auto const numAOffers = 2'000 + 100 + 1'000 + 1 - (2 * 100 + 2 * 199 + 1 + 1); + env.require(offers(alice, numAOffers)); + env.require(owners(alice, numAOffers + 2)); + + env.require(offers(carol, 0)); + }; + testHelper2TokensMix(test); + } + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(100'000'000), gw, alice, bob, carol); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = maxMPTokenAmount}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {bob}, + .limit = maxMPTokenAmount}); + + env(pay(gw, alice, USD(4'000))); + env(pay(gw, carol, USD(3))); + + // Notice the strand with the 800 unfunded offers does not have + // the initial best quality + n_offers(env, 1, alice, EUR(1), USD(10)); + n_offers(env, 2'000, alice, EUR(2), XRP(1)); + n_offers(env, 100, alice, XRP(1), USD(4)); + n_offers(env, 801, carol, XRP(1), + USD(3)); // only one offer is funded + n_offers(env, 1'000, alice, XRP(1), USD(3)); + + n_offers(env, 1, alice, EUR(499), USD(499)); + + // Bob offers to buy 2000 USD for 2000 EUR; He starts with 2000 + // EUR + // 1. The best quality is the offer that takes 1 EUR and gives + // 10 USD + // Bob spends 1 EUR and receives 10 USD. + // + // 2. The best quality is the autobridged offers that takes 2 + // EUR and gives 4 USD. + // Bob spends 200 EUR and receives 400 USD. + // + // 3. The best quality is the autobridged offers that takes 2 + // EUR and gives 3 USD. + // a. One of Carol's offers is taken. This leaves her other + // offers unfunded. + // b. Carol's remaining 800 offers are consumed as unfunded. + // c. 199 of alice's XRP(1) to USD(3) offers are consumed. + // A book step is allowed to consume a maximum of 1000 + // offers at a given quality, and that limit is now + // reached. + // d. Now the strand is dry, even though there are still + // funded XRP(1) to USD(3) offers available. Bob has spent + // 400 EUR and received 600 USD in this step. (200 funded + // offers consumed 800 unfunded offers) + // 4. The best is the non-autobridged offers that takes 499 EUR + // and gives 499 USD. + // Bob has 2000 EUR, and has spent 1+200+400=601 EUR. He has + // 1399 left. Bob spent 499 EUR and receives 499 USD. + // In total: Bob spent EUR(1 + 200 + 400 + 499) = EUR(1100). He + // started with 2000 so has 900 remaining + // Bob received USD(10 + 400 + 600 + 499) = USD(1509). + // Alice spent 10 + 100*4 + 199*3 + 499 = 1506 USD. + // She started with 4000 so has 2494 USD remaining. + // Alice received 200 + 400 + 500 = 1100 EUR + env.close(); + env(pay(gw, bob, EUR(2'000))); + env.close(); + env(offer(bob, USD(4'000), EUR(4'000))); + env.close(); + + env.require(balance(bob, USD(1'509))); + env.require(balance(bob, EUR(900))); + env.require(offers(bob, 1)); + env.require(owners(bob, 3)); + + env.require(balance(alice, USD(2'494))); + env.require(balance(alice, EUR(1'100))); + auto const numAOffers = + 1 + 2'000 + 100 + 1'000 + 1 - (1 + 2 * 100 + 2 * 199 + 1 + 1); + env.require(offers(alice, numAOffers)); + env.require(owners(alice, numAOffers + 2)); + + env.require(offers(carol, 0)); + }; + testHelper2TokensMix(test); + } + } + + void + testOfferOverflow(FeatureBitset features) + { + testcase("Offer Overflow"); + + using namespace jtx; + + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + Env env(*this, features); + + env.fund(XRP(100'000'000), gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, alice, USD(8'000))); + env.close(); + + // The new flow cross handles consuming excessive offers differently + // than the old offer crossing code. In the old code, the total number + // of consumed offers is tracked, and the crossings will stop after this + // limit is hit. In the new code, the number of offers is tracked per + // offerbook and per quality. This test shows how they can differ. Set + // up a book with many offers. At each quality keep the number of offers + // below the limit. However, if all the offers are consumed it would + // create a tecOVERSIZE error. + + // The featureFlowSortStrands introduces a way of tracking the total + // number of consumed offers; with this feature the transaction no + // longer fails with a tecOVERSIZE error. + // The implementation allows any single step to consume at most 1000 + // offers. With the `FlowSortStrands` feature enabled, if the total + // number of offers consumed by all the steps combined exceeds 1500, the + // payment stops. Since the first set of offers consumes 998 offers, the + // second set will consume 998, which is not over the limit and the + // payment stops. So 2*998, or 1996 is the expected value when + // `FlowSortStrands` is enabled. + n_offers(env, 998, alice, XRP(1.00), USD(1)); + n_offers(env, 998, alice, XRP(0.99), USD(1)); + n_offers(env, 998, alice, XRP(0.98), USD(1)); + n_offers(env, 998, alice, XRP(0.97), USD(1)); + n_offers(env, 998, alice, XRP(0.96), USD(1)); + n_offers(env, 998, alice, XRP(0.95), USD(1)); + + auto const expectedTER = tesSUCCESS; + + env(offer(bob, USD(8'000), XRP(8'000)), ter(expectedTER)); + env.close(); + + auto const expectedUSD = USD(1'996); + + env.require(balance(bob, expectedUSD)); + } + + void + run() override + { + using namespace jtx; + auto const features = testable_amendments(); + testStepLimit(features); + testCrossingLimit(features); + testStepAndCrossingLimit(features); + testAutoBridgedLimits(features); + testOfferOverflow(features); + } +}; + +BEAST_DEFINE_TESTSUITE_MANUAL_PRIO(CrossingLimitsMPT, tx, xrpl, 10); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/CrossingLimits_test.cpp b/src/test/app/CrossingLimits_test.cpp index 0451822492..a0e0a95437 100644 --- a/src/test/app/CrossingLimits_test.cpp +++ b/src/test/app/CrossingLimits_test.cpp @@ -143,107 +143,15 @@ public: env.require(owners("evita", 150)); } - void - testAutoBridgedLimitsTaker(FeatureBitset features) - { - testcase("Auto Bridged Limits Taker"); - - using namespace jtx; - Env env(*this, features); - - auto const gw = Account("gateway"); - auto const USD = gw["USD"]; - auto const EUR = gw["EUR"]; - - env.fund(XRP(100000000), gw, "alice", "bob", "carol", "dan", "evita"); - - env.trust(USD(2000), "alice"); - env(pay(gw, "alice", USD(2000))); - env.trust(USD(1000), "carol"); - env(pay(gw, "carol", USD(3))); - env.trust(USD(1000), "evita"); - env(pay(gw, "evita", USD(1000))); - - n_offers(env, 302, "alice", EUR(2), XRP(1)); - n_offers(env, 300, "alice", XRP(1), USD(4)); - n_offers(env, 497, "carol", XRP(1), USD(3)); - n_offers(env, 1001, "evita", EUR(1), USD(1)); - - // Bob offers to buy 2000 USD for 2000 EUR, even though he only has - // 1000 EUR. - // 1. He spends 600 EUR taking Alice's auto-bridged offers and - // gets 1200 USD for that. - // 2. He spends another 2 EUR taking one of Alice's EUR->XRP and - // one of Carol's XRP-USD offers. He gets 3 USD for that. - // 3. The remainder of Carol's offers are now unfunded. We've - // consumed 602 offers so far. We now chew through 398 more - // of Carol's unfunded offers until we hit the 1000 offer limit. - // This sets have_bridge to false -- we will handle no more - // bridged offers. - // 4. However, have_direct is still true. So we go around one more - // time and take one of Evita's offers. - // 5. After taking one of Evita's offers we notice (again) that our - // offer count was exceeded. So we completely stop after taking - // one of Evita's offers. - env.trust(EUR(10000), "bob"); - env.close(); - env(pay(gw, "bob", EUR(1000))); - env.close(); - env(offer("bob", USD(2000), EUR(2000))); - env.require(balance("bob", USD(1204))); - env.require(balance("bob", EUR(397))); - - env.require(balance("alice", USD(800))); - env.require(balance("alice", EUR(602))); - env.require(offers("alice", 1)); - env.require(owners("alice", 3)); - - env.require(balance("carol", USD(0))); - env.require(balance("carol", EUR(none))); - env.require(offers("carol", 100)); - env.require(owners("carol", 101)); - - env.require(balance("evita", USD(999))); - env.require(balance("evita", EUR(1))); - env.require(offers("evita", 1000)); - env.require(owners("evita", 1002)); - - // Dan offers to buy 900 EUR for 900 USD. - // 1. He removes all 100 of Carol's remaining unfunded offers. - // 2. Then takes 850 USD from Evita's offers. - // 3. Consuming 850 of Evita's funded offers hits the crossing - // limit. So Dan's offer crossing stops even though he would - // be willing to take another 50 of Evita's offers. - env.trust(EUR(10000), "dan"); - env.close(); - env(pay(gw, "dan", EUR(1000))); - env.close(); - - env(offer("dan", USD(900), EUR(900))); - env.require(balance("dan", USD(850))); - env.require(balance("dan", EUR(150))); - - env.require(balance("alice", USD(800))); - env.require(balance("alice", EUR(602))); - env.require(offers("alice", 1)); - env.require(owners("alice", 3)); - - env.require(balance("carol", USD(0))); - env.require(balance("carol", EUR(none))); - env.require(offers("carol", 0)); - env.require(owners("carol", 1)); - - env.require(balance("evita", USD(149))); - env.require(balance("evita", EUR(851))); - env.require(offers("evita", 150)); - env.require(owners("evita", 152)); - } - void testAutoBridgedLimits(FeatureBitset features) { testcase("Auto Bridged Limits"); + // Extracts as much as possible in one book at one Quality + // before proceeding to the other book. This reduces the number of + // times we change books. + // If any book step in a payment strand consumes 1000 offers, the // liquidity from the offers is used, but that strand will be marked as // dry for the remainder of the transaction. diff --git a/src/test/app/Delegate_test.cpp b/src/test/app/Delegate_test.cpp index 6c5698a227..d6e970190e 100644 --- a/src/test/app/Delegate_test.cpp +++ b/src/test/app/Delegate_test.cpp @@ -1619,8 +1619,8 @@ class Delegate_test : public beast::unit_test::suite Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; - Account daria{"daria"}; - Account edward{"edward"}; + Account const daria{"daria"}; + Account const edward{"edward"}; env.fund(XRP(100000), alice, bob, carol, daria, edward); env.close(); @@ -1655,9 +1655,9 @@ class Delegate_test : public beast::unit_test::suite Account const alice{"alice"}; Account const bob{"bob"}; Account const carol{"carol"}; - Account daria = Account{"daria"}; - Account edward = Account{"edward"}; - Account fred = Account{"fred"}; + Account const daria{"daria"}; + Account const edward{"edward"}; + Account const fred{"fred"}; env.fund(XRP(100000), alice, bob, carol, daria, edward, fred); env.close(); diff --git a/src/test/app/FlowMPT_test.cpp b/src/test/app/FlowMPT_test.cpp new file mode 100644 index 0000000000..004bb6eee4 --- /dev/null +++ b/src/test/app/FlowMPT_test.cpp @@ -0,0 +1,2111 @@ +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +struct FlowMPT_test : public beast::unit_test::suite +{ + using Accounts = std::vector; + + void + testDirectStep(FeatureBitset features) + { + testcase("Direct Step"); + + using namespace jtx; + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + auto const gw = Account("gw"); + { + // Pay USD, trivial path + Env env(*this, features); + + env.fund(XRP(10000), alice, bob, gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + env(pay(gw, alice, USD(100))); + env(pay(alice, bob, USD(10)), paths(USD)); + env.require(balance(bob, USD(10))); + } + { + // Partial payments + Env env(*this, features); + + env.fund(XRP(10000), alice, bob, gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + env(pay(gw, alice, USD(100))); + env(pay(alice, bob, USD(110)), paths(USD), ter(tecPATH_PARTIAL)); + env.require(balance(bob, USD(0))); + env(pay(alice, bob, USD(110)), paths(USD), txflags(tfPartialPayment)); + env.require(balance(bob, USD(100))); + } + + { + // Limit quality + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), gw, alice, bob, carol); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}}); + + env(pay(gw, alice, USD(100))); + env(pay(gw, bob, EUR(100))); + + env(offer(alice, EUR(4), USD(4))); + env.close(); + + env(pay(bob, carol, USD(5)), + sendmax(EUR(4)), + txflags(tfLimitQuality | tfPartialPayment), + ter(tecPATH_DRY)); + env.require(balance(carol, USD(0))); + + env(pay(bob, carol, USD(5)), sendmax(EUR(4)), txflags(tfPartialPayment)); + env.require(balance(carol, USD(4))); + }; + testHelper2TokensMix(test); + } + } + + void + testBookStep(FeatureBitset features) + { + testcase("Book Step"); + + using namespace jtx; + + auto const gw = Account("gateway"); + Account const alice("alice"); + Account const bob("bob"); + Account const carol("carol"); + + { + // simple [MPT|IOU]/[IOU|MPT] offer + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}}); + auto const BTC = issue2( + {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, BTC(50))); + env(pay(gw, bob, USD(50))); + + env(offer(bob, BTC(50), USD(50))); + + env(pay(alice, carol, USD(50)), path(~USD), sendmax(BTC(50))); + + env.require(balance(alice, BTC(0))); + env.require(balance(bob, BTC(50))); + env.require(balance(bob, USD(0))); + env.require(balance(carol, USD(50))); + BEAST_EXPECT(!isOffer(env, bob, BTC(50), USD(50))); + }; + testHelper2TokensMix(test); + } + { + // simple [MPT|IOU]/XRP XRP/[IOU|MPT] offer + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}}); + auto const BTC = issue2( + {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, BTC(50))); + env(pay(gw, bob, USD(50))); + + env(offer(bob, BTC(50), XRP(50))); + env(offer(bob, XRP(50), USD(50))); + + env(pay(alice, carol, USD(50)), path(~XRP, ~USD), sendmax(BTC(50))); + + env.require(balance(alice, BTC(0))); + env.require(balance(bob, BTC(50))); + env.require(balance(bob, USD(0))); + env.require(balance(carol, USD(50))); + BEAST_EXPECT(!isOffer(env, bob, XRP(50), USD(50))); + BEAST_EXPECT(!isOffer(env, bob, BTC(50), XRP(50))); + }; + testHelper2TokensMix(test); + } + { + // simple XRP -> USD through offer and sendmax + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + MPT const BTC = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, bob, USD(50))); + + env(offer(bob, XRP(50), USD(50))); + + env(pay(alice, carol, USD(50)), path(~USD), sendmax(XRP(50))); + + // fee: MPTokenAuthorize * 2(EUR, USD) + pay + env.require(balance(alice, XRP(10'000 - 50) - txfee(env, 3))); + // fee: MPTokenAuthorize * 2(EUR, USD) + offer + env.require(balance(bob, XRP(10'000 + 50) - txfee(env, 3))); + env.require(balance(bob, USD(0))); + env.require(balance(carol, USD(50))); + BEAST_EXPECT(!isOffer(env, bob, XRP(50), USD(50))); + } + { + // simple USD -> XRP through offer and sendmax + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + MPT const BTC = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, USD(50))); + + env(offer(bob, USD(50), XRP(50))); + + env(pay(alice, carol, XRP(50)), path(~XRP), sendmax(USD(50))); + + env.require(balance(alice, USD(0))); + env.require(balance(bob, XRP(10'000 - 50) - txfee(env, 3))); + env.require(balance(bob, USD(50))); + env.require(balance(carol, XRP(10'000 + 50) - txfee(env, 2))); + BEAST_EXPECT(!isOffer(env, bob, USD(50), XRP(50))); + } + { + // test unfunded offers are removed when payment succeeds + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}}); + auto const BTC = issue2( + {.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}}); + auto const EUR = issue3( + {.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, BTC(60))); + env(pay(gw, bob, USD(50))); + env(pay(gw, bob, EUR(50))); + + env(offer(bob, BTC(50), USD(50))); + env(offer(bob, BTC(40), EUR(50))); + env(offer(bob, EUR(50), USD(50))); + + // unfund offer + env(pay(bob, gw, EUR(50))); + env.require(balance(bob, EUR(0))); + BEAST_EXPECT(isOffer(env, bob, BTC(50), USD(50))); + BEAST_EXPECT(isOffer(env, bob, BTC(40), EUR(50))); + BEAST_EXPECT(isOffer(env, bob, EUR(50), USD(50))); + + env(pay(alice, carol, USD(50)), path(~USD), path(~EUR, ~USD), sendmax(BTC(60))); + + env.require(balance(alice, BTC(10))); + env.require(balance(bob, BTC(50))); + env.require(balance(bob, USD(0))); + env.require(balance(bob, EUR(0))); + env.require(balance(carol, USD(50))); + // used in the payment + BEAST_EXPECT(!isOffer(env, bob, BTC(50), USD(50))); + // found unfunded + BEAST_EXPECT(!isOffer(env, bob, BTC(40), EUR(50))); + // unfunded, but should not yet be found unfunded + BEAST_EXPECT(isOffer(env, bob, EUR(50), USD(50))); + }; + testHelper3TokensMix(test); + } + { + // test unfunded offers are returned when the payment fails. + // bob makes two offers: a funded 5000 USD for 50 BTC and an + // unfunded 5000 EUR for 60 BTC. alice pays carol 6100 USD with 61 + // BTC. alice only has 60 BTC, so the payment will fail. The payment + // uses two paths: one through bob's funded offer and one through + // his unfunded offer. When the payment fails `flow` should return + // the unfunded offer. This test is intentionally similar to the one + // that removes unfunded offers when the payment succeeds. + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000}); + auto const EUR = issue3( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000}); + + env(pay(gw, alice, BTC(60))); + env(pay(gw, bob, USD(6'000))); + env(pay(gw, bob, EUR(5'000))); + env(pay(gw, carol, EUR(100))); + + env(offer(bob, BTC(50), USD(5'000))); + env(offer(bob, BTC(60), EUR(5'000))); + env(offer(carol, BTC(1'000), EUR(100))); + env(offer(bob, EUR(5'000), USD(5'000))); + + // unfund offer + env(pay(bob, gw, EUR(5'000))); + BEAST_EXPECT(isOffer(env, bob, BTC(50), USD(5'000))); + BEAST_EXPECT(isOffer(env, bob, BTC(60), EUR(5'000))); + BEAST_EXPECT(isOffer(env, carol, BTC(1'000), EUR(100))); + + auto flowJournal = env.app().getLogs().journal("Flow"); + auto const flowResult = [&] { + STAmount const deliver(USD(5'100)); + STAmount smax(BTC(61)); + PaymentSandbox sb(env.current().get(), tapNONE); + STPathSet paths; + auto IPE = [](Asset const& asset) { + return STPathElement( + STPathElement::typeAsset | STPathElement::typeIssuer, + xrpAccount(), + asset, + asset.getIssuer()); + }; + { + // BTC -> USD + STPath const p1({IPE(USD)}); + paths.push_back(p1); + // BTC -> EUR -> USD + STPath const p2({IPE(EUR), IPE(USD)}); + paths.push_back(p2); + } + + return flow( + sb, + deliver, + alice, + carol, + paths, + false, + false, + true, + OfferCrossing::no, + std::nullopt, + smax, + std::nullopt, + flowJournal); + }(); + + BEAST_EXPECT(flowResult.removableOffers.size() == 1); + env.app().getOpenLedger().modify([&](OpenView& view, beast::Journal j) { + if (flowResult.removableOffers.empty()) + return false; + Sandbox sb(&view, tapNONE); + for (auto const& o : flowResult.removableOffers) + { + if (auto ok = sb.peek(keylet::offer(o))) + offerDelete(sb, ok, flowJournal); + } + sb.apply(view); + return true; + }); + + // used in payment, but since payment failed should + // be untouched + BEAST_EXPECT(isOffer(env, bob, BTC(50), USD(5'000))); + BEAST_EXPECT(isOffer(env, carol, BTC(1'000), EUR(100))); + // found unfunded + BEAST_EXPECT(!isOffer(env, bob, BTC(60), EUR(5'000))); + }; + testHelper3TokensMix(test); + } + { + // Do not produce more in the forward pass than the + // reverse pass. This test uses a path whose reverse + // pass will compute a 0.5 USD input required for a 1 + // EUR output. It sets a sendmax of 0.4 USD, so the + // payment engine will need to do a forward pass. + // Without limits, the 0.4 USD would produce 1000 EUR in + // the forward pass. This test checks that the payment + // produces 1 EUR, as expected. + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, carol, gw); + + auto const USD = issue1( + {.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}}); + auto const EUR = issue1( + {.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, USD(1'000))); + env(pay(gw, bob, EUR(1'000))); + + Keylet const bobUsdOffer = keylet::offer(bob, env.seq(bob)); + env(offer(bob, USD(10), drops(2)), txflags(tfPassive)); + env(offer(bob, drops(1), EUR(1'000)), txflags(tfPassive)); + + bool const reducedOffersV2 = features[fixReducedOffersV2]; + + // With reducedOffersV2, it is not allowed to accept + // less than USD(0.5) of bob's USD offer. If we + // provide 1 drop for less than USD(0.5), then the + // remaining fractional offer would block the order + // book. + TER const expectedTER = reducedOffersV2 ? TER(tecPATH_DRY) : TER(tesSUCCESS); + env(pay(alice, carol, EUR(1)), + path(~XRP, ~EUR), + sendmax(USD(4)), + txflags(tfNoRippleDirect | tfPartialPayment), + ter(expectedTER)); + + if (!reducedOffersV2) + { + env.require(balance(carol, EUR(1))); + env.require(balance(bob, USD(4))); + env.require(balance(bob, EUR(999))); + + // Show that bob's USD offer is now a blocker. + std::shared_ptr const usdOffer = env.le(bobUsdOffer); + if (BEAST_EXPECT(usdOffer)) + { + std::uint64_t const bookRate = [&usdOffer]() { + // Extract the least significant 64 + // bits from the book page. That's + // where the quality is stored. + std::string bookDirStr = to_string(usdOffer->at(sfBookDirectory)); + bookDirStr.erase(0, 48); + return std::stoull(bookDirStr, nullptr, 16); + }(); + std::uint64_t const actualRate = + getRate(usdOffer->at(sfTakerGets), usdOffer->at(sfTakerPays)); + + // We expect the actual rate of the offer to + // be worse (larger) than the rate of the + // book page holding the offer. This is a + // defect which is corrected by + // fixReducedOffersV2. + BEAST_EXPECT(actualRate > bookRate); + } + } + }; + testHelper2TokensMix(test); + } + } + + void + testTransferRate(FeatureBitset features) + { + testcase("Transfer Rate"); + + using namespace jtx; + + auto const gw = Account("gateway"); + Account const alice("alice"); + Account const bob("bob"); + Account const carol("carol"); + + { + // Simple payment through a gateway with a + // transfer rate + Env env(*this, features); + + env.fund(XRP(10000), alice, bob, carol, gw); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .maxAmt = 1'000}); + + env(pay(gw, alice, USD(50))); + env.require(balance(alice, USD(50))); + env(pay(alice, bob, USD(40)), sendmax(USD(50))); + env.require(balance(bob, USD(40)), balance(alice, USD(0))); + } + { + // transfer rate is not charged when issuer is src or + // dst + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .maxAmt = 1'000}); + + env(pay(gw, alice, USD(50))); + env.require(balance(alice, USD(50))); + env(pay(alice, gw, USD(40)), sendmax(USD(40))); + env.require(balance(alice, USD(10))); + } + { + // transfer fee on an offer + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol}, + .transferFee = 25'000, + .maxAmt = 10'000}); + + // scale by 1 + env(pay(gw, bob, USD(650))); + + env(offer(bob, XRP(50), USD(500))); + + env(pay(alice, carol, USD(500)), + path(~USD), + sendmax(XRP(50)), + txflags(tfPartialPayment)); + + // bob pays 25% on 500USD -> 100USD; 400USD goes to carol + env.require( + balance(alice, XRP(10'000 - 50) - txfee(env, 2)), + balance(bob, USD(150)), + balance(carol, USD(400))); + } + { + // Transfer fee two consecutive offers + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000, + .transferFee = 25'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 1'000, + .transferFee = 25'000}); + + env(pay(gw, bob, USD(50))); + env(pay(gw, bob, EUR(50))); + + env(offer(bob, XRP(50), USD(50))); + env(offer(bob, USD(50), EUR(50))); + + env(pay(alice, carol, EUR(40)), + path(~USD, ~EUR), + sendmax(XRP(40)), + txflags(tfPartialPayment)); + // +1 for fset in helperIssueIOU + using tEUR = std::decay_t; + auto const fee = txfee(env, 3); + // bob pays 25% on 40USD (40 since sendmax is 40XRP) + // 8USD goes to gw and 32USD goes back to bob -> + // bob's USD balance is 42USD. USD/EUR offer is 32USD/32EUR. + // bob pays 25% on 32EUR -> 7EUR if MPT, 6.4EUR if IOU, + // therefore carl gets 25EUR if MPT, 25.6EUR if IOU. + auto const carolEUR = [&]() { + if constexpr (std::is_same_v) + { + return EUR(25.6); + } + else + { + return EUR(25); + } + }(); + env.require( + balance(alice, XRP(10'000 - 40) - fee), + balance(bob, USD(42)), + balance(bob, EUR(18)), + balance(carol, carolEUR)); + }; + testHelper2TokensMix(test); + } + { + // Offer where the owner is also the issuer, sender pays + // fee + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, gw); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 25'000, + .maxAmt = 1'000}); + + env(offer(gw, XRP(100), USD(100))); + env(pay(alice, bob, USD(100)), sendmax(XRP(100)), txflags(tfPartialPayment)); + env.require(balance(alice, XRP(10'000 - 100) - txfee(env, 2)), balance(bob, USD(80))); + } + { + // Offer where the owner is also the issuer, sender pays + // fee + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, gw); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .transferFee = 25'000, + .maxAmt = 1'000}); + + env(offer(gw, XRP(125), USD(125))); + env(pay(alice, bob, USD(100)), sendmax(XRP(200))); + env.require(balance(alice, XRP(10'000 - 125) - txfee(env, 2)), balance(bob, USD(100))); + } + } + + void + testFalseDry(FeatureBitset features) + { + testcase("falseDryChanges"); + + using namespace jtx; + + auto const gw = Account("gateway"); + Account const alice("alice"); + Account const bob("bob"); + Account const carol("carol"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, carol, gw); + env.fund(reserve(env, 5), bob); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol, bob}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, carol, bob}}); + + env(pay(gw, alice, EUR(50))); + env(pay(gw, bob, USD(50))); + + // Bob has _just_ slightly less than 50 xrp available + // If his owner count changes, he will have more liquidity. + // This is one error case to test (when Flow is used). + // Computing the incoming xrp to the XRP/USD offer will + // require two recursive calls to the EUR/XRP offer. The + // second call will return tecPATH_DRY, but the entire path + // should not be marked as dry. This is the second error + // case to test (when flowV1 is used). + env(offer(bob, EUR(50), XRP(50))); + env(offer(bob, XRP(50), USD(50))); + + env(pay(alice, carol, USD(1'000'000)), + path(~XRP, ~USD), + sendmax(EUR(500)), + txflags(tfNoRippleDirect | tfPartialPayment)); + + auto const carolUSD = env.balance(carol, USD).value(); + BEAST_EXPECT(carolUSD > USD(0) && carolUSD < USD(50)); + }; + testHelper2TokensMix(test); + } + + void + testLimitQuality() + { + // Single path with two offers and limit quality. The + // quality limit is such that the first offer should be + // taken but the second should not. The total amount + // delivered should be the sum of the two offers and sendMax + // should be more than the first offer. + testcase("limitQuality"); + using namespace jtx; + + auto const gw = Account("gateway"); + Account const alice("alice"); + Account const bob("bob"); + Account const carol("carol"); + + { + Env env(*this); + + env.fund(XRP(10'000), alice, bob, carol, gw); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, bob, USD(100))); + env(offer(bob, XRP(50), USD(50))); + env(offer(bob, XRP(100), USD(50))); + + env(pay(alice, carol, USD(100)), + path(~USD), + sendmax(XRP(100)), + txflags(tfNoRippleDirect | tfPartialPayment | tfLimitQuality)); + + env.require(balance(carol, USD(50))); + } + } + + // Helper function that returns the reserve on an account based on + // the passed in number of owners. + static XRPAmount + reserve(jtx::Env& env, std::uint32_t count) + { + return env.current()->fees().accountReserve(count); + } + + // Helper function that returns the Offers on an account. + static std::vector> + offersOnAccount(jtx::Env& env, jtx::Account account) + { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + result.push_back(sle); + }); + return result; + } + + void + testSelfPayment1(FeatureBitset features) + { + testcase("Self-payment 1"); + + // In this test case the new flow code mis-computes the + // amount of money to move. Fortunately the new code's + // re-execute check catches the problem and throws out the + // transaction. + // + // The old payment code handles the payment correctly. + using namespace jtx; + + auto test = [&](auto&& issue1, auto&& issue2) { + auto const gw1 = Account("gw1"); + auto const gw2 = Account("gw2"); + auto const alice = Account("alice"); + + Env env(*this, features); + + env.fund(XRP(1'000'000), gw1, gw2); + env.close(); + + // The fee that's charged for transactions. + auto const f = env.current()->fees().base; + + env.fund(reserve(env, 3) + f * 4, alice); + env.close(); + + auto const USD = issue1( + {.env = env, .token = "USD", .issuer = gw1, .holders = {alice}, .limit = 20'000}); + auto const EUR = issue2( + {.env = env, .token = "EUR", .issuer = gw2, .holders = {alice}, .limit = 20'000}); + + env(pay(gw1, alice, USD(10))); + env(pay(gw2, alice, EUR(10'000))); + env.close(); + + env(offer(alice, USD(5'000), EUR(6'000))); + env.close(); + + env.require(owners(alice, 3)); + env.require(balance(alice, USD(10))); + env.require(balance(alice, EUR(10'000))); + + auto aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == EUR(6'000)); + BEAST_EXPECT(offer[sfTakerPays] == USD(5'000)); + } + + env(pay(alice, alice, EUR(6'000)), sendmax(USD(5'000)), txflags(tfPartialPayment)); + env.close(); + + env.require(owners(alice, 3)); + env.require(balance(alice, USD(10))); + env.require(balance(alice, EUR(10'000))); + aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + if constexpr (std::is_same_v, IOU>) + { + BEAST_EXPECT(offer[sfTakerGets] == EUR(5'988)); + } + else + { + BEAST_EXPECT(offer[sfTakerGets] == EUR(5'989)); + } + BEAST_EXPECT(offer[sfTakerPays] == USD(4'990)); + } + }; + testHelper2TokensMix(test); + } + + template + struct TokenData + { + TGets gets; + TPays pays; + jtx::PrettyAmount remTakerGets; + jtx::PrettyAmount remTakerPays; + }; + + void + testSelfPayment2(FeatureBitset features) + { + testcase("Self-payment 2"); + + using namespace jtx; + + // This test shows a difference between IOU and MPT + // self-payment result depending on IOU trustline limit. + + auto const gw1 = Account("gw1"); + auto const gw2 = Account("gw2"); + auto const alice = Account("alice"); + + auto initMPT = [&](Env& env) { + MPT const USD = + MPTTester({.env = env, .issuer = gw1, .holders = {alice}, .maxAmt = 506}); + MPT const EUR = + MPTTester({.env = env, .issuer = gw2, .holders = {alice}, .maxAmt = 606}); + // Payment's engine last step overflows + // OutstandingAmount since it doesn't know if the + // BookStep redeems or not. The BookStep then has 600EUR + // available. Consequently, the entire offer is crossed. + // Note remaining takerGets is 541 rather than 540 due to integral + // rounding. XRP has a similar result. + return TokenData{EUR, USD, EUR(541), USD(450)}; + }; + + auto initXRP = [&](Env& env) { + MPT const USD = + MPTTester({.env = env, .issuer = gw1, .holders = {alice}, .maxAmt = 1'000}); + // Payment's engine last step overflows + // OutstandingAmount since it doesn't know if the + // BookStep redeems or not. The BookStep then has 600EUR + // available. Consequently, the entire offer is crossed. + // Note remaining takerGets is 540.000001 rather than 540 due to + // integral rounding. + return TokenData{XRP, USD, XRP(540.000001), USD(450)}; + }; + + auto initIOU = [&](Env& env) { + auto const USD = gw1["USD"]; + auto const EUR = gw2["EUR"]; + env(trust(alice, USD(506))); + env(trust(alice, EUR(606))); + env.close(); + // Payment's engine last step is limited by alice's + // trustline - 606. Therefore, only 6EUR is delivered + // and the offer is partially crossed. + return TokenData{EUR, USD, EUR(594), USD(495)}; + }; + + auto initIOU1 = [&](Env& env) { + auto const USD = gw1["USD"]; + auto const EUR = gw2["EUR"]; + env(trust(alice, USD(1'000))); + env(trust(alice, EUR(1'000))); + env.close(); + // Payment's engine last step is not limited by alice's + // trustline. Therefore, the entire offer is crossed. + // This the same result as with MPT. + return TokenData{EUR, USD, EUR(540), USD(450)}; + }; + + auto test = [&](auto&& initToken) { + Env env(*this, features); + + env.fund(XRP(2'000), gw1, gw2, alice); + env.close(); + + auto const f = env.current()->fees().base; + + auto const tok = initToken(env); + + auto const& TOK1 = tok.pays; + auto const& TOK2 = tok.gets; + bool const isTakerGetsXRP = isXRP(Asset{TOK2}); + std::uint32_t const ownerCnt = isTakerGetsXRP ? 2 : 3; + + env(pay(gw1, alice, TOK1(500))); + if (!isTakerGetsXRP) + env(pay(gw2, alice, TOK2(600))); + env.close(); + + env(offer(alice, TOK1(500), TOK2(600))); + env.close(); + + env.require(owners(alice, ownerCnt)); + env.require(balance(alice, TOK1(500))); + if (isTakerGetsXRP) + { + env.require(balance(alice, TOK2(2'000) - 2 * f)); + } + else + { + env.require(balance(alice, TOK2(600))); + } + + auto aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == TOK2(600)); + BEAST_EXPECT(offer[sfTakerPays] == TOK1(500)); + } + + env(pay(alice, alice, TOK2(60)), sendmax(TOK1(50)), txflags(tfPartialPayment)); + env.close(); + + env.require(owners(alice, ownerCnt)); + env.require(balance(alice, TOK1(500))); + if (isTakerGetsXRP) + { + env.require(balance(alice, TOK2(2'000) - 3 * f)); + } + else + { + env.require(balance(alice, TOK2(600))); + } + aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == tok.remTakerGets); + BEAST_EXPECT(offer[sfTakerPays] == tok.remTakerPays); + } + }; + + test(initXRP); + test(initMPT); + test(initIOU); + test(initIOU1); + } + + void + testSelfFundedXRPEndpoint(bool consumeOffer, FeatureBitset features) + { + // Test that the deferred credit table is not bypassed for + // XRPEndpointSteps. If the account in the first step is + // sending XRP and that account also owns an offer that + // receives XRP, it should not be possible for that step to + // use the XRP received in the offer as part of the payment. + testcase("Self funded XRPEndpoint"); + + using namespace jtx; + + Env env(*this, features); + + auto const alice = Account("alice"); + auto const gw = Account("gw"); + + env.fund(XRP(10'000), alice, gw); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 20}); + + env(pay(gw, alice, USD(10))); + env(offer(alice, XRP(50'000), USD(10))); + + // Consuming the offer changes the owner count, which could + // also cause liquidity to decrease in the forward pass + auto const toSend = consumeOffer ? USD(10) : USD(9); + env(pay(alice, alice, toSend), + path(~USD), + sendmax(XRP(20'000)), + txflags(tfPartialPayment | tfNoRippleDirect)); + } + + void + testUnfundedOffer(FeatureBitset features) + { + testcase("Unfunded Offer"); + + using namespace jtx; + { + // Test reverse + Env env(*this, features); + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + + env.fund(XRP(100'000), alice, bob, gw); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20E+17}); + + // scale by 17 + STAmount const tinyAmt1{USD, 9'000'000'000'000'000ll, 0, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{USD, 9'000'000'000'000'003ll, 0, false, STAmount::unchecked{}}; + + env(offer(gw, drops(9'000'000'000), tinyAmt3)); + + env(pay(alice, bob, tinyAmt1), + path(~USD), + sendmax(drops(9'000'000'000)), + txflags(tfNoRippleDirect)); + + BEAST_EXPECT(!isOffer(env, gw, XRP(0), USD(0))); + } + { + // Test forward + Env env(*this, features); + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + + env.fund(XRP(100'000), alice, bob, gw); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 20E+17}); + + // scale by 17 + STAmount const tinyAmt1{USD, 9'000'000'000'000'000ll, 0, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{USD, 9'000'000'000'000'003ll, 0, false, STAmount::unchecked{}}; + + env(pay(gw, alice, tinyAmt1)); + + env(offer(gw, tinyAmt3, drops(9'000'000'000))); + env(pay(alice, bob, drops(9'000'000'000)), + path(~XRP), + sendmax(USD(static_cast(1E+17))), + txflags(tfNoRippleDirect)); + + BEAST_EXPECT(!isOffer(env, gw, USD(0), XRP(0))); + } + } + + void + testReExecuteDirectStep(FeatureBitset features) + { + testcase("ReexecuteDirectStep"); + + using namespace jtx; + Env env(*this, features); + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + + env.fund(XRP(10'000), alice, bob, gw); + + // scale by 16 + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 100E+16}); + + env( + pay(gw, + alice, + // 12.55.... + STAmount{USD, std::uint64_t(1255555555555555ull), 2, false})); + + env(offer( + gw, + // 5.0... + STAmount{USD, std::uint64_t(5000000000000000ull), 1, false}, + XRP(1000))); + + env(offer( + gw, + // .555... + STAmount{USD, std::uint64_t(5555555555555555ull), 0, false}, + XRP(10))); + + env(offer( + gw, + // 4.44.... + STAmount{USD, std::uint64_t(4444444444444444ull), 1, false}, + XRP(.1))); + + env(offer( + alice, + // 17 + STAmount{USD, std::uint64_t(1700000000000000ull), 0, false}, + XRP(.001))); + + env(pay(alice, bob, XRP(10'000)), + path(~XRP), + sendmax(USD(static_cast(100E+16))), + txflags(tfPartialPayment | tfNoRippleDirect)); + } + + void + testSelfPayLowQualityOffer(FeatureBitset features) + { + // The new payment code used to assert if an offer was made + // for more XRP than the offering account held. This unit + // test reproduces that failing case. + testcase("Self crossing low quality offer"); + + using namespace jtx; + + Env env(*this, features); + + auto const ann = Account("ann"); + auto const gw = Account("gateway"); + + auto const fee = env.current()->fees().base; + env.fund(reserve(env, 2) + drops(9999640) + fee, ann); + env.fund(reserve(env, 2) + fee * 4, gw); + + // scale by 5 + MPT const CTB = MPTTester( + {.env = env, + .issuer = gw, + .holders = {ann}, + .transferFee = 2'000, // 2% + .maxAmt = 1'000'000}); + + env(pay(gw, ann, CTB(285'600))); + env.close(); + + env(offer(ann, drops(365'611'702'030), CTB(571'300))); + env.close(); + + // This payment caused assert. + env(pay(ann, ann, CTB(68'700)), sendmax(drops(20'000'000'000)), txflags(tfPartialPayment)); + } + + void + testEmptyStrand(FeatureBitset features) + { + testcase("Empty Strand"); + using namespace jtx; + + auto const alice = Account("alice"); + + Env env(*this, features); + + env.fund(XRP(10000), alice); + + MPT const USD; + + env(pay(alice, alice, USD(100)), path(~USD), ter(temBAD_PATH)); + } + + void + testXRPPathLoop() + { + testcase("Circular XRP"); + + using namespace jtx; + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + + { + // Payment path starting with XRP + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(10'000), alice, bob, gw); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}}); + env(pay(gw, alice, USD(100))); + env(pay(gw, alice, EUR(100))); + env.close(); + + env(offer(alice, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(alice, USD(100), XRP(100)), txflags(tfPassive)); + env(offer(alice, XRP(100), EUR(100)), txflags(tfPassive)); + env.close(); + + TER const expectedTer = TER{temBAD_PATH_LOOP}; + env(pay(alice, bob, EUR(1)), + path(~USD, ~XRP, ~EUR), + sendmax(XRP(1)), + txflags(tfNoRippleDirect), + ter(expectedTer)); + }; + testHelper2TokensMix(test); + } + { + // Payment path ending with XRP + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + env.fund(XRP(10'000), alice, bob, gw); + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}}); + env(pay(gw, alice, USD(100))); + env(pay(gw, alice, EUR(100))); + env.close(); + + env(offer(alice, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(alice, EUR(100), XRP(100)), txflags(tfPassive)); + env.close(); + // EUR -> //XRP -> //USD ->XRP + env(pay(alice, bob, XRP(1)), + path(~XRP, ~USD, ~XRP), + sendmax(EUR(1)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper2TokensMix(test); + } + { + // Payment where loop is formed in the middle of the + // path, not on an endpoint + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this); + env.fund(XRP(10'000), alice, bob, gw); + env.close(); + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {alice, bob}}); + auto const JPY = + issue3({.env = env, .token = "JPY", .issuer = gw, .holders = {alice, bob}}); + env(pay(gw, alice, USD(100))); + env(pay(gw, alice, EUR(100))); + env(pay(gw, alice, JPY(100))); + env.close(); + + env(offer(alice, USD(100), XRP(100)), txflags(tfPassive)); + env(offer(alice, XRP(100), EUR(100)), txflags(tfPassive)); + env(offer(alice, EUR(100), XRP(100)), txflags(tfPassive)); + env(offer(alice, XRP(100), JPY(100)), txflags(tfPassive)); + env.close(); + + env(pay(alice, bob, JPY(1)), + path(~XRP, ~EUR, ~XRP, ~JPY), + sendmax(USD(1)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper3TokensMix(test); + } + } + + void + testMaxAndSelfPaymentEdgeCases(FeatureBitset features) + { + testcase("Max Flow/Self Payment Edge Cases"); + using namespace jtx; + Account const gw("gw"); + Account const alice("alice"); + Account const carol("carol"); + Account const bob("bob"); + + // Direct payment between holders. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100}); + + env(pay(gw, alice, USD(100))); + + env(pay(alice, carol, USD(100))); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + } + + // Direct payment between holders. Partial payment limited + // by holder funds. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100}); + + env(pay(gw, alice, USD(80))); + + env(pay(alice, carol, USD(100)), txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-80)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + BEAST_EXPECT(env.balance(carol, USD) == USD(80)); + } + + // Direct payment between holders. Partial payment limited + // by holder funds. OutstandingAmount is already at max + // before the payment. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol, bob); + + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 100}); + + env(pay(gw, bob, USD(20))); + env(pay(gw, alice, USD(80))); + + env(pay(alice, carol, USD(100)), txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + BEAST_EXPECT(env.balance(carol, USD) == USD(80)); + } + + // Cross-currency payment holder to holder. Holder owns an + // offer. OutstandingAmount is already at max before the + // payment. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol, bob); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 100}); + + env(pay(gw, alice, USD(100))); + + env(offer(alice, XRP(100), USD(100))); + + env(pay(bob, carol, USD(100)), sendmax(XRP(100)), path(~USD)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + } + + // Cross-currency payment holder to holder. Issuer owns an + // offer. OutstandingAmount is already at max before the + // payment. Since an issuer owns the offer, it issues more + // tokens to another holder, and the payment fails. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100}); + + env(pay(gw, carol, USD(100))); + + env(offer(gw, XRP(100), USD(100))); + + env(pay(alice, carol, USD(100)), + sendmax(XRP(100)), + path(~USD), + txflags(tfPartialPayment), + ter(tecPATH_DRY)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + } + + // Cross-currency payment holder to holder. Issuer owns an + // offer. OutstandingAmount is at 80USD before the payment. + // Consequently, the issuer can issue 20USD more. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100}); + + env(pay(gw, carol, USD(80))); + + env(offer(gw, XRP(100), USD(100))); + + env(pay(alice, carol, USD(100)), + sendmax(XRP(100)), + path(~USD), + txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + } + + // Cross-currency payment holder to holder. Holder owns an + // offer. The offer buys more MPT's. The payment fails since + // OutstandingAmount is already at max. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = 100}); + + env(pay(gw, alice, USD(100))); + + env(offer(alice, USD(100), XRP(100))); + + env(pay(gw, alice, XRP(100)), sendmax(USD(100)), path(~XRP), ter(tecPATH_PARTIAL)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(alice, USD) == USD(100)); + } + + // Cross-currency payment issuer to holder. Holder owns an + // offer. The offer buys EUR, OutstandingAmount goes to max, + // no overflow. The offer redeems USD to the issuer. While + // OutstandingAmount is already at max, the payment succeeds + // since USD is redeemed. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol}, + .limit = 100}); + using tUSD = std::decay_t; + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, carol}, + .limit = 100}); + + env(pay(gw, alice, USD(100))); + + env(offer(alice, EUR(100), USD(100))); + + env(pay(gw, carol, USD(100)), sendmax(EUR(100)), path(~USD)); + + if constexpr (std::is_same_v) + BEAST_EXPECT(env.balance(gw, USD) == USD(-100)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + BEAST_EXPECT(env.balance(alice, EUR) == EUR(100)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + }; + testHelper2TokensMix(test); + } + + // Cross-currency payment holder to holder. Offer is owned + // by destination account. OutstandingAmount is not at max. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 120}); + + env(pay(gw, carol, USD(100))); + + env(offer(carol, XRP(100), USD(100))); + + env(pay(alice, carol, USD(100)), + path(~USD), + sendmax(XRP(100)), + txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + } + + // Cross-currency payment holder to holder. Offer is owned + // by destination account. OutstandingAmount is already at + // max. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {carol}, .maxAmt = 100}); + + env(pay(gw, carol, USD(100))); + + env(offer(carol, XRP(100), USD(100))); + + env(pay(alice, carol, USD(100)), + path(~USD), + sendmax(XRP(100)), + txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + } + + // Cross-currency payment holder to holder. Multiple offers + // with different owners - some holders, some issuer. + { + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol, bob); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, carol, bob}, + .limit = 1'000}); + using tUSD = std::decay_t; + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, carol, bob}, + .limit = 1'000}); + using tEUR = std::decay_t; + + env(pay(gw, alice, USD(600))); + env(pay(gw, carol, EUR(700))); + + env(offer(alice, EUR(100), USD(105))); + env(offer(gw, EUR(100), USD(104))); + env(offer(gw, EUR(100), USD(103))); + env(offer(gw, EUR(100), USD(102))); + env(offer(gw, EUR(100), USD(101))); + env(offer(gw, EUR(100), USD(100))); + + env(pay(carol, bob, USD(2'000)), + sendmax(EUR(2'000)), + path(~USD), + txflags(tfPartialPayment)); + + if constexpr (std::is_same_v) + { + BEAST_EXPECT(env.balance(gw, USD) == USD(-1'000)); + BEAST_EXPECT(env.balance(alice, USD) == USD(495)); + BEAST_EXPECT(env.balance(bob, USD) == USD(505)); + } + else + { + BEAST_EXPECT(env.balance(gw, USD) == USD(0)); + BEAST_EXPECT(env.balance(alice, USD) == USD(495)); + // all offers are consumed since the limit is different + // for the holders + BEAST_EXPECT(env.balance(bob, USD) == USD(615)); + } + if constexpr (std::is_same_v) + { + if constexpr (std::is_same_v) + { + BEAST_EXPECT(env.balance(carol, EUR) == EUR(210)); + } + else + { + // carol sells 600USD since all offers are consumed + BEAST_EXPECT(env.balance(carol, EUR) == EUR(100)); + } + } + else + { + BEAST_EXPECT( + env.balance(carol, EUR) == STAmount(EUR, UINT64_C(209'9009900990099), -13)); + } + // 100/101 is partially crossed (90/91) and 100/100 is + // unfunded when MPT. All offers are consumed if IOU. + env.require(offers(gw, 0)); + // alice's offer is consumed. + env.require(offers(alice, 0)); + }; + testHelper2TokensMix(test); + } + + // Cross-currency payment holder to holder. Multiple offers + // with different owners - some holders, some issuer. Source + // and destination account is the same. + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}, .maxAmt = 2'000}); + + env(pay(gw, carol, USD(1'000))); + env(pay(gw, alice, USD(600))); + + env(offer(gw, XRP(5), USD(11))); + env(offer(gw, XRP(6), USD(13))); + env(offer(carol, XRP(7), USD(15))); + env(offer(carol, XRP(17), USD(35))); + env(offer(carol, XRP(23), USD(47))); + env(offer(alice, XRP(10), USD(19))); + env(offer(alice, XRP(15), USD(28))); + env(offer(alice, XRP(25), USD(46))); + + env(pay(carol, carol, USD(200)), sendmax(XRP(100)), txflags(tfPartialPayment)); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-1'624)); + BEAST_EXPECT(env.balance(carol, USD) == USD(1'102)); + env.require(offers(carol, 0)); + env.require(offers(gw, 0)); + // 100 XRP's = 5+6+7+17+23+10+15+17(25-8) + BEAST_EXPECT(isOffer(env, alice, XRP(8), USD(15))); + } + + // Cross-currency payment holder to holder. Multiple offers + // with different owners - some holders, some issuer. + { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 30}); + + env(pay(gw, alice, USD(12))); // 12, 15, 20 + env(pay(gw, bob, USD(5))); // 5, 5, 10 + + env(offer(alice, XRP(10), USD(12))); + env(offer(gw, XRP(10), USD(11))); + env(offer(bob, XRP(10), USD(10))); + + env(pay(carol, bob, USD(30)), sendmax(XRP(30)), txflags(tfPartialPayment), path(~USD)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-28)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + // 12+11+5 + BEAST_EXPECT(env.balance(bob, USD) == USD(28)); + } + + // Cross-currency payment two steps. Second book step + // issues, first book step redeems. + { + Account const dan{"dan"}; + Account const john{"john"}; + Account const ed{"ed"}; + Account const sam{"sam"}; + Account const bill{"bill"}; + + struct TestData + { + int maxAmt; + int sendMax; + int dstTrustLimit; + int dstExpectEUR; + int outstandingUSD; + int expEdBuyUSD; + int expDanBuyUSD; + int expBobSellUSD; + int expGwXRP; // whole XRP excluding the fees + std::uint8_t expOffersGw; + bool lastGwBuyUSD; + std::uint8_t + expOffersBob() const + { + return expBobSellUSD == 0 ? 1 : 0; + } + std::uint8_t + expOffersEd() const + { + // partially crossed if < 100 + return expEdBuyUSD < 100 ? 1 : 0; + } + std::uint8_t + expOffersDan() const + { + return expDanBuyUSD == 0 ? 1 : 0; + } + }; + + auto test = [&](TestData const& d) { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob, dan, john, ed, sam, bill); + env.close(); + + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = d.maxAmt}); + auto const EUR = gw["EUR"]; + + env(pay(gw, alice, USD(100))); + env(pay(gw, carol, USD(100))); + env(pay(gw, bob, USD(100))); + + BEAST_EXPECT(env.balance(gw, USD) == USD(-300)); + + env(trust(john, EUR(100))); + env(trust(dan, EUR(100))); + env(trust(ed, EUR(100))); + env(trust(bill, EUR(d.dstTrustLimit))); + + env(pay(gw, john, EUR(100))); + env(pay(gw, dan, EUR(100))); + env(pay(gw, ed, EUR(100))); + env.close(); + + // Sell USD + env(offer(alice, XRP(100), USD(100))); + env.close(); // close after each create to ensure + // the order + env(offer(carol, XRP(100), USD(100))); + env.close(); + if (!d.lastGwBuyUSD) + { + env(offer(gw, XRP(100), USD(100))); + env.close(); + } + env(offer(bob, XRP(100), USD(100))); + env.close(); + if (d.lastGwBuyUSD) + { + env(offer(gw, XRP(100), USD(100))); + env.close(); + } + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(expectOffers(env, carol, 1)); + BEAST_EXPECT(expectOffers(env, gw, 1)); + BEAST_EXPECT(expectOffers(env, bob, 1)); + + // Buy USD + env(offer(john, USD(100), EUR(100))); + env.close(); + env(offer(gw, USD(100), EUR(100))); + env.close(); + env(offer(dan, USD(100), EUR(100))); + env.close(); + env(offer(ed, USD(100), EUR(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, john, 1)); + BEAST_EXPECT(expectOffers(env, gw, 2)); + BEAST_EXPECT(expectOffers(env, dan, 1)); + BEAST_EXPECT(expectOffers(env, ed, 1)); + + env(pay(sam, bill, EUR(400)), + sendmax(XRP(d.sendMax)), + path(~USD, ~EUR), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + auto const baseFee = env.current()->fees().base.drops(); + BEAST_EXPECT(env.balance(bill, EUR) == EUR(d.dstExpectEUR)); + BEAST_EXPECT(env.balance(john, USD) == USD(100)); + BEAST_EXPECT(env.balance(dan, USD) == USD(d.expDanBuyUSD)); + BEAST_EXPECT(env.balance(ed, USD) == USD(d.expEdBuyUSD)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-d.outstandingUSD)); + BEAST_EXPECT(env.balance(alice, USD) == USD(0)); + BEAST_EXPECT(env.balance(carol, USD) == USD(0)); + BEAST_EXPECT(env.balance(bob, USD) == USD(100 - d.expBobSellUSD)); + BEAST_EXPECT( + env.balance(gw) == XRPAmount{d.expGwXRP * DROPS_PER_XRP - baseFee * 9}); + BEAST_EXPECT(expectOffers(env, john, 0)); + BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); + BEAST_EXPECT(expectOffers(env, dan, d.expOffersDan())); + BEAST_EXPECT(expectOffers(env, ed, d.expOffersEd())); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob())); + }; + + // clang-format off + std::vector const tests = { + // Sell USD: alice, carol, bob, gw are consumed. + // Buy USD: john, gw, dan, ed are consumed. + // gw's sell USD is consumed because there is sufficient available balance (100USD). + // but OutstandingAmount is 300USD because gw's sell offer is balanced out by + // gw's buy offer. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 400, 400, 400, 400, 300, 100, 100, 100, 1100, 0, false}, + // Sell USD: alice, carol, bob, gw are consumed. + // Buy USD: john, gw, dan, ed (partially) are consumed. + // gw's sell USD is partially consumed because there is available balance (50USD). + // OutstandingAmount is 250USD because gw's sell offer is partially balanced by + // gw's buy offer. ed's offer is on the books because it's partially crossed. + // gw's offer is removed from the order book because it's partially consumed and + // the remaining offer is unfunded. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 350, 400, 400, 350, 250, 50, 100, 100, 1050, 0, false}, + // Sell USD: alice, carol, bob are consumed; gw's is unfunded + // since OutstandingAmount is initially at MaximumAmount. + // Buy USD: john, gw, dan are consumed; ed's remains on the order + // book since 300USD is the sell limit. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 300, 400, 400, 300, 200, 0, 100, 100, 1000, 0, false}, + // Same as above. bill's trustline limit sets the output to 300USD. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 300, 400, 300, 300, 200, 0, 100, 100, 1000, 0, false}, + // Sell USD: alice, carol, bob are consumed; gw's removed from + // the order book since it's unfunded. + // Buy USD: john, gw, dan are consumed; ed's remains on the order + // book since 300USD is the limit. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 300, 400, 300, 300, 200, 0, 100, 100, 1000, 0, true}, + // Sell USD: alice, carol are consumed; gw's removed from + // the order book in rev pass since it's unfunded; bob's + // remains on the order book. + // Buy USD: john, gw; ed's, dan's remains on the order + // book since 300USD is the limit. + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 300, 200, 300, 200, 200, 0, 0, 0, 1000, 0, false}, + // Same as three tests above since limited by buy 300USD (gw offer is unfunded) + //*maxAmt sendMax limitEUR expectEUR outstandingUSD edBuy danBuy bobSell gwXRP offersGw lastGw + { 300, 380, 400, 300, 200, 0, 100, 100, 1000, 0, false}, + }; + // clang-format on + for (auto const& t : tests) + test(t); + } + + // Cross-currency payment. BookStep issues, the first step + // redeems. + { + Account const ed{"ed"}; + + struct TestData + { + int maxAmt; + int sendMax; + int gwOffer; // quality == 1 + int dstExpectXRP; + int outstandingUSD; + int expBobBuyUSD; + int expGwXRP; // whole XRP excluding the fees + std::uint8_t expOffersGw; + bool lastGwBuyUSD; + std::uint8_t + expOffersBob() const + { + // partially crossed if < 100 + return expBobBuyUSD < 100 ? 1 : 0; + } + }; + + auto test = [&](TestData const& d) { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob, ed); + env.close(); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .maxAmt = d.maxAmt}); + + env(pay(gw, alice, USD(300))); + env.close(); + + env(offer(carol, USD(100), XRP(100))); + env.close(); + if (!d.lastGwBuyUSD) + { + env(offer(gw, USD(d.gwOffer), XRP(d.gwOffer))); + env.close(); + } + env(offer(bob, USD(100), XRP(100))); + env.close(); + if (d.lastGwBuyUSD) + { + env(offer(gw, USD(d.gwOffer), XRP(d.gwOffer))); + env.close(); + } + + BEAST_EXPECT(expectOffers(env, carol, 1)); + BEAST_EXPECT(expectOffers(env, bob, 1)); + BEAST_EXPECT(expectOffers(env, gw, 1)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-300)); + + env(pay(alice, ed, XRP(300)), + sendmax(USD(d.sendMax)), + path(~XRP), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + auto const baseFee = env.current()->fees().base.drops(); + BEAST_EXPECT(env.balance(alice, USD) == USD(300 - d.sendMax)); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + BEAST_EXPECT(env.balance(bob, USD) == USD(d.expBobBuyUSD)); + BEAST_EXPECT(env.balance(ed) == XRP(d.dstExpectXRP)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-d.outstandingUSD)); + BEAST_EXPECT( + env.balance(gw) == XRPAmount{d.expGwXRP * DROPS_PER_XRP - baseFee * 3}); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob())); + BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); + }; + + // clang-format off + std::vector const tests = { + // Buy USD: carol, gw, bob are consumed. + // Gw gets 300USD from alice; carol and bob buy 200USD, + // therefore OutstandingAmount is 200. + //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw + { 300, 300, 100, 1300, 200, 100, 900, 0, false}, + // Same as above. Gw offer location in the order book doesn't matter + //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw + { 300, 300, 100, 1300, 200, 100, 900, 0, true}, + // Buy USD: carol, gw are consumed. bob's offer remains on the order book. + // Gw gets 300USD from alice; carol buys 100USD, + // therefore OutstandingAmount is 100. + //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw + { 300, 300, 200, 1300, 100, 0, 800, 0, false}, + // Buy USD: carol, bob are consumed; gw's is partially consumed (100/100) since it's last. + // Gw gets 300USD from alice; carol and bob buy 200USD, + // therefore OutstandingAmount is 200. + //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw + { 300, 300, 200, 1300, 200, 100, 900, 1, true}, + // Buy USD: carol, bob are consumed; gw's is partially consumed (50/50) since it's last + // and sendMax limits the output. + // Gw gets 250USD from alice; carol and bob buy 200USD, alice has 50USD left, + // therefore OutstandingAmount is 200. + //*maxAmt sendMax gwOffer dstXRP outstandingUSD bobBuy gwXRP offersGw lastGw + { 300, 250, 200, 1250, 250, 100, 950, 1, true}, + }; + // clang-format on + for (auto const& t : tests) + test(t); + } + + // Cross-currency payment. BookStep redeems, the last step + // issues. + { + Account const ed{"ed"}; + + struct TestData + { + int maxAmt; + int sendMax; + int initDst; + int gwOffer; // quality == 1 + int dstExpectUSD; + int outstandingUSD; + int expAliceXRP; // whole XRP excluding the fees + int expBobSellUSD; + int expGwXRP; + std::uint8_t expOffersGw; + bool lastGwBuyUSD; + std::uint8_t + expOffersBob() const + { + return expBobSellUSD > 0 && expBobSellUSD < 100 ? 1 : 0; + } + }; + + auto test = [&](TestData const& d) { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob, ed); + env.close(); + + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {carol, bob, ed}, .maxAmt = d.maxAmt}); + + if (d.initDst != 0) + env(pay(gw, ed, USD(d.initDst))); + env(pay(gw, carol, USD(100))); + env(pay(gw, bob, USD(100))); + env.close(); + + env(offer(carol, XRP(100), USD(100))); + env.close(); + if (!d.lastGwBuyUSD) + { + env(offer(gw, XRP(d.gwOffer), USD(d.gwOffer))); + env.close(); + } + env(offer(bob, XRP(100), USD(100))); + env.close(); + if (d.lastGwBuyUSD) + { + env(offer(gw, XRP(d.gwOffer), USD(d.gwOffer))); + env.close(); + } + + BEAST_EXPECT(expectOffers(env, carol, 1)); + BEAST_EXPECT(expectOffers(env, bob, 1)); + BEAST_EXPECT(expectOffers(env, gw, 1)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-200 - d.initDst)); + + env(pay(alice, ed, USD(300)), + sendmax(XRP(d.sendMax)), + path(~USD), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + auto const baseFee = env.current()->fees().base.drops(); + BEAST_EXPECT( + env.balance(alice) == XRPAmount{d.expAliceXRP * DROPS_PER_XRP - baseFee}); + BEAST_EXPECT(env.balance(carol, USD) == USD(0)); + BEAST_EXPECT(env.balance(bob, USD) == USD(100 - d.expBobSellUSD)); + BEAST_EXPECT(env.balance(ed, USD) == USD(d.dstExpectUSD)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-d.outstandingUSD)); + BEAST_EXPECT( + env.balance(gw) == + XRPAmount{ + d.expGwXRP * DROPS_PER_XRP - baseFee * (4 + (d.initDst != 0 ? 1 : 0))}); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, bob, d.expOffersBob())); + BEAST_EXPECT(expectOffers(env, gw, d.expOffersGw)); + }; + + // clang-format off + std::vector const tests = { + // Sell USD: carol, gw, bob are consumed. + // ed buys 300USD from carol, gw, bob therefore OutstandingAmount is 300. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 300, 0, 100, 300, 300, 700, 100, 1100, 0, false}, + // Same as above. Gw offer location in the order book doesn't matter + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 300, 0, 100, 300, 300, 700, 100, 1100, 0, true}, + // Sell USD: carol, bob are consumed, gw is partially consumed. + // ed buys 200 from carol and bob and 50 from gw because gw can only issue 50 + // (300(max) - 200(carol+bob) - 50(ed)). ed buys 250 from carol, gw, bob and has 50 initially, + // therefore OutstandingAmount is 300. + // gw's offer is removed from the order book because it's partially consumed and the remaining + // offer is unfunded. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 300, 50, 100, 300, 300, 750, 100, 1050, 0, false}, + // Same as above. Gw offer location in the order book doesn't matter. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 300, 50, 100, 300, 300, 750, 100, 1050, 0, true}, + // Same as above. Gw offer size doesn't matter. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 300, 50, 200, 300, 300, 750, 100, 1050, 0, true}, + // Sell USD: carol, gw are consumed, bob is partially consumed. + // ed buys 200 from carol and gw and 50 form bob because of sendMax limit. bob keeps 50, + // therefore OutstandingAmount is 300. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 250, 0, 100, 250, 300, 750, 50, 1100, 0, false}, + // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit. + // ed buys 200 from carol and bob and 50 from gw. Therefore, OutstandingAmount is 250. + // gw's offer remains on the order book because it's partially consumed and has more funds. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 250, 0, 100, 250, 250, 750, 100, 1050, 1, true}, + // Sell USD: carol, bob are consumed, gw is partially consumed because of sendMax limit, also + // there is only 50 available to issue. ed buys 200 from carol and bob and 50 from gw, plus + // he has initially 50, therefore OutstandingAmount is 300. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 250, 50, 100, 300, 300, 750, 100, 1050, 0, true}, + // Sell USD: carol, bob are consumed, gw is not consumed because there is not available funds + // to issue. ed buys 200 from carol and bob and, plus he has initially 100, + // therefore OutstandingAmount is 300. gw offer is removed because it's unfunded. + //*maxAmt sendMax initDst gwOffer dstUSD outstandingUSD aliceXRP bobSell gwXRP offersGw lastGw + { 300, 250, 100, 100, 300, 300, 800, 100, 1000, 0, true}, + }; + // clang-format on + for (auto const& t : tests) + test(t); + } + + // Cross-currency payment with BookStep as the first step. + // BookStep limits the buy amount. + { + auto test = [&](int sendMax, std::uint16_t dstXRP, std::uint8_t expGwOffers) { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .maxAmt = 300}); + + env(offer(carol, USD(400), XRP(400))); + env(offer(gw, USD(100), XRP(100))); + BEAST_EXPECT(expectOffers(env, carol, 1)); + BEAST_EXPECT(expectOffers(env, gw, 1)); + + env(pay(gw, alice, XRP(500)), + sendmax(USD(sendMax)), + path(~XRP), + txflags(tfPartialPayment | tfNoRippleDirect)); + + BEAST_EXPECT(env.balance(alice) == XRP(dstXRP)); + BEAST_EXPECT(env.balance(gw, USD) == USD(-300)); + BEAST_EXPECT(env.balance(carol, USD) == USD(300)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(expectOffers(env, gw, expGwOffers)); + }; + // carol's offer is partially consumed - 300USD/300XRP + // because available amount to issue is 300USD. gw's + // offer is fully consumed because it doesn't change + // OutstandingAmount. Both offers are removed from the + // order book - carol's offer is unfunded and gw's offer + // is fully consumed. + test(500, 1'400, 0); + // carol's offer is partially consumed - 300USD/300XRP + // because available amount to issue is 300USD. gw's + // offer is partially consumed because of sendMax limit. + // carol's offer is removed from the order book because + // it's unfunded. gw's offer remains on the order book + // because it's partially consumed and gw has more + // funds. + test(350, 1'350, 1); + } + } + + void + testWithFeats(FeatureBitset features) + { + using namespace jtx; + + testMaxAndSelfPaymentEdgeCases(features); + testFalseDry(features); + testDirectStep(features); + testBookStep(features); + testTransferRate(features); + testSelfPayment1(features); + testSelfPayment2(features); + testSelfFundedXRPEndpoint(false, features); + testSelfFundedXRPEndpoint(true, features); + testUnfundedOffer(features); + testReExecuteDirectStep(features); + testSelfPayLowQualityOffer(features); + } + + void + run() override + { + using namespace jtx; + auto const sa = testable_amendments(); + testLimitQuality(); + testXRPPathLoop(); + testWithFeats(sa); + testEmptyStrand(sa); + } +}; + +BEAST_DEFINE_TESTSUITE_PRIO(FlowMPT, app, xrpl, 2); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/Flow_test.cpp b/src/test/app/Flow_test.cpp index 0bc5bd1727..218f6fe03a 100644 --- a/src/test/app/Flow_test.cpp +++ b/src/test/app/Flow_test.cpp @@ -450,10 +450,10 @@ struct Flow_test : public beast::unit_test::suite }; { // BTC -> USD - STPath const p1({IPE(USD.issue())}); + STPath const p1({IPE(USD)}); paths.push_back(p1); // BTC -> EUR -> USD - STPath const p2({IPE(EUR.issue()), IPE(USD.issue())}); + STPath const p2({IPE(EUR), IPE(USD)}); paths.push_back(p2); } @@ -876,10 +876,8 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(bob, USD(20))); - STAmount const tinyAmt1{ - USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; - STAmount const tinyAmt3{ - USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt1{USD, 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{USD, 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(offer(gw, drops(9000000000), tinyAmt3)); env(pay(alice, bob, tinyAmt1), @@ -902,10 +900,8 @@ struct Flow_test : public beast::unit_test::suite env.close(); env(trust(alice, USD(20))); - STAmount const tinyAmt1{ - USD.issue(), 9000000000000000ll, -17, false, STAmount::unchecked{}}; - STAmount const tinyAmt3{ - USD.issue(), 9000000000000003ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt1{USD, 9000000000000000ll, -17, false, STAmount::unchecked{}}; + STAmount const tinyAmt3{USD, 9000000000000003ll, -17, false, STAmount::unchecked{}}; env(pay(gw, alice, tinyAmt1)); @@ -944,30 +940,30 @@ struct Flow_test : public beast::unit_test::suite pay(gw, alice, // 12.55.... - STAmount{USD.issue(), std::uint64_t(1255555555555555ull), -14, false})); + STAmount{USD, std::uint64_t(1255555555555555ull), -14, false})); env(offer( gw, // 5.0... - STAmount{USD.issue(), std::uint64_t(5000000000000000ull), -15, false}, + STAmount{USD, std::uint64_t(5000000000000000ull), -15, false}, XRP(1000))); env(offer( gw, // .555... - STAmount{USD.issue(), std::uint64_t(5555555555555555ull), -16, false}, + STAmount{USD, std::uint64_t(5555555555555555ull), -16, false}, XRP(10))); env(offer( gw, // 4.44.... - STAmount{USD.issue(), std::uint64_t(4444444444444444ull), -15, false}, + STAmount{USD, std::uint64_t(4444444444444444ull), -15, false}, XRP(.1))); env(offer( alice, // 17 - STAmount{USD.issue(), std::uint64_t(1700000000000000ull), -14, false}, + STAmount{USD, std::uint64_t(1700000000000000ull), -14, false}, XRP(.001))); env(pay(alice, bob, XRP(10000)), diff --git a/src/test/app/Invariants_test.cpp b/src/test/app/Invariants_test.cpp index 72ed7ba57b..7473ce6de8 100644 --- a/src/test/app/Invariants_test.cpp +++ b/src/test/app/Invariants_test.cpp @@ -587,7 +587,7 @@ class Invariants_test : public beast::unit_test::suite using namespace test::jtx; testcase << "transfers when frozen"; - Account G1{"G1"}; + Account const G1{"G1"}; // Helper function to establish the trustlines auto const createTrustlines = [&](Account const& A1, Account const& A2, Env& env) { // Preclose callback to establish trust lines with gateway @@ -2439,8 +2439,8 @@ class Invariants_test : public beast::unit_test::suite return sample; }; - Account A3{"A3"}; - Account A4{"A4"}; + Account const A3{"A3"}; + Account const A4{"A4"}; auto const precloseXrp = [&](Account const& A1, Account const& A2, Env& env) -> bool { env.fund(XRP(1000), A3, A4); Vault const vault{env}; @@ -3855,6 +3855,154 @@ class Invariants_test : public beast::unit_test::suite precloseMpt); } + void + testMPT() + { + using namespace test::jtx; + testcase << "MPT"; + + // MPT OutstandingAmount > MaximumAmount + doInvariantCheck( + {{"OutstandingAmount overflow"}}, + [](Account const& A1, Account const&, ApplyContext& ac) { + // mptissuance outstanding is negative + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + + MPTIssue const mpt{MPTIssue{makeMptID(sle->getFieldU32(sfSequence), A1)}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); + sleNew->setFieldU64(sfOutstandingAmount, 110); + sleNew->setFieldU64(sfMaximumAmount, 100); + ac.view().insert(sleNew); + return true; + }); + + // MPTToken amount doesn't add up to OutstandingAmount + doInvariantCheck( + {{"invalid OutstandingAmount balance"}}, + [](Account const& A1, Account const& A2, ApplyContext& ac) { + // mptissuance outstanding is negative + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + + MPTIssue const mpt{MPTIssue{makeMptID(sle->getFieldU32(sfSequence), A1)}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); + sleNew->setFieldU64(sfOutstandingAmount, 100); + sleNew->setFieldU64(sfMaximumAmount, 100); + ac.view().insert(sleNew); + + sleNew = std::make_shared(keylet::mptoken(mpt.getMptID(), A2)); + sleNew->setFieldU64(sfMPTAmount, 90); + ac.view().insert(sleNew); + + return true; + }); + + // Overflow/Invalid balance on payment + auto testPayment = [&](std::string const& log, auto&& update) { + MPTID id; + doInvariantCheck( + {{log}}, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { + return update(id, ac, A1); + }, + XRPAmount{}, + STTx{ttPAYMENT, [](STObject& tx) {}}, + {tecINVARIANT_FAILED, tecINVARIANT_FAILED}, + [&](Account const& A1, Account const& A2, Env& env) { + Account const gw("gw"); + env.fund(XRP(1'000), gw); + MPTTester const mpt( + {.env = env, .issuer = gw, .holders = {A1}, .pay = 100, .maxAmt = 100}); + id = mpt.issuanceID(); + return true; + }); + }; + testPayment( + "invalid OutstandingAmount balance", + [&](MPTID const& id, ApplyContext& ac, Account const& A1) { + auto sle = ac.view().peek(keylet::mptoken(id, A1)); + if (!sle) + return false; + sle->setFieldU64(sfMPTAmount, 101); + ac.view().update(sle); + return true; + }); + testPayment( + "OutstandingAmount overflow", [&](MPTID const& id, ApplyContext& ac, Account const&) { + auto sle = ac.view().peek(keylet::mptIssuance(id)); + if (!sle) + return false; + sle->setFieldU64(sfOutstandingAmount, 101); + ac.view().update(sle); + return true; + }); + + // More MPTokens created than expected + std::array, 4> const tests = { + std::make_pair(ttAMM_WITHDRAW, 2), + std::make_pair(ttAMM_CLAWBACK, 2), + std::make_pair(ttAMM_CREATE, 3), + std::make_pair(ttCHECK_CASH, 2)}; + for (auto const& [tx, nTokens] : tests) + { + doInvariantCheck( + {{std::string("MPToken created for the MPT issuer")}}, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { + auto const sle = ac.view().peek(keylet::account(A1.id())); + if (!sle) + return false; + + auto seq = sle->getFieldU32(sfSequence); + for (int i = 0; i < nTokens; ++i) + { + MPTIssue const mpt{MPTIssue{makeMptID(seq + i, A1)}}; + auto sleNew = std::make_shared(keylet::mptIssuance(mpt.getMptID())); + ac.view().insert(sleNew); + + sleNew = std::make_shared(keylet::mptoken(mpt.getMptID(), A2)); + ac.view().insert(sleNew); + } + + return true; + }, + XRPAmount{}, + STTx{tx, [](STObject& tx) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}); + } + + // More MPTokens deleted than expected + for (auto const& tx : {ttAMM_WITHDRAW, ttAMM_CLAWBACK}) + { + MPTID id; + Account const A3("A3"); + doInvariantCheck( + {{"MPT authorize succeeded but created/deleted bad number of mptokens"}}, + [&](Account const& A1, Account const& A2, ApplyContext& ac) { + for (auto const& a : {A1, A2, A3}) + { + auto sle = ac.view().peek(keylet::mptoken(id, a)); + if (!sle) + return false; + ac.view().erase(sle); + } + return true; + }, + XRPAmount{}, + STTx{tx, [](STObject& tx) {}}, + {tecINVARIANT_FAILED, tefINVARIANT_FAILED}, + [&](Account const& A1, Account const& A2, Env& env) { + Account const gw("gw"); + env.fund(XRP(1'000), gw, A3); + MPTTester const mpt({.env = env, .issuer = gw, .holders = {A1, A2, A3}}); + id = mpt.issuanceID(); + return true; + }); + } + } + public: void run() override @@ -3880,6 +4028,7 @@ public: testValidPseudoAccounts(); testValidLoanBroker(); testVault(); + testMPT(); } }; diff --git a/src/test/app/LPTokenTransfer_test.cpp b/src/test/app/LPTokenTransfer_test.cpp index 265ff7d2ef..3a99c8782d 100644 --- a/src/test/app/LPTokenTransfer_test.cpp +++ b/src/test/app/LPTokenTransfer_test.cpp @@ -224,7 +224,7 @@ class LPTokenTransfer_test : public jtx::AMMTest AMM ammAlice1(env, alice, XRP(10'000), USD(10'000)); ammAlice1.deposit(carol, 10'000'000); - fund(env, gw, {alice, carol}, {EUR(10'000)}, Fund::IOUOnly); + fund(env, gw, {alice, carol}, {EUR(10'000)}, Fund::TokenOnly); AMM ammAlice2(env, alice, XRP(10'000), EUR(10'000)); ammAlice2.deposit(carol, 10'000'000); auto const token1 = ammAlice1.lptIssue(); diff --git a/src/test/app/LedgerLoad_test.cpp b/src/test/app/LedgerLoad_test.cpp index 1df41671fe..c4610d0225 100644 --- a/src/test/app/LedgerLoad_test.cpp +++ b/src/test/app/LedgerLoad_test.cpp @@ -57,7 +57,7 @@ class LedgerLoad_test : public beast::unit_test::suite for (auto i = 0; i < 20; ++i) { - Account acct{"A" + std::to_string(i)}; + Account const acct{"A" + std::to_string(i)}; env.fund(XRP(10000), acct); env.close(); if (i > 0 && BEAST_EXPECT(prev.has_value())) @@ -68,7 +68,7 @@ class LedgerLoad_test : public beast::unit_test::suite } env(offer(acct, XRP(100), acct["USD"](1))); env.close(); - prev.emplace(std::move(acct)); + prev.emplace(acct); } retval.ledger = env.rpc("ledger", "current", "full")[jss::result]; diff --git a/src/test/app/LendingHelpers_test.cpp b/src/test/app/LendingHelpers_test.cpp index 56db553583..06728413c8 100644 --- a/src/test/app/LendingHelpers_test.cpp +++ b/src/test/app/LendingHelpers_test.cpp @@ -265,7 +265,7 @@ class LendingHelpers_test : public beast::unit_test::suite auto const expectedOverpaymentManagementFee = Number{10}; // 10% of 100 auto const expectedPrincipalPortion = Number{400}; // 1,000 - 100 - 500 - auto const components = detail::computeOverpaymentComponents( + auto const components = xrpl::detail::computeOverpaymentComponents( IOU, loanScale, overpayment, diff --git a/src/test/app/LoanBroker_test.cpp b/src/test/app/LoanBroker_test.cpp index f7222aa61a..9204a17b69 100644 --- a/src/test/app/LoanBroker_test.cpp +++ b/src/test/app/LoanBroker_test.cpp @@ -495,9 +495,9 @@ class LoanBroker_test : public beast::unit_test::suite Account const issuer{"issuer"}; // For simplicity, alice will be the sole actor for the vault & brokers. - Account alice{"alice"}; + Account const alice{"alice"}; // Evan will attempt to be naughty - Account evan{"evan"}; + Account const evan{"evan"}; // Bystander doesn't have anything to do with the SAV or Broker, or any // of the relevant tokens Account const bystander{"bystander"}; @@ -1290,7 +1290,7 @@ class LoanBroker_test : public beast::unit_test::suite auto const broker = env.le(brokerKeylet); if (!BEAST_EXPECT(broker)) return; - Account brokerPseudo("pseudo", broker->at(sfAccount)); + Account const brokerPseudo("pseudo", broker->at(sfAccount)); // Can't unauthorize LoanBroker pseudo-account asset.authorize( @@ -1527,9 +1527,9 @@ class LoanBroker_test : public beast::unit_test::suite testRIPD4274IOU() { using namespace jtx; - Account issuer("broker"); - Account broker("issuer"); - Account dest("destination"); + Account const issuer("broker"); + Account const broker("issuer"); + Account const dest("destination"); auto const token = issuer["IOU"]; enum TrustState { @@ -1654,9 +1654,9 @@ class LoanBroker_test : public beast::unit_test::suite testRIPD4274MPT() { using namespace jtx; - Account issuer("broker"); - Account broker("issuer"); - Account dest("destination"); + Account const issuer("broker"); + Account const broker("issuer"); + Account const dest("destination"); enum MPTState { RequireAuth, diff --git a/src/test/app/Loan_test.cpp b/src/test/app/Loan_test.cpp index 05123c11c0..bf46f886bd 100644 --- a/src/test/app/Loan_test.cpp +++ b/src/test/app/Loan_test.cpp @@ -886,7 +886,7 @@ protected: auto const borrowerInitialBalance = env.balance(borrower, broker.asset).number(); auto const initialState = state; - detail::PaymentComponents totalPaid{ + xrpl::detail::PaymentComponents totalPaid{ .trackedValueDelta = 0, .trackedPrincipalDelta = 0, .trackedManagementFeeDelta = 0}; Number totalInterestPaid = 0; Number totalFeesPaid = 0; @@ -921,7 +921,7 @@ protected: { validateBorrowerBalance(); // Compute the expected principal amount - auto const paymentComponents = detail::computePaymentComponents( + auto const paymentComponents = xrpl::detail::computePaymentComponents( broker.asset.raw(), state.loanScale, state.totalValue, @@ -934,7 +934,7 @@ protected: BEAST_EXPECT( paymentComponents.trackedValueDelta <= roundedPeriodicPayment || - (paymentComponents.specialCase == detail::PaymentSpecialCase::final && + (paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final && paymentComponents.trackedValueDelta >= roundedPeriodicPayment)); BEAST_EXPECT( paymentComponents.trackedValueDelta == @@ -946,11 +946,11 @@ protected: periodicRate, state.paymentRemaining - 1, broker.params.managementFeeRate); - detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; + xrpl::detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; BEAST_EXPECT( deltas.total() == deltas.principal + deltas.interest + deltas.managementFee); BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || deltas.total() == state.periodicPayment || (state.loanScale - (deltas.total() - state.periodicPayment).exponent()) > 14); @@ -963,9 +963,9 @@ protected: << paymentComponents.trackedPrincipalDelta << ", " << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta << ", " << [&]() -> char const* { - if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == ::xrpl::detail::PaymentSpecialCase::final) return "final"; - if (paymentComponents.specialCase == detail::PaymentSpecialCase::extra) + if (paymentComponents.specialCase == ::xrpl::detail::PaymentSpecialCase::extra) return "extra"; return "none"; }() << std::endl; @@ -984,7 +984,7 @@ protected: // IOUs, the difference should be dust. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || diff == beast::zero || (diff > beast::zero && ((broker.asset.integral() && (static_cast(diff) < 3)) || @@ -994,7 +994,7 @@ protected: paymentComponents.trackedPrincipalDelta >= beast::zero && paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase != detail::PaymentSpecialCase::final || + paymentComponents.specialCase != xrpl::detail::PaymentSpecialCase::final || paymentComponents.trackedPrincipalDelta == state.principalOutstanding); } @@ -1054,7 +1054,7 @@ protected: --state.paymentRemaining; state.previousPaymentDate = state.nextPaymentDate; - if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final) { state.paymentRemaining = 0; state.nextPaymentDate = 0; @@ -2496,7 +2496,7 @@ protected: Number::upward)); auto const initialState = state; - detail::PaymentComponents totalPaid{ + xrpl::detail::PaymentComponents totalPaid{ .trackedValueDelta = 0, .trackedPrincipalDelta = 0, .trackedManagementFeeDelta = 0}; @@ -2512,7 +2512,7 @@ protected: while (state.paymentRemaining > 0) { // Compute the expected principal amount - auto const paymentComponents = detail::computePaymentComponents( + auto const paymentComponents = xrpl::detail::computePaymentComponents( broker.asset.raw(), state.loanScale, state.totalValue, @@ -2524,7 +2524,7 @@ protected: broker.params.managementFeeRate); BEAST_EXPECTS( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || paymentComponents.trackedValueDelta <= roundedPeriodicPayment, "Delta: " + to_string(paymentComponents.trackedValueDelta) + ", periodic payment: " + to_string(roundedPeriodicPayment)); @@ -2534,7 +2534,7 @@ protected: periodicRate, state.paymentRemaining - 1, broker.params.managementFeeRate); - detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; + xrpl::detail::LoanStateDeltas const deltas = currentTrueState - nextTrueState; testcase << currencyLabel << " Payment components: " << state.paymentRemaining << ", " << deltas.interest << ", " << deltas.principal << ", " @@ -2543,9 +2543,11 @@ protected: << paymentComponents.trackedInterestPart() << ", " << paymentComponents.trackedManagementFeeDelta << ", " << [&]() -> char const* { - if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == + ::xrpl::detail::PaymentSpecialCase::final) return "final"; - if (paymentComponents.specialCase == detail::PaymentSpecialCase::extra) + if (paymentComponents.specialCase == + ::xrpl::detail::PaymentSpecialCase::extra) return "extra"; return "none"; }(); @@ -2561,7 +2563,7 @@ protected: // IOUs, the difference should be after the 8th digit. Number const diff = totalDue - totalDueAmount; BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || diff == beast::zero || (diff > beast::zero && ((broker.asset.integral() && (static_cast(diff) < 3)) || @@ -2573,7 +2575,7 @@ protected: paymentComponents.trackedInterestPart() + paymentComponents.trackedManagementFeeDelta); BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || paymentComponents.trackedValueDelta <= roundedPeriodicPayment); BEAST_EXPECT( @@ -2588,10 +2590,10 @@ protected: paymentComponents.trackedPrincipalDelta >= beast::zero && paymentComponents.trackedPrincipalDelta <= state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase != detail::PaymentSpecialCase::final || + paymentComponents.specialCase != xrpl::detail::PaymentSpecialCase::final || paymentComponents.trackedPrincipalDelta == state.principalOutstanding); BEAST_EXPECT( - paymentComponents.specialCase == detail::PaymentSpecialCase::final || + paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final || (state.periodicPayment.exponent() - (deltas.principal + deltas.interest + deltas.managementFee - state.periodicPayment) @@ -2629,7 +2631,7 @@ protected: --state.paymentRemaining; state.previousPaymentDate = state.nextPaymentDate; - if (paymentComponents.specialCase == detail::PaymentSpecialCase::final) + if (paymentComponents.specialCase == xrpl::detail::PaymentSpecialCase::final) { state.paymentRemaining = 0; state.nextPaymentDate = 0; @@ -5244,13 +5246,13 @@ protected: } void - testCoverDepositWithdrawNonTransferableMPT() + testCoverDepositWithdrawNonTransferableMPT(FeatureBitset feature) { testcase("CoverDeposit and CoverWithdraw reject MPT without CanTransfer"); using namespace jtx; using namespace loanBroker; - Env env(*this, all); + Env env(*this, feature); Account const issuer{"issuer"}; Account const alice{"alice"}; @@ -5292,7 +5294,8 @@ protected: env.close(); // Standard Payment path should forbid third-party transfers. - env(pay(alice, pseudoAccount, asset(1)), ter(tecNO_AUTH)); + auto const err = feature[featureMPTokensV2] ? tecNO_PERMISSION : tecNO_AUTH; + env(pay(alice, pseudoAccount, asset(1)), ter(err)); env.close(); // Cover cannot be transferred to broker account @@ -5656,7 +5659,7 @@ protected: // Compute a regular periodic due and pay it early (before next due). auto state = getCurrentState(env, broker, loanKeylet); Number const periodicRate = loanPeriodicRate(state.interestRate, state.paymentInterval); - auto const components = detail::computePaymentComponents( + auto const components = xrpl::detail::computePaymentComponents( asset.raw(), state.loanScale, state.totalValue, @@ -5689,7 +5692,7 @@ protected: // Accrued + prepayment-penalty interest based on current periodic // schedule auto const fullPaymentInterest = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment( + xrpl::detail::loanPrincipalFromPeriodicPayment( after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), @@ -5722,7 +5725,7 @@ protected: // window by clamping prevPaymentDate to 'now' for the full-pay path. auto const prevClamped = std::min(after.previousPaymentDate, nowSecs); auto const fullPaymentInterestClamped = computeFullPaymentInterest( - detail::loanPrincipalFromPeriodicPayment( + xrpl::detail::loanPrincipalFromPeriodicPayment( after.periodicPayment, periodicRate2, after.paymentRemaining), periodicRate2, env.current()->parentCloseTime(), @@ -7006,7 +7009,9 @@ public: #endif testInvalidLoanSet(); - testCoverDepositWithdrawNonTransferableMPT(); + auto const all = jtx::testable_amendments(); + testCoverDepositWithdrawNonTransferableMPT(all); + testCoverDepositWithdrawNonTransferableMPT(all - featureMPTokensV2); testPoC_UnsignedUnderflowOnFullPayAfterEarlyPeriodic(); testDisabled(); diff --git a/src/test/app/MPToken_test.cpp b/src/test/app/MPToken_test.cpp index b7f1d22aa7..69dd397210 100644 --- a/src/test/app/MPToken_test.cpp +++ b/src/test/app/MPToken_test.cpp @@ -1,16 +1,23 @@ #include +#include +#include +#include +#include #include +#include #include #include #include #include #include +#include #include #include #include #include #include +#include namespace xrpl { namespace test { @@ -27,7 +34,7 @@ class MPToken_test : public beast::unit_test::suite // test preflight of MPTokenIssuanceCreate { // If the MPT amendment is not enabled, you should not be able to - // create MPTokenIssuances + // create MPTokenIssuance Env env{*this, features - featureMPTokensV1}; MPTTester mptAlice(env, alice); @@ -817,6 +824,7 @@ class MPToken_test : public beast::unit_test::suite Account const alice("alice"); // issuer Account const bob("bob"); // holder Account const carol("carol"); // holder + auto const MPTokensV2 = features[featureMPTokensV2]; // preflight validation @@ -863,8 +871,10 @@ class MPToken_test : public beast::unit_test::suite mptAlice.authorize({.account = bob}); - for (auto flags : {tfNoRippleDirect, tfLimitQuality}) - env(pay(alice, bob, MPT(10)), txflags(flags), ter(temINVALID_FLAG)); + auto err = !features[featureMPTokensV2] ? ter(temINVALID_FLAG) : ter(temRIPPLE_EMPTY); + env(pay(alice, bob, MPT(10)), txflags(tfNoRippleDirect), err); + err = !features[featureMPTokensV2] ? ter(temINVALID_FLAG) : ter(tesSUCCESS); + env(pay(alice, bob, MPT(10)), txflags(tfLimitQuality), err); } // Invalid combination of send, sendMax, deliverMin, paths @@ -875,31 +885,37 @@ class MPToken_test : public beast::unit_test::suite MPTTester mptAlice(env, alice, {.holders = {carol}}); - mptAlice.create({.ownerCount = 1, .holderCount = 0}); + mptAlice.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); mptAlice.authorize({.account = carol}); // sendMax and DeliverMin are valid XRP amount, // but is invalid combination with MPT amount auto const MPT = mptAlice["MPT"]; - env(pay(alice, carol, MPT(100)), sendmax(XRP(100)), ter(temMALFORMED)); + auto err = !MPTokensV2 ? ter(temMALFORMED) : ter(tecPATH_PARTIAL); + env(pay(alice, carol, MPT(100)), sendmax(XRP(100)), err); env(pay(alice, carol, MPT(100)), deliver_min(XRP(100)), ter(temBAD_AMOUNT)); // sendMax MPT is invalid with IOU or XRP auto const USD = alice["USD"]; - env(pay(alice, carol, USD(100)), sendmax(MPT(100)), ter(temMALFORMED)); - env(pay(alice, carol, XRP(100)), sendmax(MPT(100)), ter(temMALFORMED)); + err = !MPTokensV2 ? ter(temMALFORMED) : ter(tecPATH_DRY); + env(pay(alice, carol, USD(100)), sendmax(MPT(100)), err); + err = !MPTokensV2 ? ter(temMALFORMED) : ter(tecPATH_PARTIAL); + env(pay(alice, carol, XRP(100)), sendmax(MPT(100)), err); env(pay(alice, carol, USD(100)), deliver_min(MPT(100)), ter(temBAD_AMOUNT)); env(pay(alice, carol, XRP(100)), deliver_min(MPT(100)), ter(temBAD_AMOUNT)); // sendmax and amount are different MPT issue test::jtx::MPT const MPT1("MPT", makeMptID(env.seq(alice) + 10, alice)); - env(pay(alice, carol, MPT1(100)), sendmax(MPT(100)), ter(temMALFORMED)); - // paths is invalid - env(pay(alice, carol, MPT(100)), path(~USD), ter(temMALFORMED)); + err = !MPTokensV2 ? ter(temMALFORMED) : ter(tecOBJECT_NOT_FOUND); + env(pay(alice, carol, MPT1(100)), sendmax(MPT(100)), err); + // "paths" is invalid in V1 + err = !MPTokensV2 ? ter(temMALFORMED) : ter(tesSUCCESS); + env(pay(alice, carol, MPT(100)), path(~USD), err); } // build_path is invalid if MPT { - Env env{*this, features}; + Env env{*this, features - featureMPTokensV2}; Account const alice("alice"); Account const carol("carol"); @@ -1042,7 +1058,7 @@ class MPToken_test : public beast::unit_test::suite env(credentials::accept(bob, credIssuer1, credType)); env.close(); - MPTTester mptAlice(env, alice); + MPTTester mptAlice(env, alice, MPTInit{}); env.close(); mptAlice.create({ @@ -1084,7 +1100,7 @@ class MPToken_test : public beast::unit_test::suite env(credentials::accept(bob, credIssuer1, credType)); env.close(); - MPTTester mptAlice(env, alice); + MPTTester mptAlice(env, alice, MPTInit{}); env.close(); mptAlice.create({ @@ -1161,7 +1177,7 @@ class MPToken_test : public beast::unit_test::suite env(credentials::accept(carol, credIssuer2, credType)); env.close(); - MPTTester mptAlice(env, alice); + MPTTester mptAlice(env, alice, MPTInit{}); env.close(); mptAlice.create({ @@ -1288,11 +1304,14 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 100); mptAlice.pay(alice, carol, 100); + auto const err = + env.current()->rules().enabled(featureMPTokensV2) ? tecPATH_DRY : tecLOCKED; + // Global lock mptAlice.set({.account = alice, .flags = tfMPTLock}); // Can't send between holders - mptAlice.pay(bob, carol, 1, tecLOCKED); - mptAlice.pay(carol, bob, 2, tecLOCKED); + mptAlice.pay(bob, carol, 1, err); + mptAlice.pay(carol, bob, 2, err); // Issuer can send mptAlice.pay(alice, bob, 3); // Holder can send back to issuer @@ -1303,8 +1322,8 @@ class MPToken_test : public beast::unit_test::suite // Individual lock mptAlice.set({.account = alice, .holder = bob, .flags = tfMPTLock}); // Can't send between holders - mptAlice.pay(bob, carol, 5, tecLOCKED); - mptAlice.pay(carol, bob, 6, tecLOCKED); + mptAlice.pay(bob, carol, 5, err); + mptAlice.pay(carol, bob, 6, err); // Issuer can send mptAlice.pay(alice, bob, 7); // Holder can send back to issuer @@ -1357,10 +1376,13 @@ class MPToken_test : public beast::unit_test::suite // Payment succeeds if partial payment even if // SendMax is less than deliver amount env(pay(bob, carol, MPT(100)), sendmax(MPT(90)), txflags(tfPartialPayment)); - // 82 to carol, 8 to issuer (90 / 1.1 ~ 81.81 (rounded to nearest) = - // 82) + // 82 to carol, 8 to issuer (90 / 1.1 ~ 81.81 (rounded to nearest in + // v1) = 82) BEAST_EXPECT(mptAlice.checkMPTokenAmount(bob, 690)); - BEAST_EXPECT(mptAlice.checkMPTokenAmount(carol, 282)); + // In V2 the payments are executed via the payment engine and + // the rounding results in a higher quality trade + BEAST_EXPECT( + mptAlice.checkMPTokenAmount(carol, !features[featureMPTokensV2] ? 282 : 281)); } // Insufficient SendMax with no transfer fee @@ -1432,7 +1454,8 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, 100); // issuer tries to exceed max amount - mptAlice.pay(alice, bob, 1, tecPATH_PARTIAL); + auto const err = MPTokensV2 ? tecPATH_DRY : tecPATH_PARTIAL; + mptAlice.pay(alice, bob, 1, err); } // Issuer fails trying to send more than the default maximum @@ -1450,7 +1473,8 @@ class MPToken_test : public beast::unit_test::suite mptAlice.pay(alice, bob, maxMPTokenAmount); // issuer tries to exceed max amount - mptAlice.pay(alice, bob, 1, tecPATH_PARTIAL); + auto const err = MPTokensV2 ? tecPATH_DRY : tecPATH_PARTIAL; + mptAlice.pay(alice, bob, 1, err); } // Pay more than max amount fails in the json parser before @@ -1490,6 +1514,7 @@ class MPToken_test : public beast::unit_test::suite // payment between the holders env(pay(bob, carol, MPT(10'000)), sendmax(MPT(10'000)), txflags(tfPartialPayment)); + // Verify the metadata auto const meta = env.meta()->getJson(JsonOptions::none)[sfAffectedNodes.fieldName]; // Issuer got 10 in the transfer fees @@ -1509,7 +1534,8 @@ class MPToken_test : public beast::unit_test::suite // payment between the holders fails without // partial payment - env(pay(bob, carol, MPT(10'000)), sendmax(MPT(10'000)), ter(tecPATH_PARTIAL)); + auto const err = MPTokensV2 ? tecPATH_DRY : tecPATH_PARTIAL; + env(pay(bob, carol, MPT(10'000)), sendmax(MPT(10'000)), ter(err)); } // Pay maximum allowed amount @@ -1565,7 +1591,9 @@ class MPToken_test : public beast::unit_test::suite env.fund(XRP(1'000), alice, bob); STAmount const mpt{MPTID{0}, 100}; - env(pay(alice, bob, mpt), ter(tecOBJECT_NOT_FOUND)); + auto const err = + !features[featureMPTokensV2] ? ter(tecOBJECT_NOT_FOUND) : ter(temBAD_CURRENCY); + env(pay(alice, bob, mpt), err); } // Issuer fails trying to send to an account, which doesn't own MPT for @@ -1834,7 +1862,6 @@ class MPToken_test : public beast::unit_test::suite jrr = env.rpc("json", "sign", to_string(jv1)); BEAST_EXPECT(jrr[jss::result][jss::error] == "invalidParams"); }; - auto toSFieldRef = [](SField const& field) { return std::ref(field); }; auto setMPTFields = [&](SField const& field, Json::Value& jv, bool withAmount = true) { jv[jss::Asset] = to_json(xrpIssue()); jv[jss::Asset2] = to_json(USD.issue()); @@ -1857,22 +1884,6 @@ class MPToken_test : public beast::unit_test::suite // Transactions with amount fields, which can't be MPT. // Transactions with issue fields, which can't be MPT. - // AMMCreate - auto ammCreate = [&](SField const& field) { - Json::Value jv; - jv[jss::TransactionType] = jss::AMMCreate; - jv[jss::Account] = alice.human(); - jv[jss::Amount] = (field.fieldName == sfAmount.fieldName) - ? mpt.getJson(JsonOptions::none) - : "100000000"; - jv[jss::Amount2] = (field.fieldName == sfAmount2.fieldName) - ? mpt.getJson(JsonOptions::none) - : "100000000"; - jv[jss::TradingFee] = 0; - test(jv, field.fieldName); - }; - ammCreate(sfAmount); - ammCreate(sfAmount2); // AMMDeposit auto ammDeposit = [&](SField const& field) { Json::Value jv; @@ -1882,13 +1893,7 @@ class MPToken_test : public beast::unit_test::suite setMPTFields(field, jv); test(jv, field.fieldName); }; - for (SField const& field : - {toSFieldRef(sfAmount), - toSFieldRef(sfAmount2), - toSFieldRef(sfEPrice), - toSFieldRef(sfLPTokenOut), - toSFieldRef(sfAsset), - toSFieldRef(sfAsset2)}) + for (SField const& field : {std::ref(sfEPrice), std::ref(sfLPTokenOut)}) ammDeposit(field); // AMMWithdraw auto ammWithdraw = [&](SField const& field) { @@ -1899,13 +1904,7 @@ class MPToken_test : public beast::unit_test::suite setMPTFields(field, jv); test(jv, field.fieldName); }; - ammWithdraw(sfAmount); - for (SField const& field : - {toSFieldRef(sfAmount2), - toSFieldRef(sfEPrice), - toSFieldRef(sfLPTokenIn), - toSFieldRef(sfAsset), - toSFieldRef(sfAsset2)}) + for (SField const& field : {std::ref(sfEPrice), std::ref(sfLPTokenIn)}) ammWithdraw(field); // AMMBid auto ammBid = [&](SField const& field) { @@ -1915,72 +1914,8 @@ class MPToken_test : public beast::unit_test::suite setMPTFields(field, jv); test(jv, field.fieldName); }; - for (SField const& field : - {toSFieldRef(sfBidMin), - toSFieldRef(sfBidMax), - toSFieldRef(sfAsset), - toSFieldRef(sfAsset2)}) - ammBid(field); - // AMMClawback - auto ammClawback = [&](SField const& field) { - Json::Value jv; - jv[jss::TransactionType] = jss::AMMClawback; - jv[jss::Account] = alice.human(); - jv[jss::Holder] = carol.human(); - setMPTFields(field, jv); - test(jv, field.fieldName); - }; - for (SField const& field : - {toSFieldRef(sfAmount), toSFieldRef(sfAsset), toSFieldRef(sfAsset2)}) - ammClawback(field); - // AMMDelete - auto ammDelete = [&](SField const& field) { - Json::Value jv; - jv[jss::TransactionType] = jss::AMMDelete; - jv[jss::Account] = alice.human(); - setMPTFields(field, jv, false); - test(jv, field.fieldName); - }; - ammDelete(sfAsset); - ammDelete(sfAsset2); - // AMMVote - auto ammVote = [&](SField const& field) { - Json::Value jv; - jv[jss::TransactionType] = jss::AMMVote; - jv[jss::Account] = alice.human(); - jv[jss::TradingFee] = 100; - setMPTFields(field, jv, false); - test(jv, field.fieldName); - }; - ammVote(sfAsset); - ammVote(sfAsset2); - // CheckCash - auto checkCash = [&](SField const& field) { - Json::Value jv; - jv[jss::TransactionType] = jss::CheckCash; - jv[jss::Account] = alice.human(); - jv[sfCheckID.fieldName] = to_string(uint256{1}); - jv[field.fieldName] = mpt.getJson(JsonOptions::none); - test(jv, field.fieldName); - }; - checkCash(sfAmount); - checkCash(sfDeliverMin); - // CheckCreate - { - Json::Value jv; - jv[jss::TransactionType] = jss::CheckCreate; - jv[jss::Account] = alice.human(); - jv[jss::Destination] = carol.human(); - jv[jss::SendMax] = mpt.getJson(JsonOptions::none); - test(jv, jss::SendMax.c_str()); - } - // OfferCreate - { - Json::Value jv = offer(alice, USD(100), mpt); - test(jv, jss::TakerPays.c_str()); - jv = offer(alice, mpt, USD(100)); - test(jv, jss::TakerGets.c_str()); - } + ammBid(sfBidMin); + ammBid(sfBidMax); // PaymentChannelCreate { Json::Value jv; @@ -3198,7 +3133,19 @@ class MPToken_test : public beast::unit_test::suite BEAST_EXPECT(mptAlice.isTransferFeePresent()); // Bob can pay carol - mptAlice.pay(bob, carol, 50); + MPT const MPTC = mptAlice; + if (!features[featureMPTokensV2]) + { + mptAlice.pay(bob, carol, 50); + BEAST_EXPECT(env.balance(carol, MPTC) == MPTC(50)); + } + else + { + // The difference is due to the rounding in MPT/DEX. + // 1 MPTC is the transfer fee paid by bob to the issuer. + env(pay(bob, carol, mptAlice(50)), txflags(tfPartialPayment)); + BEAST_EXPECT(env.balance(carol, MPTC) == MPTC(49)); + } // Alice clears MPTCanTransfer mptAlice.set({.account = alice, .mutableFlags = tmfMPTClearCanTransfer}); @@ -3390,6 +3337,3286 @@ class MPToken_test : public beast::unit_test::suite } } + void + testOfferCrossing(FeatureBitset features) + { + testcase("Offer Crossing"); + using namespace test::jtx; + Account const gw = Account("gw"); + Account const alice = Account("alice"); + Account const carol = Account("carol"); + auto const USD = gw["USD"]; + + // Blocking flags + for (auto flags : + {tfMPTCanTrade | tfMPTCanLock | tfMPTCanClawback, // global lock - holder, issuer fail + tfMPTCanTrade | tfMPTRequireAuth, // not authorized - holder fails + tfMPTCanTrade, // holder, issuer succeed + tfMPTCanTrade | tfMPTCanLock, // local lock - holder fails + tfMPTCanTransfer}) // can't trade - holder, issuer fail + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice); + env.close(); + + // Use CanClawback flag to distinguish global from local lock + bool const lockMPToken = (flags & (tfMPTCanLock | tfMPTCanClawback)) == tfMPTCanLock; + bool const lockMPTIssue = + (flags & (tfMPTCanLock | tfMPTCanClawback)) == (tfMPTCanLock | tfMPTCanClawback); + bool const requireAuth = (flags & tfMPTRequireAuth) != 0u; + + auto mpt = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 1'000, + .flags = flags, + .authHolder = true}); + MPT const BTC = mpt; + + if (requireAuth) + mpt.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + if (lockMPToken) + { + mpt.set({.holder = alice, .flags = tfMPTLock}); + } + else if (lockMPTIssue) + { + mpt.set({.flags = tfMPTLock}); + } + + auto testOffer = + [&](Account const& account, auto const& buy, auto const& sell, bool buyUSD) { + auto error = [&](auto const err) -> TER { + if (account == gw) + return tesSUCCESS; + return err; + }; + auto const [errBuy, errSell] = [&]() -> std::pair { + // Global lock + if (lockMPTIssue) + return std::make_pair(tecFROZEN, tecFROZEN); + // Local lock + if (lockMPToken) + return std::make_pair(tesSUCCESS, error(tecUNFUNDED_OFFER)); + // MPToken doesn't exist + if (requireAuth) + return std::make_pair(error(tecNO_AUTH), error(tecUNFUNDED_OFFER)); + if (flags & tfMPTCanTransfer) + return std::make_pair(tecNO_PERMISSION, tecNO_PERMISSION); + return std::make_pair(tesSUCCESS, tesSUCCESS); + }(); + + auto const err = buyUSD ? errBuy : errSell; + + auto seq(env.seq(account)); + env(offer(account, buy(10), sell(10)), ter(err)); + env(offer_cancel(account, seq)); + env.close(); + }; + + auto testOffers = [&](Account const& account) { + testOffer(account, XRP, BTC, false); + testOffer(account, BTC, XRP, true); + }; + testOffers(alice); + testOffers(gw); + } + + // MPTokenV2 is disabled + { + Env env{*this, features - featureMPTokensV2}; + + MPTTester mpt(env, gw, {.holders = {alice}}); + + mpt.create({.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer}); + + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 200); + + env(offer(alice, XRP(100), mpt.mpt(101)), ter(temDISABLED)); + env.close(); + } + + // MPTokenIssuance object doesn't exist + { + Env env(*this); + env.fund(XRP(1'000), gw, alice); + env.close(); + MPT const BTC = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 100}); + MPT const ETH = MPT(gw, 1); + + env(offer(alice, ETH(10), BTC(10)), ter(tecOBJECT_NOT_FOUND)); + env(offer(alice, BTC(10), ETH(10)), ter(tecUNFUNDED_OFFER)); + } + + // MPToken object doesn't exist and the account is not the issuer of MPT + { + Env env(*this); + env.fund(XRP(1'000), gw, alice); + MPTTester const BTC({.env = env, .issuer = gw, .holders = {alice}, .pay = 100}); + MPTTester const ETH({.env = env, .issuer = gw}); + + env(offer(alice, ETH(10), BTC(10))); + env(offer(alice, BTC(10), ETH(10)), ter(tecUNFUNDED_OFFER)); + } + + // MPTLock flag is set and the account is not the issuer of MPT + { + Account const bob = Account("bob"); + Account const dan = Account("dan"); + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob, dan); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob, dan}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob, dan}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + + env(offer(bob, ETH(10), BTC(10)), txflags(tfPassive)); + env(offer(dan, BTC(10), ETH(10)), txflags(tfPassive)); + + auto test = [&](auto const& flag, bool gwOwner = false) { + BTC.set({.holder = carol, .flags = flag}); + BTC.set({.holder = alice, .flags = flag}); + + if (gwOwner) + { + // Succeeds if the account is the issuer + env(offer(gw, ETH(1), BTC(1))); + env(offer(gw, BTC(1), ETH(1))); + } + else + { + auto const err = flag == tfMPTLock ? ter(tecUNFUNDED_OFFER) : ter(tesSUCCESS); + env(offer(alice, ETH(1), BTC(1)), err); + // Offer created by not crossed + env(offer(carol, BTC(1), ETH(1))); + BEAST_EXPECT(expectOffers(env, carol, 1, {{BTC(1), ETH(1)}})); + } + }; + + test(tfMPTLock); + test(tfMPTLock, true); + test(tfMPTUnlock); + } + + // MPTRequireAuth flag is set and the account is not authorized + { + Env env(*this); + env.fund(XRP(1'000), gw, alice); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 100, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 100, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + + BTC.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + + env(offer(alice, ETH(10), BTC(10)), ter(tecUNFUNDED_OFFER)); + + // issuer can create + + env(offer(gw, ETH(10), BTC(10))); + env.close(); + } + + // MPTCanTransfer is not set and the account is not the issuer of MPT + { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = tfMPTCanTrade, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = tfMPTCanTrade | tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + + // Can create + env(offer(alice, ETH(10), BTC(10)), txflags(tfPassive)); + BTC.set({.mutableFlags = tmfMPTSetCanTransfer}); + ETH.set({.mutableFlags = tmfMPTClearCanTransfer}); + env(offer(alice, ETH(10), BTC(10)), txflags(tfPassive)); + BEAST_EXPECT(getAccountOffers(env, alice)[jss::offers].size() == 2); + + // issuer can create + env(offer(gw, ETH(10), BTC(10)), txflags(tfPassive)); + env.close(); + + // can cross issuer's offer, other offers are removed + env(offer(carol, BTC(10), ETH(10))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, gw, 0)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + // can't cross holder's offer, holder's offer is removed + env(offer(alice, ETH(10), BTC(10)), txflags(tfPassive)); + env(offer(carol, BTC(10), ETH(10))); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, carol, 1)); + } + + // MPTCanTrade is disabled + { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol); + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTrade}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = tfMPTCanTrade, + .mutableFlags = tmfMPTCanMutateCanTrade}); + + // Can't create + env(offer(gw, ETH(10), BTC(10)), ter(tecNO_PERMISSION)); + env.close(); + } + + // XRP/MPT + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice, carol}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 200); + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + env(offer(alice, XRP(100), MPT(101))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{XRP(100), MPT(101)}}})); + + env(offer(carol, MPT(101), XRP(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 99)); + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 301)); + } + + // IOU/MPT + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice, carol}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + env(trust(alice, USD(2'000))); + env(pay(gw, alice, USD(1'000))); + env.close(); + + env(trust(carol, USD(2'000))); + env(pay(gw, carol, USD(1'000))); + env.close(); + + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 200); + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + env(offer(alice, USD(100), MPT(101))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{USD(100), MPT(101)}}})); + + env(offer(carol, MPT(101), USD(100))); + env.close(); + + BEAST_EXPECT(env.balance(alice, USD) == USD(1'100)); + BEAST_EXPECT(env.balance(carol, USD) == USD(900)); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 99)); + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 301)); + } + + // MPT/MPT + { + Env env{*this, features}; + + MPTTester mpt1(env, gw, {.holders = {alice, carol}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + + MPTTester mpt2(env, gw, {.holders = {alice, carol}, .fund = false}); + mpt2.create( + {.ownerCount = 2, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT2"]; + + mpt1.authorize({.account = alice}); + mpt1.authorize({.account = carol}); + mpt1.pay(gw, alice, 200); + mpt1.pay(gw, carol, 200); + + mpt2.authorize({.account = alice}); + mpt2.authorize({.account = carol}); + mpt2.pay(gw, alice, 200); + mpt2.pay(gw, carol, 200); + + env(offer(alice, MPT2(100), MPT1(101))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{MPT2(100), MPT1(101)}}})); + + env(offer(carol, MPT1(101), MPT2(100))); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, carol, 0)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 99)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(carol, 301)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 300)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 100)); + } + } + + void + testCrossAssetPayment(FeatureBitset features) + { + testcase("Cross Asset Payment"); + using namespace test::jtx; + Account const gw = Account("gw"); + Account const alice = Account("alice"); + Account const carol = Account("carol"); + Account const bob = Account("bob"); + auto const USD = gw["USD"]; + + // Loop + { + Env env{*this, features}; + MPTTester mpt(env, gw, {.holders = {carol, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + mpt.authorize({.account = bob}); + + // holder to holder + env(pay(carol, bob, MPT(1)), + test::jtx::path(~MPT, ~USD, ~MPT), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH_LOOP)); + env.close(); + + // issuer to holder + env(pay(gw, bob, MPT(1)), + test::jtx::path(~MPT, ~USD, ~MPT), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH_LOOP)); + env.close(); + + // holder to issuer + env(pay(bob, gw, MPT(1)), + test::jtx::path(~MPT, ~USD, ~MPT), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH_LOOP)); + env.close(); + } + + // Rippling + { + Env env{*this, features}; + MPTTester mpt(env, gw, {.holders = {carol, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + mpt.authorize({.account = bob}); + + // holder to holder + env(pay(carol, bob, MPT(1)), + test::jtx::path(~MPT, gw), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH)); + env.close(); + + // issuer to holder + env(pay(gw, bob, MPT(1)), + test::jtx::path(~MPT, carol), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH)); + env.close(); + + // holder to issuer + env(pay(bob, gw, MPT(1)), + test::jtx::path(~MPT, carol), + sendmax(XRP(1)), + txflags(tfPartialPayment), + ter(temBAD_PATH)); + env.close(); + } + + // MPTokenV2 is disabled + { + Env env{*this, features - featureMPTokensV2}; + + MPTTester mpt(env, gw, {.holders = {alice}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + + env(pay(gw, alice, MPT(101)), + test::jtx::path(~MPT), + sendmax(XRP(100)), + txflags(tfPartialPayment), + ter(temMALFORMED)); + } + + { + auto const ed = Account{"ed"}; + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol, bob, ed); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanLock | MPTDEXFlags, + .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTrade | + tmfMPTCanMutateCanTransfer}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanLock | MPTDEXFlags, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = MPTDEXFlags | tfMPTCanLock, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester const CAD( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = MPTDEXFlags | tfMPTCanLock, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + + env(offer(bob, ETH(1'000), BTC(1'000)), txflags(tfPassive)); + env.close(); + env(offer(bob, BTC(1'000), ETH(1'000)), txflags(tfPassive)); + env.close(); + + // MPTokenIssuance doesn't exist + + env(pay(alice, carol, MPT(gw, 1'000)(10)), sendmax(ETH(10)), ter(tecOBJECT_NOT_FOUND)); + env.close(); + env(pay(alice, carol, ETH(10)), sendmax(MPT(gw)(10)), ter(tecOBJECT_NOT_FOUND)); + env.close(); + + // MPToken object doesn't exist + + // holder and issuer fail + env(pay(ed, carol, BTC(10)), sendmax(ETH(10)), ter(tecNO_AUTH)); + env(pay(carol, ed, BTC(10)), sendmax(ETH(10)), ter(tecNO_AUTH)); + env(pay(ed, gw, BTC(10)), sendmax(ETH(10)), ter(tecNO_AUTH)); + env(pay(gw, ed, BTC(10)), sendmax(ETH(10)), ter(tecNO_AUTH)); + env.close(); + + // MPTRequireAuth is set + + BTC.authorize({.account = ed}); + ETH.authorize({.account = ed}); + env(pay(gw, ed, ETH(100))); + env(pay(gw, ed, BTC(100))); + env.close(); + BTC.set({.mutableFlags = tmfMPTSetRequireAuth}); + // authorize bob to enable the offers trading + BTC.authorize({.account = gw, .holder = bob}); + env.close(); + env(pay(ed, carol, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecNO_AUTH)); + env(pay(carol, ed, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecNO_AUTH)); + // BTC is transferred from bob to ed, ed is not authorized + env(pay(gw, ed, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecNO_AUTH)); + // BTC is transferred from bob to issuer + env(pay(ed, gw, BTC(10)), path(~BTC), sendmax(ETH(10))); + // BTC is transferred from issuer to bob + env(pay(gw, ed, ETH(10)), path(~ETH), sendmax(BTC(10))); + // BTC is transferred from ed to bob, ed is not authorized + env(pay(ed, gw, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tecNO_AUTH)); + env.close(); + BTC.set({.mutableFlags = tmfMPTClearRequireAuth}); + + // MPTCanTransfer is not set + + // Fail regardless if source/destination is the issuer or + // not since the offer is owned by a holder. + BTC.set({.mutableFlags = tmfMPTClearCanTransfer}); + env(pay(ed, carol, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecPATH_PARTIAL)); + env(pay(carol, ed, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecPATH_PARTIAL)); + env(pay(ed, carol, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tecPATH_PARTIAL)); + env(pay(carol, ed, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tecPATH_PARTIAL)); + // Fail because BTC, which has CanTransfer disabled, is sent to + // bob + env(pay(ed, gw, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tecPATH_PARTIAL)); + env(pay(ed, gw, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tesSUCCESS)); + env(pay(gw, ed, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tesSUCCESS)); + // Fail because BTC, which has CanTransfer disabled, is sent to + // ed + env(pay(gw, ed, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tecPATH_PARTIAL)); + env.close(); + env(offer(gw, ETH(100), BTC(100)), txflags(tfPassive)); + env.close(); + env(offer(gw, BTC(100), ETH(100)), txflags(tfPassive)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 2)); + env(pay(ed, carol, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tesSUCCESS)); + env(pay(ed, carol, ETH(10)), path(~ETH), sendmax(BTC(10)), ter(tesSUCCESS)); + env(pay(gw, carol, BTC(10)), path(~BTC), sendmax(ETH(10)), ter(tesSUCCESS)); + env.close(); + env(pay(ed, gw, BTC(10)), path(~BTC), sendmax(ETH(10))); + env.close(); + } + // Multiple steps: CAD/USD, USD/BTC, BTC/ETH + { + auto const ed = Account{"ed"}; + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol, bob, ed); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanLock | MPTDEXFlags, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanLock | MPTDEXFlags, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester USD( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = MPTDEXFlags | tfMPTCanLock, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + MPTTester CAD( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = MPTDEXFlags | tfMPTCanLock, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + // takerGets can transfer if: + // - CanTransfer is set + // - The offer's owner is the issuer + // - BookStep is the last step, which means strand's destination is + // the issuer + // takerPays can transfer if + // - BookStep is the first step, which means strand's source is + // the issuer + // - The offer's owner is the issuer + // - Previous step is BookStep, which transfers per above + // - CanTransfer is set + env(offer(bob, CAD(100), USD(100)), txflags(tfPassive)); + env(offer(bob, USD(100), BTC(100)), txflags(tfPassive)); + env(offer(bob, BTC(100), ETH(100)), txflags(tfPassive)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + BTC.set({.mutableFlags = tmfMPTSetCanTransfer}); + USD.set({.mutableFlags = tmfMPTClearCanTransfer}); + // TakerGets + // fail - CAD/USD is owned by bob + env(pay(alice, carol, ETH(1)), + path(~USD, ~BTC, ~ETH), + sendmax(CAD(1)), + ter(tecPATH_PARTIAL)); + auto seq(env.seq(gw)); + env(offer(gw, USD(1), BTC(1)), txflags(tfPassive)); + env.close(); + // fail - CAD/USD is owned by bob + env(pay(alice, carol, ETH(1)), + path(~USD, ~BTC, ~ETH), + sendmax(CAD(1)), + ter(tecPATH_PARTIAL)); + env.close(); + env(offer_cancel(gw, seq)); + env(offer(gw, CAD(1), USD(1)), txflags(tfPassive)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + // succeed - CAD/USD is owned by issuer + env(pay(alice, carol, ETH(1)), path(~USD, ~BTC, ~ETH), sendmax(CAD(1))); + env.close(); + // bob's CAD/USD is deleted + BEAST_EXPECT(expectOffers(env, bob, 2)); + env(offer(bob, CAD(100), USD(100)), txflags(tfPassive)); + BEAST_EXPECT(expectOffers(env, gw, 0)); + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + ETH.set({.mutableFlags = tmfMPTClearCanTransfer}); + // fail - BTC/ETH is owned by bob, destination is carol + env(pay(alice, carol, ETH(1)), + path(~USD, ~BTC, ~ETH), + sendmax(CAD(1)), + ter(tecPATH_PARTIAL)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + // succeed - destination is an issuer + env(pay(alice, gw, ETH(1)), path(~USD, ~BTC, ~ETH), sendmax(CAD(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + // TakerPays + ETH.set({.mutableFlags = tmfMPTSetCanTransfer}); + CAD.set({.mutableFlags = tmfMPTClearCanTransfer}); + // fail - CAD/USD is owned by bob, source is alice + env(pay(alice, carol, ETH(1)), + path(~USD, ~BTC, ~ETH), + sendmax(CAD(1)), + ter(tecPATH_PARTIAL)); + // succeed - source is the issuer + env(pay(gw, carol, ETH(1)), path(~USD, ~BTC, ~ETH), sendmax(CAD(1))); + env.close(); + env(offer(gw, CAD(1), USD(1)), txflags(tfPassive)); + env.close(); + // succeed - CAD/USD is owned by issuer + env(pay(alice, carol, ETH(1)), path(~USD, ~BTC, ~ETH), sendmax(CAD(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, gw, 0)); + BEAST_EXPECT(expectOffers(env, bob, 2)); + CAD.set({.mutableFlags = tmfMPTSetCanTransfer}); + BTC.set({.mutableFlags = tmfMPTClearCanTransfer}); + env(offer(bob, CAD(1), USD(1)), txflags(tfPassive)); + env(offer(gw, USD(1), BTC(1)), txflags(tfPassive)); + env.close(); + // succeed - USD/BTC is owned by issuer + env(pay(alice, carol, ETH(1)), path(~USD, ~BTC, ~ETH), sendmax(CAD(1))); + env.close(); + BEAST_EXPECT(expectOffers(env, gw, 0)); + } + + // MPTCanTrade is not set + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol, bob); + env.close(); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTrade}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanTransfer | tfMPTCanTrade, + .mutableFlags = tmfMPTCanMutateCanTrade}); + MPTTester const USD( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 1'000, + .flags = tfMPTCanTransfer | tfMPTCanTrade, + .mutableFlags = tmfMPTCanMutateCanTrade}); + + env(pay(alice, carol, ETH(1)), path(~ETH), sendmax(BTC(1)), ter(tecNO_PERMISSION)); + env(pay(alice, carol, BTC(1)), path(~BTC), sendmax(ETH(1)), ter(tecNO_PERMISSION)); + env.close(); + + BTC.set({.mutableFlags = tmfMPTSetCanTrade}); + env(offer(bob, XRP(1), BTC(1))); + env(offer(bob, BTC(1), ETH(1))); + env(offer(bob, ETH(1), USD(1))); + env.close(); + BTC.set({.mutableFlags = tmfMPTClearCanTrade}); + env(pay(gw, carol, USD(1)), + path(~BTC, ~ETH, ~USD), + sendmax(XRP(1)), + ter(tecPATH_PARTIAL)); + env.close(); + BEAST_EXPECT(expectOffers(env, bob, 3)); + } + + // Holders are locked + { + enum LockType { Global, Individual, None }; + struct TestArg + { + Account src; + Account dst; + Account offerOwner; + LockType srcFlag = None; + LockType dstFlag = None; + LockType offerFlagBuy = None; + LockType offerFlagSell = None; + LockType globalFlagBuy = None; + LockType globalFlagSell = None; + TER err = tesSUCCESS; + std::optional errIOU = std::nullopt; + }; + auto getErr = [&](Token const&, TestArg const& arg) { + if constexpr (std::is_same_v) + { + return arg.errIOU.value_or(arg.err); + } + else if constexpr (std::is_same_v) + { + return arg.err; + } + }; + auto getMPT = [&](Env& env) { + MPTTester const BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester const ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + return std::make_pair(BTC, ETH); + }; + auto getIOU = [&](Env& env) { + for (auto const& iou : {gw["BTC"], gw["ETH"]}) + { + for (auto const& a : {alice, carol, bob}) + { + env(fset(a, asfDefaultRipple)); + env.close(); + env(trust(a, iou(200))); + env(pay(gw, a, iou(100))); + env.close(); + } + } + return std::make_pair(gw["BTC"], gw["ETH"]); + }; + auto lock = [&]( + Env& env, Account const& account, Token& token, LockType lock) { + if (lock == None) + return; + if constexpr (std::is_same_v) + { + if (lock == Global) + { + env(fset(gw, asfGlobalFreeze)); + } + else + { + IOU const iou{account, token.currency}; + env(trust(gw, iou(0), tfSetFreeze)); + } + } + else if constexpr (std::is_same_v) + { + if (lock == Global) + { + token.set({.flags = tfMPTLock}); + } + else if (token.issuer() != account) + { + token.set({.holder = account, .flags = tfMPTLock}); + } + } + }; + auto test = [&](auto&& getTokens, TestArg const& arg) { + Env env(*this); + env.fund(XRP(1'000), gw, alice, carol, bob); + + auto [BTC, ETH] = getTokens(env); + + env(offer(arg.offerOwner, ETH(10), BTC(10)), txflags(tfPassive)); + env.close(); + + if (arg.globalFlagBuy != LockType::None) + { + lock(env, gw, ETH, LockType::Global); + } + else + { + lock(env, arg.offerOwner, ETH, arg.offerFlagBuy); + lock(env, arg.src, ETH, arg.srcFlag); + } + if (arg.globalFlagSell != LockType::None) + { + lock(env, gw, BTC, LockType::Global); + } + else + { + lock(env, arg.offerOwner, BTC, arg.offerFlagSell); + lock(env, arg.dst, BTC, arg.dstFlag); + } + + auto const err = getErr(ETH, arg); + env(pay(arg.src, arg.dst, BTC(1)), + path(~BTC), + txflags(tfNoRippleDirect), + sendmax(ETH(1)), + ter(err)); + env.close(); + }; + // clang-format off + std::vector const tests = { + // src, dst, offer's owner are a holder + {.src = alice, .dst = carol, .offerOwner = bob, .srcFlag = Individual, .err = tecPATH_DRY}, + // dst can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = bob, .dstFlag = Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagBuy = Global, .err = tecPATH_DRY}, + {.src = alice, .dst = carol, .offerOwner = bob, .globalFlagSell = Global, .err = tecPATH_DRY}, + // offer's owner can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagBuy = Individual, .err = + tecPATH_PARTIAL, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = bob, .offerFlagSell = Individual, .err = tecPATH_PARTIAL}, + // src, dst are a holder, offer's owner is an issuer + {.src = alice, .dst = carol, .offerOwner = gw, .srcFlag = Individual, .err = tecPATH_DRY}, + // dst can receive IOU even if the account is frozen + {.src = alice, .dst = carol, .offerOwner = gw, .dstFlag = Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagBuy = Global, .err = tecPATH_DRY}, + {.src = alice, .dst = carol, .offerOwner = gw, .globalFlagSell = Global, .err = tecPATH_DRY}, + // src is issuer, dst and offer's owner are a holder + // dst can receive IOU even if the account is frozen + {.src = gw, .dst = carol, .offerOwner = bob, .dstFlag = Individual, .err = tecPATH_DRY, .errIOU = tesSUCCESS}, + // offer's owner can receive IOU from an issuer even if takerBuys is frozen, MPT offer is unfunded in this case + {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagBuy = Individual, .err = tecPATH_PARTIAL, .errIOU = tesSUCCESS}, + {.src = gw, .dst = carol, .offerOwner = bob, .offerFlagSell = Individual, .err = tecPATH_PARTIAL}, + // dst is issuer, src and offer's owner are a holder + {.src = alice, .dst = gw, .offerOwner = bob, .srcFlag = Individual, .err = tecPATH_DRY}, + // offer's owner can receive IOU even if the account is frozen + {.src = alice, .dst = gw, .offerOwner = bob, .offerFlagBuy = Individual, .err = tecPATH_PARTIAL, + .errIOU = tesSUCCESS}, + {.src = alice, .dst = gw, .offerOwner = bob, .offerFlagSell = Individual, .err = tecPATH_PARTIAL}, + }; + // clang-format on + + for (auto const& t : tests) + { + test(getMPT, t); + test(getIOU, t); + } + } + { + Env env(*this); + auto const USD = gw["USD"]; + env.fund(XRP(1'000), gw, alice, carol, bob); + MPTTester BTC( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + MPTTester ETH( + {.env = env, + .issuer = gw, + .holders = {alice, carol, bob}, + .pay = 100, + .flags = tfMPTCanLock | MPTDEXFlags}); + + env(trust(alice, USD(100))); + env(pay(gw, alice, USD(100))); + env(trust(carol, USD(100))); + + env(offer(alice, XRP(10), ETH(10))); + env(offer(bob, ETH(10), BTC(10))); + env(offer(alice, BTC(10), USD(10))); + env.close(); + + BTC.set({.holder = bob, .flags = tfMPTLock}); + + // Bob's offer is unfunded + env(pay(alice, carol, USD(1)), + path(~(MPT)ETH, ~(MPT)BTC, ~USD), + txflags(tfNoRippleDirect | tfPartialPayment), + sendmax(XRP(1)), + ter(tecPATH_DRY)); + env.close(); + + BTC.set({.holder = bob, .flags = tfMPTUnlock}); + ETH.set({.holder = bob, .flags = tfMPTLock}); + + env(pay(alice, carol, USD(1)), + path(~(MPT)ETH, ~(MPT)BTC, ~USD), + txflags(tfNoRippleDirect | tfPartialPayment), + sendmax(XRP(1)), + ter(tecPATH_DRY)); + } + + // A domain payment should only consume a USD/MPT offer with a domain. + // It must not consume a regular USD/MPT offer. + { + Env env(*this, features); + Account const domainOwner("DomainOwner"); + env.fund(XRP(1'000), gw, alice, carol, bob); + auto const domainID = + setupDomain(env, {alice, bob, carol, gw}, domainOwner, "permdex-cred"); + + MPTTester BTC({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 100}); + MPTTester ETH({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 100}); + + auto test = [&](bool withDomain) { + if (withDomain) + { + env(offer(bob, ETH(1), BTC(1)), domain(domainID)); + } + else + { + env(offer(bob, ETH(1), BTC(1))); + } + + auto const err = withDomain ? ter(tesSUCCESS) : ter(tecPATH_DRY); + env(pay(alice, carol, BTC(1)), + path(~(MPT)BTC), + txflags(tfPartialPayment), + sendmax(ETH(1)), + domain(domainID), + err); + }; + test(true); + test(false); + } + + // A hybrid USD/MPT domain offer should still be consumable by + // a regular payment. + { + Env env(*this, features); + Account const domainOwner("DomainOwner"); + env.fund(XRP(1'000), gw, alice, carol, bob); + auto const domainID = + setupDomain(env, {alice, bob, carol, gw}, domainOwner, "permdex-cred"); + + MPTTester BTC({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 100}); + MPTTester ETH({.env = env, .issuer = gw, .holders = {alice, carol, bob}, .pay = 100}); + + auto test = [&](bool isHybrid) { + auto const flags = isHybrid ? tfHybrid : 0; + env(offer(bob, ETH(1), BTC(1)), txflags(flags), domain(domainID)); + + auto const err = isHybrid ? ter(tesSUCCESS) : ter(tecPATH_DRY); + env(pay(alice, carol, BTC(1)), + path(~(MPT)BTC), + txflags(tfPartialPayment), + sendmax(ETH(1)), + err); + }; + test(true); + test(false); + } + + // MPT/XRP + { + Env env{*this, features}; + MPTTester mpt(env, gw, {.holders = {alice, carol, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 200); + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + mpt.authorize({.account = bob}); + + env(offer(alice, XRP(100), MPT(101))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{XRP(100), MPT(101)}}})); + + env(pay(carol, bob, MPT(101)), + test::jtx::path(~MPT), + sendmax(XRP(100)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 99)); + BEAST_EXPECT(mpt.checkMPTokenAmount(bob, 101)); + } + + // MPT/IOU + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice, carol, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + env(trust(alice, USD(2'000))); + env(pay(gw, alice, USD(1'000))); + env(trust(bob, USD(2'000))); + env(pay(gw, bob, USD(1'000))); + env(trust(carol, USD(2'000))); + env(pay(gw, carol, USD(1'000))); + env.close(); + + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 200); + + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + mpt.authorize({.account = bob}); + + env(offer(alice, USD(100), MPT(101))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{USD(100), MPT(101)}}})); + + env(pay(carol, bob, MPT(101)), + test::jtx::path(~MPT), + sendmax(USD(100)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(env.balance(carol, USD) == USD(900)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 99)); + BEAST_EXPECT(mpt.checkMPTokenAmount(bob, 101)); + } + + // IOU/MPT + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice, carol, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + env(trust(alice, USD(2'000)), txflags(tfClearNoRipple)); + env(pay(gw, alice, USD(1'000))); + env(trust(bob, USD(2'000)), txflags(tfClearNoRipple)); + env.close(); + + mpt.authorize({.account = alice}); + env(pay(gw, alice, MPT(200))); + + mpt.authorize({.account = carol}); + env(pay(gw, carol, MPT(200))); + + env(offer(alice, MPT(101), USD(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{MPT(101), USD(100)}}})); + + env(pay(carol, bob, USD(100)), + test::jtx::path(~USD), + sendmax(MPT(101)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(env.balance(alice, USD) == USD(900)); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 301)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 99)); + BEAST_EXPECT(env.balance(bob, USD) == USD(100)); + } + + // MPT/MPT + { + Env env{*this, features}; + + MPTTester mpt1(env, gw, {.holders = {alice, carol, bob}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + + MPTTester mpt2(env, gw, {.holders = {alice, carol, bob}, .fund = false}); + mpt2.create( + {.ownerCount = 2, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT2"]; + + mpt1.authorize({.account = alice}); + mpt1.pay(gw, alice, 200); + mpt2.authorize({.account = alice}); + + mpt2.authorize({.account = carol}); + mpt2.pay(gw, carol, 200); + + mpt1.authorize({.account = bob}); + mpt2.authorize({.account = bob}); + mpt2.pay(gw, bob, 200); + + env(offer(alice, MPT2(100), MPT1(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{MPT2(100), MPT1(100)}}})); + + // holder to holder + env(pay(carol, bob, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 190)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 10)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(200)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(400)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 10)); + + // issuer to holder + env(pay(gw, bob, MPT1(20)), + test::jtx::path(~MPT1), + sendmax(MPT2(20)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 170)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 30)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(200)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(420)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 30)); + + // holder to issuer + env(pay(bob, gw, MPT1(70)), + test::jtx::path(~MPT1), + sendmax(MPT2(70)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 100)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 100)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(130)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(420)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 30)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 130)); + } + + // MPT/MPT, issuer owns the offer + { + Env env{*this, features}; + + MPTTester mpt1(env, gw, {.holders = {carol, bob}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + + MPTTester mpt2(env, gw, {.holders = {carol, bob}, .fund = false}); + mpt2.create( + {.ownerCount = 2, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT2"]; + + mpt2.authorize({.account = carol}); + mpt2.pay(gw, carol, 200); + + mpt1.authorize({.account = bob}); + mpt2.authorize({.account = bob}); + mpt2.pay(gw, bob, 200); + + env(offer(gw, MPT2(100), MPT1(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, gw, 1, {{Amounts{MPT2(100), MPT1(100)}}})); + + // holder to holder + env(pay(carol, bob, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, gw, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(10)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(390)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 10)); + + // issuer to holder + env(pay(gw, bob, MPT1(20)), + test::jtx::path(~MPT1), + sendmax(MPT2(20)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, gw, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(30)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(390)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 30)); + + // holder to issuer + env(pay(bob, gw, MPT1(70)), + test::jtx::path(~MPT1), + sendmax(MPT2(70)), + txflags(tfPartialPayment)); + env.close(); + + BEAST_EXPECT(expectOffers(env, gw, 0)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(30)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(320)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 30)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 130)); + } + + // MPT/MPT, different issuer + { + Env env{*this, features}; + Account const gw1{"gw1"}; + + MPTTester mpt1(env, gw, {.holders = {alice, carol, bob}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + + env.fund(XRP(1'000), gw1); + MPTTester mpt2(env, gw1, {.holders = {alice, carol, bob}, .fund = false}); + mpt2.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT2"]; + + mpt1.authorize({.account = alice}); + mpt1.pay(gw, alice, 200); + mpt2.authorize({.account = alice}); + + mpt2.authorize({.account = carol}); + mpt2.pay(gw1, carol, 200); + + mpt1.authorize({.account = bob}); + mpt1.pay(gw, bob, 200); + mpt2.authorize({.account = bob}); + mpt2.pay(gw1, bob, 200); + + mpt1.authorize({.account = gw1}); + mpt1.pay(gw, gw1, 200); + + mpt2.authorize({.account = gw}); + mpt2.pay(gw1, gw, 200); + + env(offer(alice, MPT2(100), MPT1(100))); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1, {{Amounts{MPT2(100), MPT1(100)}}})); + + env(pay(carol, bob, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(600)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(600)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 200)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 200)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(carol, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 210)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 200)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 190)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 10)); + + env(pay(bob, gw, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(590)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(600)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 200)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 200)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 210)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 180)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 20)); + + env(pay(gw, bob, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(590)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(600)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 200)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 220)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 170)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 30)); + + env(pay(bob, gw1, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(590)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(600)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 210)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 220)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 180)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 160)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 40)); + + env(pay(gw1, bob, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(590)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(610)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 210)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 190)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 230)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(bob, 180)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 150)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 50)); + + env(pay(gw, gw1, MPT1(10)), + test::jtx::path(~MPT1), + sendmax(MPT2(10)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 1)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(590)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(610)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 220)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 180)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 140)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 60)); + + env(pay(gw1, gw, MPT1(40)), + test::jtx::path(~MPT1), + sendmax(MPT2(40)), + txflags(tfPartialPayment)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(mpt1.checkMPTokenOutstandingAmount(550)); + BEAST_EXPECT(mpt2.checkMPTokenOutstandingAmount(650)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(gw1, 220)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(gw, 180)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(alice, 100)); + BEAST_EXPECT(mpt2.checkMPTokenAmount(alice, 100)); + } + + // MPT/IOU IOU/MPT1 + { + Env env = pathTestEnv(*this); + Account const gw1{"gw1"}; + Account const gw2{"gw2"}; + Account const dan{"dan"}; + env.fund(XRP(1'000), gw2); + auto const USD = gw2["USD"]; + + MPTTester mpt(env, gw, {.holders = {alice, carol}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + MPTTester mpt1(env, gw1, {.holders = {bob, dan}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + mpt1.authorize({.account = bob}); + mpt1.pay(gw1, bob, 200); + mpt1.authorize({.account = dan}); + + env(trust(alice, USD(400))); + env(pay(gw2, alice, USD(200))); + env(trust(bob, USD(400))); + + env(offer(alice, MPT(100), USD(100))); + env(offer(bob, USD(100), MPT1(100))); + env.close(); + + env(pay(carol, dan, MPT1(100)), + sendmax(MPT(100)), + path(~USD, ~MPT1), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + BEAST_EXPECT(expectOffers(env, alice, 0)); + BEAST_EXPECT(expectOffers(env, bob, 0)); + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 100)); + BEAST_EXPECT(mpt1.checkMPTokenAmount(dan, 100)); + } + + // XRP/MPT AMM + { + Env env{*this, features}; + + fund(env, gw, {alice, carol, bob}, XRP(11'000), {USD(20'000)}); + + MPTTester mpt(env, gw, {.fund = false}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = bob}); + mpt.pay(gw, alice, 10'100); + + AMM const amm(env, alice, XRP(10'000), MPT(10'100)); + + env(pay(carol, bob, MPT(100)), + test::jtx::path(~MPT), + sendmax(XRP(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(amm.expectBalances(XRP(10'100), MPT(10'000), amm.tokens())); + BEAST_EXPECT(mpt.checkMPTokenAmount(bob, 100)); + } + + // IOU/MPT AMM + { + Env env{*this, features}; + + fund(env, gw, {alice, carol, bob}, XRP(11'000), {USD(20'000)}); + + MPTTester mpt(env, gw, {.fund = false}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = bob}); + mpt.pay(gw, alice, 10'100); + + AMM const amm(env, alice, USD(10'000), MPT(10'100)); + + env(pay(carol, bob, MPT(100)), + test::jtx::path(~MPT), + sendmax(USD(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(amm.expectBalances(USD(10'100), MPT(10'000), amm.tokens())); + BEAST_EXPECT(mpt.checkMPTokenAmount(bob, 100)); + } + + // MPT/MPT AMM cross-asset payment + { + Env env{*this, features}; + env.fund(XRP(20'000), gw, alice, carol, bob); + env.close(); + + MPTTester mpt1(env, gw, {.fund = false}); + mpt1.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + mpt1.authorize({.account = alice}); + mpt1.authorize({.account = bob}); + mpt1.pay(gw, alice, 10'100); + + MPTTester mpt2(env, gw, {.fund = false}); + mpt2.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT1"]; + mpt2.authorize({.account = alice}); + mpt2.authorize({.account = bob}); + mpt2.authorize({.account = carol}); + mpt2.pay(gw, alice, 10'100); + mpt2.pay(gw, carol, 100); + + AMM const amm(env, alice, MPT2(10'000), MPT1(10'100)); + + env(pay(carol, bob, MPT1(100)), + test::jtx::path(~MPT1), + sendmax(MPT2(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(amm.expectBalances(MPT2(10'100), MPT1(10'000), amm.tokens())); + BEAST_EXPECT(mpt1.checkMPTokenAmount(bob, 100)); + } + + // Multi-steps with AMM + // EUR/MPT1 MPT1/MPT2 MPT2/USD USD/CRN AMM:CRN/MPT MPT/YAN + { + Env env{*this, features}; + auto const USD = gw["USD"]; + auto const EUR = gw["EUR"]; + auto const CRN = gw["CRN"]; + auto const YAN = gw["YAN"]; + + fund( + env, + gw, + {alice, carol, bob}, + XRP(1'000), + {USD(1'000), EUR(1'000), CRN(2'000), YAN(1'000)}); + + auto createMPT = [&]() -> std::pair { + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 2'000); + return {mpt, mpt["MPT"]}; + }; + + auto const [mpt1, MPT1] = createMPT(); + auto const [mpt2, MPT2] = createMPT(); + auto const [mpt3, MPT3] = createMPT(); + + env(offer(alice, EUR(100), MPT1(101))); + env(offer(alice, MPT1(101), MPT2(102))); + env(offer(alice, MPT2(102), USD(103))); + env(offer(alice, USD(103), CRN(104))); + env.close(); + AMM const amm(env, alice, CRN(1'000), MPT3(1'104)); + env(offer(alice, MPT3(104), YAN(100))); + + env(pay(carol, bob, YAN(100)), + test::jtx::path(~MPT1, ~MPT2, ~USD, ~CRN, ~MPT3, ~YAN), + sendmax(EUR(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(env.balance(carol, EUR) == EUR(900)); + BEAST_EXPECT(env.balance(bob, YAN) == YAN(1'100)); + BEAST_EXPECT(amm.expectBalances(CRN(1'104), MPT3(1'000), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + + // Multi-steps with AMM and MPT endpoints + // MPT1/EUR EUR/MPT2 MPT2/USD USD/CRN AMM:CRN/MPT3 MPT3/MPT4 + { + Env env{*this, features}; + auto const USD = gw["USD"]; + auto const EUR = gw["EUR"]; + auto const CRN = gw["CRN"]; + + fund(env, gw, {alice, carol, bob}, XRP(1'000), {USD(1'000), EUR(1'000), CRN(2'000)}); + + auto createMPT = [&]() -> std::pair { + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 2'000); + return {mpt, mpt["MPT"]}; + }; + + auto const [mpt1, MPT1] = createMPT(); + auto const [mpt2, MPT2] = createMPT(); + auto const [mpt3, MPT3] = createMPT(); + auto [mpt4, MPT4] = createMPT(); + mpt4.authorize({.account = bob}); + + env(offer(alice, EUR(100), MPT1(101))); + env(offer(alice, MPT1(101), MPT2(102))); + env(offer(alice, MPT2(102), USD(103))); + env(offer(alice, USD(103), CRN(104))); + env.close(); + AMM const amm(env, alice, CRN(1'000), MPT3(1'104)); + env(offer(alice, MPT3(104), MPT4(100))); + + env(pay(carol, bob, MPT4(100)), + test::jtx::path(~MPT1, ~MPT2, ~USD, ~CRN, ~MPT3, ~MPT4), + sendmax(EUR(100)), + txflags(tfPartialPayment | tfNoRippleDirect)); + env.close(); + + BEAST_EXPECT(env.balance(carol, EUR) == EUR(900)); + BEAST_EXPECT(mpt4.checkMPTokenAmount(bob, 100)); + BEAST_EXPECT(amm.expectBalances(CRN(1'104), MPT3(1'000), amm.tokens())); + BEAST_EXPECT(expectOffers(env, alice, 0)); + } + + // Check that limiting step reduces maximumAmount returned by + // MPTEndpointStep::maxPaymentFlow() + { + Env env(*this, features); + + env.fund(XRP(1'000), gw, alice, carol, bob); + + MPTTester usd(env, gw, {.holders = {alice, carol, bob}, .fund = false}); + usd.create( + {.maxAmt = 1'000, + .authorize = MPTCreate::AllHolders, + .pay = {{{alice}, 1'000}}, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const USD = usd["USD"]; + + MPTTester eur(env, gw, {.holders = {alice, carol, bob}, .fund = false}); + eur.create( + {.maxAmt = 1'000, + .authorize = {{alice, carol}}, + .pay = {{{carol}, 100}}, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const EUR = eur["EUR"]; + + env(offer(alice, EUR(10), USD(10))); + + env(pay(carol, bob, USD(10)), + sendmax(EUR(10)), + path(~USD), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + { + Env env(*this, features); + env.fund(XRP(1'000), gw, alice, carol, bob); + + auto MUSD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 1'000}); + MPT const USD = MUSD; + env(pay(gw, alice, USD(800))); + env(offer(gw, XRP(300), USD(300))); + env(pay(carol, bob, USD(300)), + sendmax(XRP(300)), + path(~USD), + txflags(tfPartialPayment)); + BEAST_EXPECT(MUSD.checkMPTokenAmount(bob, 200)); + BEAST_EXPECT(MUSD.checkMPTokenOutstandingAmount(1'000)); + // initial + offer - fees + BEAST_EXPECT(env.balance(gw) == (XRP(1'000) + XRP(200) - txfee(env, 3))); + } + { + Env env(*this, features); + auto const EUR = gw["EUR"]; + env.fund(XRP(1'000), gw, alice, carol, bob); + env.close(); + + env(trust(alice, EUR(1'000))); + env(pay(gw, alice, EUR(300))); + env(trust(bob, EUR(1'000))); + + auto MUSD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol, bob}, .maxAmt = 1'000}); + MPT const USD = MUSD; + + env(pay(gw, alice, USD(800))); + env(offer(gw, XRP(300), USD(300))); + env(offer(alice, USD(300), EUR(300))); + env(pay(carol, bob, EUR(300)), + sendmax(XRP(300)), + path(~USD, ~EUR), + txflags(tfPartialPayment)); + BEAST_EXPECT(MUSD.checkMPTokenAmount(alice, 1'000)); + BEAST_EXPECT(MUSD.checkMPTokenOutstandingAmount(1'000)); + // initial + offer - fees + BEAST_EXPECT(env.balance(gw) == (XRP(1'000) + XRP(200) - txfee(env, 4))); + BEAST_EXPECT(env.balance(bob, EUR) == EUR(200)); + } + } + + void + testPath(FeatureBitset features) + { + testcase("Path"); + using namespace test::jtx; + Account const gw{"gw"}; + Account const gw1{"gw1"}; + Account const alice{"alice"}; + Account const carol{"carol"}; + Account const bob{"bob"}; + Account const dan{"dan"}; + auto const USD = gw["USD"]; + auto const EUR = gw1["EUR"]; + + // MPT can be a mpt end point step or a book-step + + // Direct MPT payment + { + Env env = pathTestEnv(*this); + + MPTTester mpt(env, gw, {.holders = {dan, carol}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = dan}); + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + auto const [pathSet, srcAmt, dstAmt] = find_paths(env, carol, dan, MPT(-1)); + BEAST_EXPECT(srcAmt == MPT(200)); + BEAST_EXPECT(dstAmt == MPT(200)); + // Direct payment, no path + BEAST_EXPECT(pathSet.empty()); + } + + // Cross-asset payment via XRP/MPT offer (one step) + { + Env env = pathTestEnv(*this); + + env.fund(XRP(1'000), carol); + + MPTTester mpt(env, gw, {.holders = {alice, dan}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = dan}); + mpt.pay(gw, alice, 200); + + env(offer(alice, XRP(100), MPT(100))); + env.close(); + + auto const [pathSet, srcAmt, dstAmt] = find_paths(env, carol, dan, MPT(-1)); + BEAST_EXPECT(srcAmt == XRP(100)); + BEAST_EXPECT(dstAmt == MPT(100)); + if (BEAST_EXPECT(same(pathSet, stpath(IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(~MPT), + sendmax(XRP(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via IOU/MPT offer (one step) + { + Env env = pathTestEnv(*this); + + env.fund(XRP(1'000), carol); + env.fund(XRP(1'000), gw); + + MPTTester mpt(env, gw1, {.holders = {alice, dan}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = dan}); + mpt.pay(gw1, alice, 200); + + env(trust(alice, USD(400))); + env(trust(carol, USD(400))); + env(pay(gw, carol, USD(200))); + + env(offer(alice, USD(100), MPT(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT(-1)); + BEAST_EXPECT(srcAmt == USD(100)); + BEAST_EXPECT(dstAmt == MPT(100)); + if (BEAST_EXPECT( + pathSet.size() == 1 && same(pathSet, stpath(gw, IPE(mpt.issuanceID()))))) + { + // Validate the payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(USD(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT(-1), USD(-1)); + BEAST_EXPECT(srcAmt == USD(90)); + BEAST_EXPECT(dstAmt == MPT(90)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(USD(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include source token + std::tie(pathSet, srcAmt, dstAmt) = + find_paths(env, carol, dan, MPT(-1), std::nullopt, USD.currency); + BEAST_EXPECT(srcAmt == USD(80)); + BEAST_EXPECT(dstAmt == MPT(80)); + if (BEAST_EXPECT( + pathSet.size() == 1 && same(pathSet, stpath(gw, IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(USD(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via MPT/IOU offer (one step) + { + Env env = pathTestEnv(*this); + + env.fund(XRP(1'000), dan); + env.fund(XRP(1'000), gw); + + MPTTester mpt(env, gw1, {.holders = {carol, alice}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = carol}); + mpt.authorize({.account = alice}); + mpt.pay(gw1, carol, 200); + + env(trust(dan, USD(400))); + env(trust(alice, USD(400))); + env(pay(gw, alice, USD(200))); + + env(offer(alice, MPT(100), USD(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, USD(-1)); + BEAST_EXPECT(srcAmt == MPT(100)); + BEAST_EXPECT(dstAmt == USD(100)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(USD))))) + { + // Validate the payment works with the path + env(pay(carol, dan, USD(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, USD(-1), MPT(-1)); + BEAST_EXPECT(srcAmt == MPT(90)); + BEAST_EXPECT(dstAmt == USD(90)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(USD))))) + { + // validate a payment works with the path + env(pay(carol, dan, USD(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include source token + std::tie(pathSet, srcAmt, dstAmt) = + find_paths(env, carol, dan, USD(-1), std::nullopt, MPT.mpt()); + BEAST_EXPECT(srcAmt == MPT(80)); + BEAST_EXPECT(dstAmt == USD(80)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(USD))))) + { + // validate a payment works with the path + env(pay(carol, dan, USD(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via MPT1/MPT offer (one step) + { + Env env = pathTestEnv(*this); + + MPTTester mpt(env, gw, {.holders = {alice, dan}}); + MPTTester mpt1(env, gw1, {.holders = {carol}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = dan}); + mpt.pay(gw, alice, 200); + + mpt1.authorize({.account = carol}); + mpt1.authorize({.account = alice}); + mpt1.pay(gw1, carol, 200); + + env(offer(alice, MPT1(100), MPT(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT(-1)); + BEAST_EXPECT(srcAmt == MPT1(100)); + BEAST_EXPECT(dstAmt == MPT(100)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(MPT1(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT(-1), MPT1(-1)); + BEAST_EXPECT(srcAmt == MPT1(90)); + BEAST_EXPECT(dstAmt == MPT(90)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(MPT1(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include source token + std::tie(pathSet, srcAmt, dstAmt) = + find_paths(env, carol, dan, MPT(-1), std::nullopt, MPT1.mpt()); + BEAST_EXPECT(srcAmt == MPT1(80)); + BEAST_EXPECT(dstAmt == MPT(80)); + if (BEAST_EXPECT(pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT(10)), + path(pathSet[0]), + sendmax(MPT1(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via offers (two steps) + { + Env env = pathTestEnv(*this); + + env.fund(XRP(1'000), carol); + env.fund(XRP(1'000), dan); + + MPTTester mpt(env, gw, {.holders = {alice, bob}}); + + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + mpt.authorize({.account = alice}); + mpt.authorize({.account = bob}); + mpt.pay(gw, alice, 200); + mpt.pay(gw, bob, 200); + + env(trust(bob, USD(200))); + env(pay(gw, bob, USD(100))); + env(trust(dan, USD(200))); + env(trust(alice, USD(200))); + + env(offer(alice, XRP(100), MPT(100))); + env(offer(bob, MPT(100), USD(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, USD(-1)); + BEAST_EXPECT(srcAmt == XRP(100)); + BEAST_EXPECT(dstAmt == USD(100)); + if (BEAST_EXPECT( + pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()), IPE(USD))))) + { + // validate a payment works with the path + env(pay(carol, dan, USD(10)), + path(pathSet[0]), + sendmax(XRP(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, USD(-1), XRP(100)); + BEAST_EXPECT(srcAmt == XRP(90)); + BEAST_EXPECT(dstAmt == USD(90)); + if (BEAST_EXPECT( + pathSet.size() == 1 && same(pathSet, stpath(IPE(mpt.issuanceID()), IPE(USD))))) + { + // validate a payment works with the path + env(pay(carol, dan, USD(10)), + path(pathSet[0]), + sendmax(XRP(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via offers (two steps) + // Start/End with mpt/mp1 and book steps in the middle + { + Env env = pathTestEnv(*this); + Account const gw2{"gw2"}; + env.fund(XRP(1'000), gw2); + auto const USD2 = gw2["USD"]; + + MPTTester mpt(env, gw, {.holders = {alice, carol}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + MPTTester mpt1(env, gw1, {.holders = {bob, dan}}); + mpt1.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + mpt1.authorize({.account = bob}); + mpt1.pay(gw1, bob, 200); + mpt1.authorize({.account = dan}); + + env(trust(alice, USD2(400))); + env(pay(gw2, alice, USD2(200))); + env(trust(bob, USD2(400))); + + env(offer(alice, MPT(100), USD2(100))); + env(offer(bob, USD2(100), MPT1(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT1(-1)); + BEAST_EXPECT(srcAmt == MPT(100)); + BEAST_EXPECT(dstAmt == MPT1(100)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(USD2), IPE(mpt1.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT1(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT1(-1), MPT(-1)); + BEAST_EXPECT(srcAmt == MPT(90)); + BEAST_EXPECT(dstAmt == MPT1(90)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(USD2), IPE(mpt1.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT1(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include source token + std::tie(pathSet, srcAmt, dstAmt) = + find_paths(env, carol, dan, MPT1(-1), std::nullopt, MPT.mpt()); + BEAST_EXPECT(srcAmt == MPT(80)); + BEAST_EXPECT(dstAmt == MPT1(80)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(USD2), IPE(mpt1.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT1(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // Cross-asset payment via offers (two steps) + // Start/End with mpt/mp2 and book steps in the middle + // offers are MPT/MPT + { + Env env = pathTestEnv(*this); + Account const gw2{"gw2"}; + env.fund(XRP(1'000), gw, gw1, gw2, alice, bob, carol, dan); + + MPTTester mpt(env, gw, {.holders = {alice, carol}, .fund = false}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + mpt.authorize({.account = carol}); + mpt.pay(gw, carol, 200); + + MPTTester mpt1(env, gw1, {.holders = {bob, alice}, .fund = false}); + mpt1.create({.ownerCount = 1, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + mpt1.authorize({.account = alice}); + mpt1.pay(gw1, alice, 200); + mpt1.authorize({.account = bob}); + + MPTTester mpt2(env, gw2, {.holders = {bob, dan}, .fund = false}); + mpt2.create({.ownerCount = 1, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT2 = mpt2["MPT2"]; + mpt2.authorize({.account = bob}); + mpt2.pay(gw2, bob, 200); + mpt2.authorize({.account = dan}); + + env(offer(alice, MPT(100), MPT1(100))); + env(offer(bob, MPT1(100), MPT2(100))); + env.close(); + + // No sendMax + STPathSet pathSet; + STAmount srcAmt; + STAmount dstAmt; + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT2(-1)); + BEAST_EXPECT(srcAmt == MPT(100)); + BEAST_EXPECT(dstAmt == MPT2(100)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(mpt1.issuanceID()), IPE(mpt2.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT2(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include sendMax + std::tie(pathSet, srcAmt, dstAmt) = find_paths(env, carol, dan, MPT2(-1), MPT(-1)); + BEAST_EXPECT(srcAmt == MPT(90)); + BEAST_EXPECT(dstAmt == MPT2(90)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(mpt1.issuanceID()), IPE(mpt2.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT2(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + + // Include source token + std::tie(pathSet, srcAmt, dstAmt) = + find_paths(env, carol, dan, MPT2(-1), std::nullopt, MPT.mpt()); + BEAST_EXPECT(srcAmt == MPT(80)); + BEAST_EXPECT(dstAmt == MPT2(80)); + if (BEAST_EXPECT( + pathSet.size() == 1 && + same(pathSet, stpath(IPE(mpt1.issuanceID()), IPE(mpt2.issuanceID()))))) + { + // validate a payment works with the path + env(pay(carol, dan, MPT2(10)), + path(pathSet[0]), + sendmax(MPT(10)), + txflags(tfNoRippleDirect | tfPartialPayment)); + } + } + + // verify no MPT rippling + { + Env env = pathTestEnv(*this); + Account const gw{"gw"}; + Account const gw1{"gw1"}; + Account const carol{"carol"}; + Account const bob{"bob"}; + Account const dan{"dan"}; + Account const john{"john"}; + Account const sean{"sean"}; + + env.fund(XRP(1'000'000), gw); + env.fund(XRP(1'000'000), gw1); + env.fund(XRP(1'000'000), carol); + env.fund(XRP(1'000'000), dan); + env.fund(XRP(1'000'000), bob); + env.fund(XRP(1'000'000), john); + env.fund(XRP(1'000'000), sean); + env.close(); + + MPTTester usd(env, gw, {.holders = {carol, dan}, .fund = false}); + usd.create( + {.authorize = MPTCreate::AllHolders, + .pay = {{MPTCreate::AllHolders, 100}}, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const USD = usd["USD"]; + env(offer(carol, XRP(100), USD(100))); + + MPTTester gbp(env, gw, {.holders = {bob, sean}, .fund = false}); + gbp.create( + {.authorize = MPTCreate::AllHolders, + .pay = {{{bob}, 100}}, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const GBP = gbp["GBP"]; + + MPTTester usd1(env, gw1, {.holders = {bob, dan}, .fund = false}); + usd1.create( + {.authorize = MPTCreate::AllHolders, + .pay = {{{dan}, 100}}, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const USD1 = usd1["USD1"]; + env(offer(bob, USD1(100), GBP(100))); + + // dan has USD/gw and USD1/gw. Had USD been IOU, it would have + // been able to ripple through dan's account. + auto const [pathSet, srcAmt, dstAmt] = find_paths(env, john, sean, GBP(-1), XRP(-1)); + BEAST_EXPECT(pathSet.empty()); + + env(pay(john, sean, GBP(10)), + sendmax(XRP(20)), + path(~USD, dan, gw1, ~GBP), + txflags(tfNoRippleDirect | tfPartialPayment), + ter(temBAD_PATH)); + } + } + + void + testCheck(FeatureBitset features) + { + testcase("Check Create/Cash"); + + using namespace test::jtx; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const carol{"carol"}; + + // MPTokensV2 is disabled + { + Env env{*this, features - featureMPTokensV2}; + + MPTTester mpt(env, gw, {.holders = {alice}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + + uint256 const checkId{keylet::check(gw, env.seq(gw)).key}; + + env(check::create(gw, alice, MPT(100)), ter(temDISABLED)); + env.close(); + + env(check::cash(alice, checkId, MPT(100)), ter(temDISABLED)); + env.close(); + } + + // Insufficient funds + { + Env env{*this, features}; + Account const carol{"carol"}; + + MPTTester mpt(env, gw, {.holders = {alice, carol}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 50); + + uint256 const checkId{keylet::check(alice, env.seq(alice)).key}; + + // can create + env(check::create(alice, carol, MPT(100))); + env.close(); + + // can't cash since alice only has 50 of MPT + env(check::cash(carol, checkId, MPT(100)), ter(tecPATH_PARTIAL)); + env.close(); + + // can cash if DeliverMin is set + // carol is not authorized, MPToken is authorized by CheckCash + env(check::cash(carol, checkId, check::DeliverMin(MPT(50)))); + env.close(); + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 50)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(50)); + } + + // Exceed max amount + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice}}); + mpt.create( + {.maxAmt = 100, + .ownerCount = 1, + .holderCount = 0, + .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + uint256 const checkId{keylet::check(gw, env.seq(gw)).key}; + + // can create + env(check::create(gw, alice, MPT(200))); + env.close(); + + // can't cash since the outstanding amount exceeds max amount + env(check::cash(alice, checkId, MPT(200)), ter(tecPATH_PARTIAL)); + env.close(); + + // can cash if DeliverMin is set + env(check::cash(alice, checkId, check::DeliverMin(MPT(100)))); + env.close(); + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 100)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(100)); + } + + // MPTokenIssuance object doesn't exist + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + env(check::create(alice, carol, MPT(gw)(50)), ter(tecOBJECT_NOT_FOUND)); + env.close(); + auto BTC = MPTTester({.env = env, .issuer = gw}); + uint256 const chkId{getCheckIndex(gw, env.seq(gw))}; + env(check::cash(carol, chkId, MPT(gw)(1)), ter(tecNO_ENTRY)); + env.close(); + } + + // MPToken doesn't exist - can create check since MPToken will be + // automatically created on cash check + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + auto BTC = MPTTester({.env = env, .issuer = gw}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, BTC(50))); + env.close(); + + // But cashing fails if alice doesn't have MPToken + env(check::cash(carol, chkId, BTC(1)), ter(tecPATH_PARTIAL)); + env.close(); + } + + // MPTLock is set + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + auto mpt = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .pay = 100, + .flags = MPTDEXFlags | tfMPTCanLock}); + + mpt.set({.flags = tfMPTLock}); + + // Create Check fails, holder or issuer as destination + env(check::create(alice, carol, mpt(10)), ter(tecLOCKED)); + env.close(); + env(check::create(gw, carol, mpt(10)), ter(tecLOCKED)); + env.close(); + + mpt.set({.flags = tfMPTUnlock}); + + // Create Check succeeds, holder or issuer as destination + uint256 const chkIdAlice{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, mpt(10))); + env.close(); + uint256 const chkIdGw{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, carol, mpt(10))); + env.close(); + + mpt.set({.flags = tfMPTLock}); + + // Cash Check fails, holder and issuer env(check::cash(carol, + // chkIdAlice, mpt(1)), ter(tecPATH_PARTIAL)); // tec is different + // if the source is the issuer (this is consistent with IOU) + env(check::cash(carol, chkIdGw, mpt(2)), ter(tecLOCKED)); + env.close(); + + mpt.set({.flags = tfMPTUnlock}); + + // Cash Check succeeds, holder and issuer. + env(check::cash(carol, chkIdAlice, mpt(1))); + env(check::cash(carol, chkIdGw, mpt(2))); + + // Individual lock + mpt.set({.holder = alice, .flags = tfMPTLock}); + env(check::create(alice, carol, mpt(10)), ter(tecLOCKED)); + env.close(); + env(check::create(carol, alice, mpt(10)), ter(tecLOCKED)); + env.close(); + + mpt.set({.holder = alice, .flags = tfMPTUnlock}); + uint256 const chkId1{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, mpt(10))); + env.close(); + uint256 const chkId2{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, alice, mpt(10))); + env.close(); + uint256 const chkId3{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, gw, mpt(10))); + env.close(); + uint256 const chkId4{getCheckIndex(gw, env.seq(gw))}; + env(check::create(gw, alice, mpt(10))); + env.close(); + mpt.set({.holder = alice, .flags = tfMPTLock}); + env(check::cash(carol, chkId1, mpt(1)), ter(tecPATH_PARTIAL)); + env(check::cash(alice, chkId2, mpt(1)), ter(tecLOCKED)); + env(check::cash(gw, chkId3, mpt(1)), ter(tecPATH_PARTIAL)); + env(check::cash(alice, chkId4, mpt(1)), ter(tecLOCKED)); + } + + // MPTRequireAuth flag is set and the account is not authorized. + // Can create check, which is consistent with the trustlines. + // It should fail on cash check. + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + auto BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .flags = tfMPTRequireAuth | MPTDEXFlags}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, BTC(50))); + env.close(); + + // Authorize alice + BTC.authorize({.account = gw, .holder = alice}); + env(pay(gw, alice, BTC(100))); + + // carol is still not authorized + env(check::cash(carol, chkId, BTC(10)), ter(tecNO_AUTH)); + env.close(); + + // authorize carol, can cash now + BTC.authorize({.account = gw, .holder = carol}); + env(check::cash(carol, chkId, BTC(10))); + env.close(); + } + + // MPTCanTransfer disabled + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + + MPTTester mpt( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .flags = tfMPTCanTrade, + .mutableFlags = tmfMPTCanMutateCanTransfer}); + + // src is issuer + uint256 checkId{keylet::check(gw, env.seq(gw)).key}; + + // can create + env(check::create(gw, alice, mpt(100))); + env.close(); + + // can cash since source is issuer + env(check::cash(alice, checkId, mpt(100))); + env.close(); + + BEAST_EXPECT(env.balance(alice, mpt) == mpt(100)); + BEAST_EXPECT(env.balance(gw, mpt) == mpt(-100)); + + // dst is issuer + checkId = keylet::check(alice, env.seq(alice)).key; + + // can create + env(check::create(alice, gw, mpt(100))); + env.close(); + + // can cash since source is issuer + env(check::cash(gw, checkId, mpt(100))); + env.close(); + + BEAST_EXPECT(env.balance(alice, mpt) == mpt(0)); + BEAST_EXPECT(env.balance(gw, mpt) == mpt(0)); + + // neither src nor dst is issuer, can still create + checkId = keylet::check(alice, env.seq(alice)).key; + env(check::create(alice, carol, mpt(100))); + env.close(); + + // can't cash + env(check::cash(carol, checkId, mpt(10)), ter(tecPATH_PARTIAL)); + env.close(); + + // can cash now + mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTransfer}); + env(pay(gw, alice, mpt(10))); + env.close(); + env(check::cash(carol, checkId, mpt(10))); + env.close(); + } + + // MPTCanTrade disabled + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + + MPTTester mpt( + {.env = env, + .issuer = gw, + .holders = {alice, carol}, + .flags = tfMPTCanTransfer, + .mutableFlags = tmfMPTCanMutateCanTrade}); + + uint256 checkId{keylet::check(gw, env.seq(gw)).key}; + + // can't create + env(check::create(gw, alice, mpt(100)), ter(tecNO_PERMISSION)); + env.close(); + mpt.set({.account = gw, .mutableFlags = tmfMPTSetCanTrade}); + + // can't cash + checkId = keylet::check(gw, env.seq(gw)).key; + env(check::create(gw, carol, mpt(100))); + env.close(); + mpt.set({.account = gw, .mutableFlags = tmfMPTClearCanTrade}); + env(check::cash(carol, checkId, mpt(10)), ter(tecNO_PERMISSION)); + env.close(); + } + + // MPTokenIssuance object doesn't exist + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + auto USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, USD(1))); + env.close(); + + // temMALFORMED because MPT is not USD. It doesn't matter if it + // exists or not + env(check::cash(carol, chkId, MPT(alice)(1)), ter(temMALFORMED)); + env.close(); + } + + // MPToken object doesn't exist and the account is not the issuer of MPT + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + + auto BTC = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000}); + + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + + env(check::create(alice, carol, BTC(1))); + env.close(); + + // MPToken is automatically created + env(check::cash(carol, chkId, BTC(1))); + env.close(); + } + + // MPTRequireAuth flag is set and the account is not authorized. + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + + auto BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .flags = tfMPTRequireAuth | MPTDEXFlags, + .authHolder = true}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + env(check::create(alice, carol, BTC(1))); + env.close(); + + env(check::cash(carol, chkId, BTC(1)), ter(tecPATH_PARTIAL)); + env.close(); + } + + // MPTCanTransfer is not set and the account is not the issuer of MPT + { + Env env{*this, features}; + env.fund(XRP(1'000), gw, alice, carol); + + auto EUR = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, carol}, .flags = tfMPTCanTrade}); + uint256 const chkId{getCheckIndex(alice, env.seq(alice))}; + // alice can create + env(check::create(alice, carol, EUR(1))); + env.close(); + + // carol can't cash + env(check::cash(carol, chkId, EUR(1)), ter(tecPATH_PARTIAL)); + env.close(); + + // if issuer creates a check then carol can cash since + // it's a transfer from the issuer + uint256 const chkId1{getCheckIndex(gw, env.seq(gw))}; + // alice can't create since CanTransfer is not set + env(check::create(gw, carol, EUR(1))); + env.close(); + + env(check::cash(carol, chkId1, EUR(1))); + env.close(); + } + + // Can create check if src/dst don't own MPT + { + Env env{*this, features}; + + MPTTester mpt(env, gw); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + + env.fund(XRP(1'000), alice, carol); + + // src is issuer + uint256 const checkId{keylet::check(alice, env.seq(alice)).key}; + + // can create + env(check::create(alice, carol, MPT(100))); + env.close(); + + // authorize/fund alice + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 100); + + // carol can cash the check. MPToken is created automatically + env(check::cash(carol, checkId, MPT(100))); + env.close(); + + BEAST_EXPECT(mpt.checkMPTokenAmount(carol, 100)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(100)); + } + + // Normal create/cash + { + Env env{*this, features}; + + MPTTester mpt(env, gw, {.holders = {alice}}); + mpt.create( + {.ownerCount = 1, .holderCount = 0, .flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + + uint256 const checkId{keylet::check(gw, env.seq(gw)).key}; + + env(check::create(gw, alice, MPT(100))); + env.close(); + + env(check::cash(alice, checkId, MPT(100))); + env.close(); + + BEAST_EXPECT(mpt.checkMPTokenAmount(alice, 100)); + BEAST_EXPECT(mpt.checkMPTokenOutstandingAmount(100)); + } + } + + void + testAMMClawback(FeatureBitset features) + { + using namespace jtx; + testcase("AMMClawback"); + Account const gw{"gw"}; + Account const alice{"alice"}; + auto const USD = gw["USD"]; + + // MPTokenIssuance object doesn't exist + { + Env env(*this, features); + env.fund(XRP(1'000), gw, alice); + MPTTester const BTC({.env = env, .issuer = gw}); + AMM const amm(env, gw, BTC(100), USD(100)); + env(amm::ammClawback(gw, alice, USD, MPT(alice), std::nullopt), ter(terNO_AMM)); + env(amm::ammClawback(gw, alice, USD, BTC, MPT(alice)(100)), ter(temBAD_AMOUNT)); + } + + // MPTLock flag is set and the account is not the issuer of MPT - + // can still clawback since the issuer clawbacks + { + Env env(*this, features); + env.fund(XRP(100'000), gw, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanLock | tfMPTCanClawback | MPTDEXFlags}); + + env.trust(USD(10'000), alice); + env(pay(gw, alice, USD(10'000))); + env.close(); + + AMM amm(env, gw, BTC(100), USD(100)); + env.close(); + amm.deposit(alice, 1'000); + env.close(); + + BTC.set({.flags = tfMPTLock}); + + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt)); + } + + // MPTRequireAuth flag is set and the account is not authorized - + // can still clawback since the issuer clawbacks + { + Env env(*this, features); + env.fund(XRP(100'000), gw, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTRequireAuth | tfMPTCanClawback | MPTDEXFlags, + .authHolder = true}); + + env.trust(USD(10'000), alice); + env(pay(gw, alice, USD(10'000))); + env.close(); + + AMM amm(env, gw, BTC(100), USD(100)); + env.close(); + amm.deposit(alice, 1'000); + env.close(); + + BTC.authorize({.account = gw, .holder = alice, .flags = tfMPTUnauthorize}); + + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt)); + } + + // MPTCanTransfer is not set and the account is not the issuer of MPT - + // can't clawback since a holder can't deposit + { + Env env(*this, features); + env.fund(XRP(100'000), gw, alice); + env.close(); + + env(fset(gw, asfAllowTrustLineClawback)); + env.close(); + + auto BTC = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 40'000, + .flags = tfMPTCanClawback | tfMPTCanTrade, + .authHolder = true}); + + env.trust(USD(10'000), alice); + env(pay(gw, alice, USD(10'000))); + env.close(); + + AMM amm(env, gw, BTC(100), USD(100)); + env.close(); + // alice can't deposit since MPTCanTransfer is not set + amm.deposit( + DepositArg{.account = alice, .tokens = 1'000, .err = ter(tecNO_PERMISSION)}); + env.close(); + + // can't clawback since alice is not an LP + env(amm::ammClawback(gw, alice, BTC, USD, std::nullopt), ter(tecAMM_BALANCE)); + } + + { + Env env(*this, features); + fund(env, gw, {alice}, XRP(1'000), {USD(1'000)}); + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + AMM amm(env, gw, MPT(100), XRP(100)); + amm.deposit(DepositArg{.account = alice, .asset1In = XRP(10)}); + amm::ammClawback(gw, alice, MPTIssue(mpt.issuanceID()), xrpIssue(), MPT(10)); + } + + { + Env env(*this, features); + fund(env, gw, {alice}, XRP(1'000), {USD(1'000)}); + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + mpt.authorize({.account = alice}); + mpt.pay(gw, alice, 1'000); + auto const MPT = mpt["MPT"]; + AMM amm(env, gw, MPT(100), XRP(100)); + amm.deposit(DepositArg{.account = alice, .tokens = 10'000}); + amm::ammClawback(gw, alice, MPTIssue(mpt.issuanceID()), xrpIssue(), MPT(10)); + } + + // clawback one asset from MPT/MPT AMM. MPToken for another asset + // is created for the Liquidity Provider + { + Env env(*this, features); + env.fund(XRP(1'000), gw, alice); + auto USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice}, + .pay = 10'000, + .flags = tfMPTCanClawback | MPTDEXFlags}); + auto EUR = + MPTTester({.env = env, .issuer = gw, .flags = tfMPTCanClawback | MPTDEXFlags}); + AMM amm(env, gw, USD(1'000), EUR(1'000)); + amm.deposit({.account = alice, .asset1In = USD(1'000)}); + // MPToken doesn't exist + BEAST_EXPECT(env.le(keylet::mptoken(EUR.issuanceID(), alice)) == nullptr); + env(amm::ammClawback(gw, alice, USD, EUR, USD(100))); + // MPToken is created + BEAST_EXPECT(env.le(keylet::mptoken(EUR.issuanceID(), alice))); + } + } + + void + testBasicAMM(FeatureBitset features) + { + testcase("Basic AMM"); + using namespace jtx; + Account const gw{"gw"}; + Account const alice{"alice"}; + Account const carol{"carol"}; + Account const bob{"bob"}; + auto const USD = gw["USD"]; + + // Create/deposit/withdraw + { + Env env{*this}; + + fund(env, gw, {alice, carol, bob}, XRP(1'000), {USD(1'000)}); + + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + mpt.authorize({.account = alice}); + mpt.authorize({.account = carol}); + mpt.pay(gw, alice, 1'000); + mpt.pay(gw, carol, 1'000); + + MPTTester mpt1(env, gw, {.fund = false}); + mpt1.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT1 = mpt1["MPT1"]; + mpt1.authorize({.account = alice}); + mpt1.authorize({.account = carol}); + mpt1.pay(gw, alice, 1'000); + mpt1.pay(gw, carol, 1'000); + + std::vector> pools = { + {XRP(100), MPT(100), IOUAmount{100'000}}, + {USD(100), MPT(100), IOUAmount{100}}, + {MPT(100), MPT1(100), IOUAmount{100}}}; + for (auto& pool : pools) + { + AMM amm(env, gw, std::get<0>(pool), std::get<1>(pool)); + amm.deposit(alice, std::get<2>(pool)); + amm.deposit(carol, std::get<2>(pool)); + // bob doesn't own MPT + amm.deposit( + DepositArg{ + .account = bob, .tokens = std::get<2>(pool), .err = ter(tecNO_AUTH)}); + amm.withdrawAll(alice); + amm.withdrawAll(carol); + amm.withdrawAll(gw); + BEAST_EXPECT(!amm.ammExists()); + } + } + + // Payment, one step + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + MPT const EUR = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + + env(pay(gw, alice, EUR(100))); + + AMM const amm(env, gw, USD(1'100), EUR(1'000)); + + env(pay(alice, carol, USD(100)), sendmax(EUR(100))); + + BEAST_EXPECT(amm.expectBalances(USD(1'000), EUR(1'100), amm.tokens())); + BEAST_EXPECT(env.balance(carol, USD) == USD(100)); + BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); + } + + // Payment, two steps + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice, carol); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + MPT const EUR = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + MPT const BTC = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + env(pay(gw, alice, EUR(100))); + + AMM const ammEUR_USD(env, gw, EUR(1'000), USD(1'100)); + AMM const ammUSD_BTC(env, gw, USD(1'000), BTC(1'100)); + + env(pay(alice, carol, BTC(100)), + sendmax(EUR(100)), + path(~USD, ~BTC), + txflags(tfNoRippleDirect)); + + BEAST_EXPECT(ammEUR_USD.expectBalances(USD(1'000), EUR(1'100), ammEUR_USD.tokens())); + BEAST_EXPECT(ammUSD_BTC.expectBalances(USD(1'100), BTC(1'000), ammUSD_BTC.tokens())); + BEAST_EXPECT(env.balance(carol, BTC) == BTC(100)); + BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); + } + + // Offer crossing + { + Env env(*this); + + env.fund(XRP(1'000), gw, alice); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + MPT const EUR = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + env(pay(gw, alice, EUR(1'000))); + + AMM const amm(env, gw, EUR(1'000'000), USD(1'001'000)); + + env(offer(alice, USD(1'000), EUR(1'000))); + + BEAST_EXPECT(amm.expectBalances(USD(1'000'000), EUR(1'001'000), amm.tokens())); + BEAST_EXPECT(env.balance(alice, USD) == USD(1'000)); + BEAST_EXPECT(env.balance(alice, EUR) == EUR(0)); + } + + { + Env env(*this); + env.fund(XRP(1'000'000), gw, alice, carol); + + auto USD = MPTTester( + {.env = env, + .issuer = gw, + .flags = tfMPTCanLock | MPTDEXFlags, + .mutableFlags = tmfMPTCanMutateRequireAuth | tmfMPTCanMutateCanTransfer | + tmfMPTCanMutateCanClawback | tmfMPTCanMutateCanTrade}); + auto EUR = MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000'000}); + + auto const increment = env.current()->fees().increment; + auto const txfee = fee(drops(increment)); + auto const badMPT = MPT(gw, 1'000); + + auto createDeleteAMM = [&](Account const& lp) { + AMM amm( + env, + lp, + USD(1'000), + EUR(1'000), + CreateArg{.fee = static_cast(increment.value())}); + amm.withdrawAll(lp); + BEAST_EXPECT(!amm.ammExists()); + }; + + // + // AMMCreate + // + + auto createJv = AMM::createJv(alice, badMPT(1'000), EUR(1'000), 0); + + auto createFail = [&](Account const& account, auto const& err) { + createJv[sfAccount] = account.human(); + env(createJv, txfee, ter(err)); + env.close(); + }; + + // MPTokenIssuance doesn't exist + + createFail(alice, tecOBJECT_NOT_FOUND); + + // MPToken doesn't exist + + createJv[sfAmount] = STAmount{USD(1'000)}.getJson(); + createFail(alice, tecNO_AUTH); + + // alice authorizes MPToken, can create + USD.authorize({.account = alice}); + env(pay(gw, alice, USD(1'000'000)), txfee); + env.close(); + createDeleteAMM(alice); + + // MPTLock is set + + // alice and issuer can't create + USD.set({.flags = tfMPTLock}); + createFail(alice, tecFROZEN); + createFail(gw, tecFROZEN); + + // MPTRequireAuth is set + + // alice is not authorized + USD.set({.flags = tfMPTUnlock}); + USD.set({.mutableFlags = tmfMPTSetRequireAuth}); + createFail(alice, tecNO_AUTH); + // issuer can create + createDeleteAMM(gw); + + // alice is authorized, can create + USD.authorize({.account = gw, .holder = alice}); + createDeleteAMM(alice); + + // MPTCanTransfer is not set + + USD.set({.mutableFlags = tmfMPTClearRequireAuth}); + USD.set({.mutableFlags = tmfMPTClearCanTransfer}); + // alice can't create + createFail(alice, tecNO_PERMISSION); + // issuer can create + createDeleteAMM(gw); + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + // alice can create + createDeleteAMM(alice); + + // MPTCanTrade is not set + + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + USD.set({.mutableFlags = tmfMPTClearCanTrade}); + // alice and issuer can't create + createFail(alice, tecNO_PERMISSION); + createFail(gw, tecNO_PERMISSION); + USD.set({.mutableFlags = tmfMPTSetCanTrade}); + + // + // AMMDeposit + // + + AMM amm(env, gw, USD(1'000), EUR(1'000)); + + // MPTokenIssuance doesn't exist + + amm.deposit( + {.account = alice, + .asset1In = badMPT(1), + .asset2In = EUR(1), + .assets = std::make_pair(badMPT, EUR), + .err = ter(terNO_AMM)}); + + // MPToken doesn't exist + + amm.deposit( + {.account = carol, .asset1In = USD(1), .asset2In = EUR(1), .err = ter(tecNO_AUTH)}); + + // MPTLock is set + + USD.set({.flags = tfMPTLock}); + // alice and issuer can't deposit + for (auto const& account : {carol, gw}) + { + amm.deposit( + {.account = account, + .asset1In = USD(1), + .asset2In = EUR(1), + .err = ter(tecFROZEN)}); + amm.deposit( + {.account = account, + .asset1In = EUR(1), + .assets = std::make_pair(EUR, USD), + .err = ter(tecFROZEN)}); + } + USD.set({.flags = tfMPTUnlock}); + + // MPTRequireAuth is set + + // carol authorizes MPToken but is not authorized by the issuer + USD.authorize({.account = carol}); + env(pay(gw, carol, USD(1'000'000))); + // carol authorizes EUR + EUR.authorize({.account = carol}); + env(pay(gw, carol, EUR(1'000'000))); + USD.set({.mutableFlags = tmfMPTSetRequireAuth}); + // have to authorize amm account + USD.authorize({.account = gw, .holder = Account{"amm", amm.ammAccount()}}); + env.close(); + amm.deposit( + {.account = carol, .asset1In = USD(1), .asset2In = EUR(1), .err = ter(tecNO_AUTH)}); + amm.deposit( + {.account = carol, + .asset1In = EUR(1), + .assets = std::make_pair(EUR, USD), + .err = ter(tecNO_AUTH)}); + // issuer can deposit + amm.deposit({.account = gw, .tokens = 1'000}); + // carol is authorized, can deposit + USD.authorize({.account = gw, .holder = carol}); + amm.deposit({.account = carol, .tokens = 1'000}); + + // MPTCanTransfer is not set + + USD.set({.mutableFlags = tmfMPTClearRequireAuth}); + USD.set({.mutableFlags = tmfMPTClearCanTransfer}); + // carol can't deposit + amm.deposit( + {.account = carol, + .asset1In = USD(1), + .asset2In = EUR(1), + .err = ter(tecNO_PERMISSION)}); + amm.deposit( + {.account = carol, + .asset1In = EUR(1), + .assets = std::make_pair(EUR, USD), + .err = ter(tecNO_PERMISSION)}); + // issuer can deposit + amm.deposit({.account = gw, .tokens = 1'000}); + // carol can deposit + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + amm.deposit({.account = carol, .tokens = 1'000}); + + // MPTCanTrade is not set + + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + USD.set({.mutableFlags = tmfMPTClearCanTrade}); + amm.deposit({.account = gw, .tokens = 1'000, .err = ter(tecNO_PERMISSION)}); + amm.deposit({.account = carol, .tokens = 1'000, .err = ter(tecNO_PERMISSION)}); + USD.set({.mutableFlags = tmfMPTSetCanTrade}); + + // + // AMMWithdraw + // + + // MPTokenIssuance doesn't exist + + amm.withdraw( + WithdrawArg{ + .account = carol, + .asset1Out = badMPT(1), + .asset2Out = EUR(1), + .assets = std::make_pair(badMPT, EUR), + .err = ter(terNO_AMM)}); + + // MPToken doesn't exist - doesn't apply since MPToken is created + // on withdraw in this case + + // MPTLock is set + + USD.set({.flags = tfMPTLock}); + // carol and issuer can't withdraw + for (auto const& account : {carol, gw}) + { + amm.withdraw( + {.account = account, + .asset1Out = USD(1), + .asset2Out = EUR(1), + .err = ter(tecFROZEN)}); + amm.withdraw({.account = account, .tokens = 1'000, .err = ter(tecFROZEN)}); + // can single withdraw another asset + amm.withdraw( + {.account = account, .asset1Out = EUR(1), .assets = std::make_pair(EUR, USD)}); + } + USD.set({.flags = tfMPTUnlock}); + + // MPTRequireAuth is set + + USD.set({.mutableFlags = tmfMPTSetRequireAuth}); + USD.authorize({.account = gw, .holder = carol, .flags = tfMPTUnauthorize}); + // carol can't withdraw + amm.withdraw( + {.account = carol, + .asset1Out = USD(1), + .asset2Out = EUR(1), + .err = ter(tecNO_AUTH)}); + // can withdraw another asset + amm.withdraw( + {.account = carol, .asset1Out = EUR(1), .assets = std::make_pair(EUR, USD)}); + // issuer can withdraw + amm.withdraw({.account = gw, .asset1Out = USD(1), .asset2Out = EUR(1)}); + // carol is authorized, can withdraw + USD.authorize({.account = gw, .holder = carol}); + amm.withdraw({.account = carol, .asset1Out = USD(1), .asset2Out = EUR(1)}); + + // MPTCanTransfer is set + + USD.set({.mutableFlags = tmfMPTClearRequireAuth}); + USD.set({.mutableFlags = tmfMPTClearCanTransfer}); + // carol can't withdraw + amm.withdraw( + {.account = carol, + .asset1Out = USD(1), + .asset2Out = EUR(1), + .err = ter(tecNO_PERMISSION)}); + // can withdraw another asset + amm.withdraw( + {.account = carol, .asset1Out = EUR(1), .assets = std::make_pair(EUR, USD)}); + // issuer can withdraw + amm.withdraw({.account = gw, .asset1Out = USD(1), .asset2Out = EUR(1)}); + // carol can withdraw + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + amm.withdraw({.account = carol, .asset1Out = USD(1), .asset2Out = EUR(1)}); + + USD.set({.mutableFlags = tmfMPTSetCanTransfer}); + USD.set({.mutableFlags = tmfMPTClearCanTrade}); + amm.withdraw({.account = gw, .tokens = 1'000, .err = ter(tecNO_PERMISSION)}); + amm.withdraw({.account = carol, .tokens = 1'000, .err = ter(tecNO_PERMISSION)}); + USD.set({.mutableFlags = tmfMPTSetCanTrade}); + + // MPToken created on withdraw + + // redeem all carol's USD and unauthorize USD + amm.withdrawAll(carol); + env(pay(carol, gw, env.balance(carol, USD))); + USD.authorize({.account = carol, .flags = tfMPTUnauthorize}); + BEAST_EXPECT(env.le(keylet::mptoken(USD.issuanceID(), carol)) == nullptr); + // single-deposit EUR + amm.deposit( + {.account = carol, .asset1In = EUR(1'000), .assets = std::make_pair(EUR, USD)}); + // withdraw in USD to create MPToken + amm.withdraw({.account = carol, .asset1Out = USD(100)}); + BEAST_EXPECT(env.le(keylet::mptoken(USD.issuanceID(), carol))); + } + } + public: void run() override @@ -3407,15 +6634,27 @@ public: // MPTokenIssuanceDestroy testDestroyValidation(all - featureSingleAssetVault); - testDestroyValidation(all); + testDestroyValidation(all - featureSingleAssetVault - featureMPTokensV2); + testDestroyValidation((all | featureSingleAssetVault) - featureMPTokensV2); + testDestroyValidation(all - featureMPTokensV2); + testDestroyValidation(all | featureSingleAssetVault); testDestroyEnabled(all - featureSingleAssetVault); - testDestroyEnabled(all); + testDestroyEnabled(all - featureSingleAssetVault - featureMPTokensV2); + testDestroyEnabled((all | featureSingleAssetVault) - featureMPTokensV2); + testDestroyEnabled(all - featureMPTokensV2); + testDestroyEnabled(all | featureSingleAssetVault); // MPTokenAuthorize testAuthorizeValidation(all - featureSingleAssetVault); - testAuthorizeValidation(all); + testAuthorizeValidation(all - featureSingleAssetVault - featureMPTokensV2); + testAuthorizeValidation((all | featureSingleAssetVault) - featureMPTokensV2); + testAuthorizeValidation(all - featureMPTokensV2); + testAuthorizeValidation(all | featureSingleAssetVault); testAuthorizeEnabled(all - featureSingleAssetVault); - testAuthorizeEnabled(all); + testAuthorizeEnabled(all - featureSingleAssetVault - featureMPTokensV2); + testAuthorizeEnabled((all | featureSingleAssetVault) - featureMPTokensV2); + testAuthorizeEnabled(all - featureMPTokensV2); + testAuthorizeEnabled(all | featureSingleAssetVault); // MPTokenIssuanceSet testSetValidation(all - featureSingleAssetVault - featureDynamicMPT); @@ -3429,12 +6668,20 @@ public: // MPT clawback testClawbackValidation(all); + testClawbackValidation(all - featureMPTokensV2); testClawback(all); + testClawback(all - featureMPTokensV2); // Test Direct Payment testPayment(all); + testPayment(all | featureSingleAssetVault); + testPayment((all | featureSingleAssetVault) - featureMPTokensV2); + testPayment(all - featureMPTokensV2); + testDepositPreauth(all); testDepositPreauth(all - featureCredentials); + testDepositPreauth(all - featureMPTokensV2); + testDepositPreauth(all - featureCredentials - featureMPTokensV2); // Test MPT Amount is invalid in Tx, which don't support MPT testMPTInvalidInTx(all); @@ -3456,7 +6703,26 @@ public: testMutateRequireAuth(all); testMutateCanEscrow(all); testMutateCanTransfer(all); + testMutateCanTransfer(all - featureMPTokensV2); testMutateCanClawback(all); + + // Test offer crossing + testOfferCrossing(all); + + // Test cross asset payment + testCrossAssetPayment(all); + + // Test path finding + testPath(all); + + // Test checks + testCheck(all); + + // Add AMMClawback + testAMMClawback(all); + + // Test AMM + testBasicAMM(all); } }; diff --git a/src/test/app/NFTokenAuth_test.cpp b/src/test/app/NFTokenAuth_test.cpp index 0c044fc009..e64935c8ab 100644 --- a/src/test/app/NFTokenAuth_test.cpp +++ b/src/test/app/NFTokenAuth_test.cpp @@ -86,8 +86,8 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; Account const A2{"A2"}; auto const USD{G1["USD"]}; @@ -132,8 +132,8 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; Account const A2{"A2"}; auto const USD{G1["USD"]}; @@ -265,8 +265,8 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; Account const A2{"A2"}; auto const USD{G1["USD"]}; @@ -373,8 +373,8 @@ public: using namespace test::jtx; Env env(*this, features); - Account G1{"G1"}; - Account A1{"A1"}; + Account const G1{"G1"}; + Account const A1{"A1"}; Account const A2{"A2"}; Account const broker{"broker"}; auto const USD{G1["USD"]}; diff --git a/src/test/app/NFToken_test.cpp b/src/test/app/NFToken_test.cpp index abbd5ba8e1..5bdd686512 100644 --- a/src/test/app/NFToken_test.cpp +++ b/src/test/app/NFToken_test.cpp @@ -2253,15 +2253,14 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite env(pay(becky, gw, env.balance(becky, gwXAU))); env.close(); - STAmount const startXAUBalance( - gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); + STAmount const startXAUBalance(gwXAU, STAmount::cMinValue, STAmount::cMinOffset + 5); env(pay(gw, alice, startXAUBalance)); env(pay(gw, minter, startXAUBalance)); env(pay(gw, becky, startXAUBalance)); env.close(); // Here is the smallest expressible gwXAU amount. - STAmount const tinyXAU(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset); + STAmount const tinyXAU(gwXAU, STAmount::cMinValue, STAmount::cMinOffset); // minter buys the nft for tinyXAU. Since the transfer involves // alice there should be no transfer fee. @@ -2294,7 +2293,7 @@ class NFTokenBaseUtil_test : public beast::unit_test::suite // carol sells to becky. This is the smallest gwXAU amount // to pay for a transfer that enables a transfer fee of 1. - STAmount const cheapNFT(gwXAU.issue(), STAmount::cMinValue, STAmount::cMinOffset + 5); + STAmount const cheapNFT(gwXAU, STAmount::cMinValue, STAmount::cMinOffset + 5); STAmount beckyBalance = env.balance(becky, gwXAU); uint256 const beckyBuyOfferIndex = keylet::nftoffer(becky, env.seq(becky)).key; diff --git a/src/test/app/OfferMPT_test.cpp b/src/test/app/OfferMPT_test.cpp new file mode 100644 index 0000000000..12d7b74c0a --- /dev/null +++ b/src/test/app/OfferMPT_test.cpp @@ -0,0 +1,4731 @@ +#include +#include +#include + +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +class OfferMPT_test : public beast::unit_test::suite +{ + static XRPAmount + reserve(jtx::Env& env, std::uint32_t count) + { + return env.current()->fees().accountReserve(count); + } + + static std::uint32_t + lastClose(jtx::Env& env) + { + return env.current()->header().parentCloseTime.time_since_epoch().count(); + } + +public: + void + testRmFundedOffer(FeatureBitset features) + { + testcase("Incorrect Removal of Funded Offers"); + + // We need at least two paths. One at good quality and one at bad + // quality. The bad quality path needs two offer books in a row. + // Each offer book should have two offers at the same quality, the + // offers should be completely consumed, and the payment should + // require both offers to be satisfied. The first offer must + // be "taker gets" XRP. Old, broken would remove the first + // "taker gets" xrp offer, even though the offer is still funded and + // not used for the payment. + + using namespace jtx; + auto const gw = Account{"gateway"}; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, bob, carol}}); + auto const BTC = + issue2({.env = env, .token = "BTC", .issuer = gw, .holders = {alice, bob, carol}}); + + env(pay(gw, alice, BTC(1'000))); + + env(pay(gw, carol, USD(1'000))); + env(pay(gw, carol, BTC(1'000))); + + // Must be two offers at the same quality + // "taker gets" must be XRP + // (Different amounts, so I can distinguish the offers) + env(offer(carol, BTC(49), XRP(49))); + env(offer(carol, BTC(51), XRP(51))); + + // Offers for the poor quality path + // Must be two offers at the same quality + env(offer(carol, XRP(50), USD(50))); + env(offer(carol, XRP(50), USD(50))); + + // Offers for the good quality path + env(offer(carol, BTC(1), USD(100))); + + PathSet const paths(Path(XRP, USD), Path(USD)); + + env(pay(alice, bob, USD(100)), + json(paths.json()), + sendmax(BTC(1'000)), + txflags(tfPartialPayment)); + + env.require(balance(bob, USD(100))); + BEAST_EXPECT( + !isOffer(env, carol, BTC(1), USD(100)) && isOffer(env, carol, BTC(49), XRP(49))); + }; + testHelper2TokensMix(test); + } + + void + testCanceledOffer(FeatureBitset features) + { + testcase("Removing Canceled Offers"); + + using namespace jtx; + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + + env.fund(XRP(10'000), alice, gw); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + env(pay(gw, alice, USD(50))); + env.close(); + + auto const offer1Seq = env.seq(alice); + + env(offer(alice, XRP(500), USD(100)), require(offers(alice, 1))); + env.close(); + + BEAST_EXPECT(isOffer(env, alice, XRP(500), USD(100))); + + // cancel the offer above and replace it with a new offer + auto const offer2Seq = env.seq(alice); + + env(offer(alice, XRP(300), USD(100)), + json(jss::OfferSequence, offer1Seq), + require(offers(alice, 1))); + env.close(); + + BEAST_EXPECT( + isOffer(env, alice, XRP(300), USD(100)) && !isOffer(env, alice, XRP(500), USD(100))); + + // Test canceling non-existent offer. + // auto const offer3Seq = env.seq (alice); + + env(offer(alice, XRP(400), USD(200)), + json(jss::OfferSequence, offer1Seq), + require(offers(alice, 2))); + env.close(); + + BEAST_EXPECT( + isOffer(env, alice, XRP(300), USD(100)) && isOffer(env, alice, XRP(400), USD(200))); + + // Test cancellation now with OfferCancel tx + auto const offer4Seq = env.seq(alice); + env(offer(alice, XRP(222), USD(111)), require(offers(alice, 3))); + env.close(); + + BEAST_EXPECT(isOffer(env, alice, XRP(222), USD(111))); + env(offer_cancel(alice, offer4Seq)); + env.close(); + BEAST_EXPECT(env.seq(alice) == offer4Seq + 2); + + BEAST_EXPECT(!isOffer(env, alice, XRP(222), USD(111))); + + // Create an offer that both fails with a tecEXPIRED code and removes + // an offer. Show that the attempt to remove the offer fails. + env.require(offers(alice, 2)); + + env(offer(alice, XRP(5), USD(2)), + json(sfExpiration.fieldName, lastClose(env)), + json(jss::OfferSequence, offer2Seq), + ter(TER{tecEXPIRED})); + env.close(); + + env.require(offers(alice, 2)); + BEAST_EXPECT(isOffer(env, alice, XRP(300), USD(100))); // offer2 + BEAST_EXPECT(!isOffer(env, alice, XRP(5), USD(2))); // expired + } + + void + testTinyPayment(FeatureBitset features) + { + testcase("Tiny payments"); + + // Regression test for tiny payments + using namespace jtx; + using namespace std::chrono_literals; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + auto const gw = Account{"gw"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 400'000'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 400'000'000}); + + env(pay(gw, alice, USD(100'000'000))); + env(pay(gw, carol, EUR(100'000'000))); + + // Create more offers than the loop max count in DeliverNodeReverse + // Note: the DeliverNodeReverse code has been removed; however since + // this is a regression test the original test is being left as-is + // for now. + for (int i = 0; i < 101; ++i) + env(offer(carol, USD(1'000'000), EUR(2'000'000))); + + // Original Offer test sends EUR(10**-81). MPT is integral, + // therefore and integral value is sent respecting the exchange + // rate. I.e. if EUR(1) is sent then it'll result in USD(0). + env(pay(alice, bob, EUR(2)), path(~EUR), sendmax(USD(100))); + }; + testHelper2TokensMix(test); + } + + void + testXRPTinyPayment(FeatureBitset features) + { + testcase("XRP Tiny payments"); + + // Regression test for tiny xrp payments + // In some cases, when the payment code calculates + // the amount of xrp needed as input to an xrp->iou offer + // it would incorrectly round the amount to zero (even when + // round-up was set to true). + // The bug would cause funded offers to be incorrectly removed + // because the code thought they were unfunded. + // The conditions to trigger the bug are: + // 1) When we calculate the amount of input xrp needed for an offer + // from xrp->iou, the amount is less than 1 drop (after rounding + // up the float representation). + // 2) There is another offer in the same book with a quality + // sufficiently bad that when calculating the input amount + // needed the amount is not set to zero. + + using namespace jtx; + using namespace std::chrono_literals; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + auto const dan = Account{"dan"}; + auto const erin = Account{"erin"}; + auto const gw = Account{"gw"}; + + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, dan, erin, gw); + env.close(); + + MPT const USD = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob, carol, dan, erin}, + .pay = std::nullopt}); + env(pay(gw, carol, USD(99'999))); + env(pay(gw, dan, USD(100'000))); + env(pay(gw, erin, USD(100'000))); + env.close(); + + // Carol doesn't quite have enough funds for this offer + // The amount left after this offer is taken will cause + // STAmount to incorrectly round to zero when the next offer + // (at a good quality) is considered. (when the now removed + // stAmountCalcSwitchover2 patch was inactive) + env(offer(carol, drops(1), USD(99'999))); + // Offer at a quality poor enough so when the input xrp is + // calculated in the reverse pass, the amount is not zero. + env(offer(dan, XRP(100), USD(1))); + + env.close(); + // This is the funded offer that will be incorrectly removed. + // It is considered after the offer from carol, which leaves a + // tiny amount left to pay. When calculating the amount of xrp + // needed for this offer, it will incorrectly compute zero in both + // the forward and reverse passes (when the now removed + // stAmountCalcSwitchover2 was inactive.) + env(offer(erin, drops(2), USD(100'000))); + + env(pay(alice, bob, USD(100'000)), + path(~USD), + sendmax(XRP(102)), + txflags(tfNoRippleDirect | tfPartialPayment)); + + env.require(offers(carol, 0), offers(dan, 1)); + + // offer was correctly consumed. There is still some + // liquidity left on that offer. + env.require(balance(erin, USD(99'999)), offers(erin, 1)); + } + + void + testRmSmallIncreasedQOffersXRP(FeatureBitset features) + { + testcase("Rm small increased q offers XRP"); + + // Carol places an offer, but cannot fully fund the offer. When her + // funding is taken into account, the offer's quality drops below its + // initial quality and has an input amount of 1 drop. This is removed as + // an offer that may block offer books. + + using namespace jtx; + using namespace std::chrono_literals; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + auto const gw = Account{"gw"}; + + // Test offer crossing + for (auto crossBothOffers : {false, true}) + { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + // underfund carol's offer + auto initialCarolUSD = USD(499); + env(pay(gw, carol, initialCarolUSD)); + env(pay(gw, bob, USD(100'000))); + env.close(); + // This offer is underfunded + env(offer(carol, drops(1), USD(1'000))); + env.close(); + // offer at a lower quality + env(offer(bob, drops(2), USD(1'000), tfPassive)); + env.close(); + env.require(offers(bob, 1), offers(carol, 1)); + + // alice places an offer that crosses carol's; depending on + // "crossBothOffers" it may cross bob's as well + auto aliceTakerGets = crossBothOffers ? drops(2) : drops(1); + env(offer(alice, USD(1'000), aliceTakerGets)); + env.close(); + + env.require( + offers(carol, 0), + balance( + carol, + initialCarolUSD)); // offer is removed but not taken + if (crossBothOffers) + { + env.require( + offers(alice, 0), balance(alice, USD(1'000))); // alice's offer is crossed + } + else + { + env.require( + offers(alice, 1), balance(alice, USD(0))); // alice's offer is not crossed + } + } + + // Test payments + for (auto partialPayment : {false, true}) + { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, carol}}); + auto const initialCarolUSD = USD(999); + env(pay(gw, carol, initialCarolUSD)); + env.close(); + env(pay(gw, bob, USD(100'000))); + env.close(); + env(offer(carol, drops(1), USD(1'000))); + env.close(); + env(offer(bob, drops(2), USD(2'000), tfPassive)); + env.close(); + env.require(offers(bob, 1), offers(carol, 1)); + + std::uint32_t const flags = + partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; + + TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; + + env(pay(alice, bob, USD(5'000)), + path(~USD), + sendmax(XRP(1)), + txflags(flags), + ter(expectedTer)); + env.close(); + + if (expectedTer == tesSUCCESS) + { + env.require(offers(carol, 0)); + env.require(balance(carol, + initialCarolUSD)); // offer is removed but not taken + } + else + { + // TODO: Offers are not removed when payments fail + // If that is addressed, the test should show that carol's + // offer is removed but not taken, as in the other branch of + // this if statement + } + } + } + + void + testRmSmallIncreasedQOffersMPT(FeatureBitset features) + { + testcase("Rm small increased q offers MPT"); + + // Carol places an offer, but cannot fully fund the offer. When her + // funding is taken into account, the offer's quality drops below its + // initial quality and has an input amount of 1 drop. This is removed as + // an offer that may block offer books. + + using namespace jtx; + using namespace std::chrono_literals; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + auto const gw = Account{"gw"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + auto tinyAmount = [&](T const& token) -> PrettyAmount { + if constexpr (std::is_same_v) + { + STAmount const amt( + token, + /*mantissa*/ 1, + /*exponent*/ -81); + return PrettyAmount(amt, token.account.name()); + } + else + { + STAmount const amt( + token, + /*mantissa*/ 1, + /*exponent*/ 0); + return PrettyAmount(amt, "MPT"); + } + }; + + // Test offer crossing + for (auto crossBothOffers : {false, true}) + { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + // underfund carol's offer + auto initialCarolUSD = tinyAmount(USD); + env(pay(gw, carol, initialCarolUSD)); + env(pay(gw, bob, USD(100'000))); + env(pay(gw, alice, EUR(100'000))); + env.close(); + // This offer is underfunded + env(offer(carol, EUR(10), USD(10'000))); + env.close(); + // offer at a lower quality + env(offer(bob, EUR(10), USD(5'000), tfPassive)); + env.close(); + env.require(offers(bob, 1), offers(carol, 1)); + + // alice places an offer that crosses carol's; depending on + // "crossBothOffers" it may cross bob's as well + // Whatever + auto aliceTakerGets = crossBothOffers ? EUR(2) : EUR(1); + env(offer(alice, USD(1'000), aliceTakerGets)); + env.close(); + + // carol's offer can be partially crossed when EUR is IOU: + // 10e-3EUR/1USD + using tEUR = std::decay_t; + bool constexpr isEURIOU = std::is_same_v; + // partially crossed if IOU, removed but not taken if MPT + auto const balanceCarolUSD = isEURIOU ? USD(0) : initialCarolUSD; + + env.require(offers(carol, 0), balance(carol, balanceCarolUSD)); + if (crossBothOffers) + { + env.require( + offers(alice, 0), balance(alice, USD(1'000))); // alice's offer is crossed + } + else + { + // partially crossed if IOU, not crossed if MPT + auto const balanceAliceUSD = isEURIOU ? USD(1) : USD(0); + env.require(offers(alice, 1), balance(alice, balanceAliceUSD)); + } + } + + // Test payments + for (auto partialPayment : {false, true}) + { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol, gw); + env.close(); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 100'000'000}); + // underfund carol's offer + auto const initialCarolUSD = tinyAmount(USD); + env(pay(gw, carol, initialCarolUSD)); + env(pay(gw, bob, USD(100'000))); + env(pay(gw, alice, EUR(100'000))); + env.close(); + // This offer is underfunded + env(offer(carol, EUR(10), USD(2'000))); + env.close(); + env(offer(bob, EUR(20), USD(4'000), tfPassive)); + env.close(); + env.require(offers(bob, 1), offers(carol, 1)); + + std::uint32_t const flags = + partialPayment ? (tfNoRippleDirect | tfPartialPayment) : tfNoRippleDirect; + + TER const expectedTer = partialPayment ? TER{tesSUCCESS} : TER{tecPATH_PARTIAL}; + + env(pay(alice, bob, USD(5'000)), + path(~USD), + sendmax(EUR(100)), + txflags(flags), + ter(expectedTer)); + env.close(); + + if (expectedTer == tesSUCCESS) + { + // carol's offer can be partially crossed when EUR is IOU: + // 10e-3EUR/1USD + using tEUR = std::decay_t; + bool constexpr isEURIOU = std::is_same_v; + // partially crossed if IOU, removed but not taken if MPT + auto const balanceCarolUSD = isEURIOU ? USD(0) : initialCarolUSD; + env.require(offers(carol, 0)); + env.require(balance(carol, balanceCarolUSD)); + } + else + { + // TODO: Offers are not removed when payments fail + // If that is addressed, the test should show that carol's + // offer is removed but not taken, as in the other branch of + // this if statement + } + } + }; + testHelper2TokensMix(test); + } + + void + testInsufficientReserve(FeatureBitset features) + { + testcase("Insufficient Reserve"); + + // If an account places an offer and its balance + // *before* the transaction began isn't high enough + // to meet the reserve *after* the transaction runs, + // then no offer should go on the books but if the + // offer partially or fully crossed the tx succeeds. + + using namespace jtx; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + + auto const xrpOffer = XRP(1'000); + + // No crossing: + { + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw); + + auto const f = env.current()->fees().base; + auto const r = reserve(env, 0); + + env.fund(r + f, alice); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + auto const usdOffer = USD(1'000); + + env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); + env(offer(alice, xrpOffer, usdOffer), ter(tecINSUF_RESERVE_OFFER)); + + env.require(balance(alice, r - f), owners(alice, 1)); + } + + // Partial cross: + { + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw); + + auto const f = env.current()->fees().base; + auto const r = reserve(env, 0); + + env.fund(r + f, alice); + env.fund(r + 2 * f + xrpOffer, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + auto const usdOffer = USD(1'000); + auto const usdOffer2 = USD(500); + auto const xrpOffer2 = XRP(500); + + env(offer(bob, usdOffer2, xrpOffer2), ter(tesSUCCESS)); + + env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); + env(offer(alice, xrpOffer, usdOffer), ter(tesSUCCESS)); + + env.require( + balance(alice, r - f + xrpOffer2), + balance(alice, usdOffer2), + owners(alice, 1), + balance(bob, r + xrpOffer2), + balance(bob, usdOffer2), + owners(bob, 1)); + } + + // Account has enough reserve as is, but not enough + // if an offer were added. Attempt to sell MPTs to + // buy XRP. If it fully crosses, we succeed. + { + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw); + + auto const f = env.current()->fees().base; + auto const r = reserve(env, 0); + + env.fund(r + f, alice); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + auto const usdOffer = USD(1'000); + auto const usdOffer2 = USD(500); + auto const xrpOffer2 = XRP(500); + + env.fund(r + f + xrpOffer, bob, carol); + env(offer(bob, usdOffer2, xrpOffer2), ter(tesSUCCESS)); + env(offer(carol, usdOffer, xrpOffer), ter(tesSUCCESS)); + + env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); + env(offer(alice, xrpOffer, usdOffer), ter(tesSUCCESS)); + + env.require( + balance(alice, r - f + xrpOffer), + balance(alice, USD(0)), + owners(alice, 1), + balance(bob, r + xrpOffer2), + balance(bob, usdOffer2), + owners(bob, 1), + balance(carol, r + xrpOffer2), + balance(carol, usdOffer2), + owners(carol, 2)); + } + } + + // Helper function that returns the Offers on an account. + static std::vector> + offersOnAccount(jtx::Env& env, jtx::Account account) + { + std::vector> result; + forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + result.push_back(sle); + }); + return result; + } + + void + testFillModes(FeatureBitset features) + { + testcase("Fill Modes"); + + using namespace jtx; + + auto const startBalance = XRP(1'000'000); + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + // Fill or Kill - unless we fully cross, just charge a fee and don't + // place the offer on the books. But also clean up expired offers + // that are discovered along the way. + // + { + Env env{*this, features}; + + auto const f = env.current()->fees().base; + + env.fund(startBalance, gw, alice, bob); + + MPTTester MUSD({.env = env, .issuer = gw}); + MPT const USD = MUSD["USD"]; + + // bob creates an offer that expires before the next ledger close. + env(offer(bob, USD(500), XRP(500)), + json(sfExpiration.fieldName, lastClose(env) + 1), + ter(tesSUCCESS)); + + // The offer expires (it's not removed yet). + env.close(); + env.require(owners(bob, 1), offers(bob, 1)); + + // bob creates the offer that will be crossed. + env(offer(bob, USD(500), XRP(500)), ter(tesSUCCESS)); + env.close(); + env.require(owners(bob, 2), offers(bob, 2)); + + MUSD.authorize({.account = alice}); + env(pay(gw, alice, USD(1'000)), ter(tesSUCCESS)); + + // Order that can't be filled but will remove bob's expired offer: + env(offer(alice, XRP(1'000), USD(1'000)), txflags(tfFillOrKill), ter(tecKILLED)); + + env.require( + balance(alice, startBalance - (f * 2)), + balance(alice, USD(1'000)), + owners(alice, 1), + offers(alice, 0), + balance(bob, startBalance - (f * 2)), + balance(bob, USD(none)), + owners(bob, 1), + offers(bob, 1)); + + // Order that can be filled + env(offer(alice, XRP(500), USD(500)), txflags(tfFillOrKill), ter(tesSUCCESS)); + + env.require( + balance(alice, startBalance - (f * 3) + XRP(500)), + balance(alice, USD(500)), + owners(alice, 1), + offers(alice, 0), + balance(bob, startBalance - (f * 2) - XRP(500)), + balance(bob, USD(500)), + owners(bob, 1), + offers(bob, 0)); + } + + // Immediate or Cancel - cross as much as possible + // and add nothing on the books: + { + Env env{*this, features}; + + auto const f = env.current()->fees().base; + + env.fund(startBalance, gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + env(pay(gw, alice, USD(1'000)), ter(tesSUCCESS)); + + // No cross: + { + env(offer(alice, XRP(1'000), USD(1000)), + txflags(tfImmediateOrCancel), + ter(tecKILLED)); + } + + env.require( + balance(alice, startBalance - f - f), + balance(alice, USD(1000)), + owners(alice, 1), + offers(alice, 0)); + + // Partially cross: + env(offer(bob, USD(50), XRP(50)), ter(tesSUCCESS)); + env(offer(alice, XRP(1000), USD(1000)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); + + env.require( + balance(alice, startBalance - f - f - f + XRP(50)), + balance(alice, USD(950)), + owners(alice, 1), + offers(alice, 0), + balance(bob, startBalance - f - XRP(50)), + balance(bob, USD(50)), + owners(bob, 1), + offers(bob, 0)); + + // Fully cross: + env(offer(bob, USD(50), XRP(50)), ter(tesSUCCESS)); + env(offer(alice, XRP(50), USD(50)), txflags(tfImmediateOrCancel), ter(tesSUCCESS)); + + env.require( + balance(alice, startBalance - f - f - f - f + XRP(100)), + balance(alice, USD(900)), + owners(alice, 1), + offers(alice, 0), + balance(bob, startBalance - f - f - XRP(100)), + balance(bob, USD(100)), + owners(bob, 1), + offers(bob, 0)); + } + + // tfPassive -- place the offer without crossing it. + { + Env env(*this, features); + + env.fund(startBalance, gw, alice, bob); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {bob}}); + + env(pay(gw, bob, USD(1'000))); + env.close(); + + env(offer(alice, USD(1'000), XRP(2'000))); + env.close(); + + auto const aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfTakerGets] == XRP(2'000)); + BEAST_EXPECT(offer[sfTakerPays] == USD(1'000)); + } + + // bob creates a passive offer that could cross alice's. + // bob's offer should stay in the ledger. + env(offer(bob, XRP(2'000), USD(1'000), tfPassive)); + env.close(); + env.require(offers(alice, 1)); + + auto const bobOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobOffers.size() == 1); + for (auto const& offerPtr : bobOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfTakerGets] == USD(1'000)); + BEAST_EXPECT(offer[sfTakerPays] == XRP(2'000)); + } + + // It should be possible for gw to cross both of those offers. + env(offer(gw, XRP(2'000), USD(1'000))); + env.close(); + env.require(offers(alice, 0)); + env.require(offers(gw, 0)); + env.require(offers(bob, 1)); + + env(offer(gw, USD(1'000), XRP(2'000))); + env.close(); + env.require(offers(bob, 0)); + env.require(offers(gw, 0)); + } + + // tfPassive -- cross only offers of better quality. + { + Env env(*this, features); + + env.fund(startBalance, gw, "alice", "bob"); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {bob}}); + + env(pay(gw, "bob", USD(10'000))); + env(offer("alice", USD(5'000), XRP(1'001))); + env.close(); + + env(offer("alice", USD(5'000), XRP(1'000))); + env.close(); + + auto const aliceOffers = offersOnAccount(env, "alice"); + BEAST_EXPECT(aliceOffers.size() == 2); + + // bob creates a passive offer. That offer should cross one + // of alice's (the one with better quality) and leave alice's + // other offer untouched. + env(offer("bob", XRP(2'000), USD(10'000), tfPassive)); + env.close(); + env.require(offers("alice", 1)); + + auto const bobOffers = offersOnAccount(env, "bob"); + BEAST_EXPECT(bobOffers.size() == 1); + for (auto const& offerPtr : bobOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfTakerGets] == USD(4'995)); + BEAST_EXPECT(offer[sfTakerPays] == XRP(999)); + } + } + } + + void + testMalformed(FeatureBitset features) + { + testcase("Malformed Detection"); + + using namespace jtx; + + auto const startBalance = XRP(1'000'000); + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + + Env env{*this, features}; + + env.fund(startBalance, gw, alice); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + // Sell and buy the same asset + { + // Alice tries an MPT to MPT order: + env(pay(gw, alice, USD(1'000)), ter(tesSUCCESS)); + env(offer(alice, USD(1'000), USD(1'000)), ter(temREDUNDANT)); + env.require(owners(alice, 1), offers(alice, 0)); + } + + // Offers with negative amounts + { + env(offer(alice, -USD(1'000), XRP(1'000)), ter(temBAD_OFFER)); + env.require(owners(alice, 1), offers(alice, 0)); + } + + // Bad MPT + { + auto const BAD = MPT(badMPT()); + + env(offer(alice, XRP(1'000), BAD(1'000)), ter(temBAD_CURRENCY)); + env.require(owners(alice, 1), offers(alice, 0)); + } + } + + void + testExpiration(FeatureBitset features) + { + testcase("Offer Expiration"); + + using namespace jtx; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + auto const startBalance = XRP(1'000'000); + auto const xrpOffer = XRP(1'000); + + Env env{*this, features}; + + env.fund(startBalance, gw, alice, bob); + env.close(); + + auto const f = env.current()->fees().base; + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + auto const usdOffer = USD(1'000); + + env(pay(gw, alice, usdOffer), ter(tesSUCCESS)); + env.close(); + env.require( + balance(alice, startBalance - f), + balance(alice, usdOffer), + offers(alice, 0), + owners(alice, 1)); + + // Place an offer that should have already expired. + env(offer(alice, xrpOffer, usdOffer), + json(sfExpiration.fieldName, lastClose(env)), + ter(TER{tecEXPIRED})); + + env.require( + balance(alice, startBalance - f - f), + balance(alice, usdOffer), + offers(alice, 0), + owners(alice, 1)); + env.close(); + + // Add an offer that expires before the next ledger close + env(offer(alice, xrpOffer, usdOffer), + json(sfExpiration.fieldName, lastClose(env) + 1), + ter(tesSUCCESS)); + env.require( + balance(alice, startBalance - f - f - f), + balance(alice, usdOffer), + offers(alice, 1), + owners(alice, 2)); + + // The offer expires (it's not removed yet) + env.close(); + env.require( + balance(alice, startBalance - f - f - f), + balance(alice, usdOffer), + offers(alice, 1), + owners(alice, 2)); + + // Add offer - the expired offer is removed + env(offer(bob, usdOffer, xrpOffer), ter(tesSUCCESS)); + + env.require( + balance(alice, startBalance - f - f - f), + balance(alice, usdOffer), + offers(alice, 0), + owners(alice, 1), + balance(bob, startBalance - f), + balance(bob, USD(none)), + offers(bob, 1), + owners(bob, 1)); + } + + void + testUnfundedCross(FeatureBitset features) + { + testcase("Unfunded Crossing"); + + using namespace jtx; + + auto const gw = Account{"gateway"}; + + auto const xrpOffer = XRP(1'000); + + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw); + + // The fee that's charged for transactions + auto const f = env.current()->fees().base; + + // Account is at the reserve, and will dip below once + // fees are subtracted. + env.fund(reserve(env, 0), "alice"); + MPT const USD = MPTTester({.env = env, .issuer = gw}); + auto const usdOffer = USD(1'000); + env(offer("alice", usdOffer, xrpOffer), ter(tecUNFUNDED_OFFER)); + env.require(balance("alice", reserve(env, 0) - f), owners("alice", 0)); + + // Account has just enough for the reserve and the + // fee. + env.fund(reserve(env, 0) + f, "bob"); + env(offer("bob", usdOffer, xrpOffer), ter(tecUNFUNDED_OFFER)); + env.require(balance("bob", reserve(env, 0)), owners("bob", 0)); + + // Account has enough for the reserve, the fee and + // the offer, and a bit more, but not enough for the + // reserve after the offer is placed. + env.fund(reserve(env, 0) + f + XRP(1), "carol"); + env(offer("carol", usdOffer, xrpOffer), ter(tecINSUF_RESERVE_OFFER)); + env.require(balance("carol", reserve(env, 0) + XRP(1)), owners("carol", 0)); + + // Account has enough for the reserve plus one + // offer, and the fee. + env.fund(reserve(env, 1) + f, "dan"); + env(offer("dan", usdOffer, xrpOffer), ter(tesSUCCESS)); + env.require(balance("dan", reserve(env, 1)), owners("dan", 1)); + + // Account has enough for the reserve plus one + // offer, the fee and the entire offer amount. + env.fund(reserve(env, 1) + f + xrpOffer, "eve"); + env(offer("eve", usdOffer, xrpOffer), ter(tesSUCCESS)); + env.require(balance("eve", reserve(env, 1) + xrpOffer), owners("eve", 1)); + } + + void + testSelfCross(bool use_partner, FeatureBitset features) + { + testcase(std::string("Self-crossing") + (use_partner ? ", with partner account" : "")); + + using namespace jtx; + auto const gw = Account{"gateway"}; + auto const partner = Account{"partner"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + env.close(); + + env.fund(XRP(10'000), gw); + auto const USD = issue1({.env = env, .token = "USD", .issuer = gw}); + auto const BTC = issue2({.env = env, .token = "BTC", .issuer = gw}); + using tUSD = std::decay_t; + using tBTC = std::decay_t; + if (use_partner) + { + env.fund(XRP(10'000), partner); + if constexpr (std::is_same_v) + { + env(trust(partner, USD(100))); + } + else + { + MPTTester MUSD(env, gw, USD); + MUSD.authorize({.account = partner}); + } + if constexpr (std::is_same_v) + { + env(trust(partner, BTC(500))); + } + else + { + MPTTester MBTC(env, gw, BTC); + MBTC.authorize({.account = partner}); + } + env(pay(gw, partner, USD(100))); + env(pay(gw, partner, BTC(500))); + } + auto const& account_to_test = use_partner ? partner : gw; + + env.close(); + env.require(offers(account_to_test, 0)); + + // PART 1: + // we will make two offers that can be used to bridge BTC to USD + // through XRP + env(offer(account_to_test, BTC(250), XRP(1'000))); + env.require(offers(account_to_test, 1)); + + // validate that the book now shows a BTC for XRP offer + BEAST_EXPECT(isOffer(env, account_to_test, BTC(250), XRP(1'000))); + + auto const secondLegSeq = env.seq(account_to_test); + env(offer(account_to_test, XRP(1'000), USD(50))); + env.require(offers(account_to_test, 2)); + + // validate that the book also shows a XRP for USD offer + BEAST_EXPECT(isOffer(env, account_to_test, XRP(1'000), USD(50))); + + // now make an offer that will cross and auto-bridge, meaning + // the outstanding offers will be taken leaving us with none + env(offer(account_to_test, USD(50), BTC(250))); + + auto jrr = getBookOffers(env, USD, BTC); + BEAST_EXPECT(jrr[jss::offers].isArray()); + BEAST_EXPECT(jrr[jss::offers].size() == 0); + + jrr = getBookOffers(env, BTC, XRP); + BEAST_EXPECT(jrr[jss::offers].isArray()); + BEAST_EXPECT(jrr[jss::offers].size() == 0); + + // At this point, all offers are expected to be consumed. + { + auto acctOffers = offersOnAccount(env, account_to_test); + + // No stale offers + BEAST_EXPECT(acctOffers.empty()); + for (auto const& offerPtr : acctOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == USD(0)); + BEAST_EXPECT(offer[sfTakerPays] == XRP(0)); + } + } + + // cancel that lingering second offer so that it doesn't interfere + // with the next set of offers we test. This will not be needed once + // the bridging bug is fixed + env(offer_cancel(account_to_test, secondLegSeq)); + env.require(offers(account_to_test, 0)); + + // PART 2: + // simple direct crossing BTC to USD and then USD to BTC which + // causes the first offer to be replaced + env(offer(account_to_test, BTC(250), USD(50))); + env.require(offers(account_to_test, 1)); + + // validate that the book shows one BTC for USD offer and no USD for + // BTC offers + BEAST_EXPECT(isOffer(env, account_to_test, BTC(250), USD(50))); + + jrr = getBookOffers(env, USD, BTC); + BEAST_EXPECT(jrr[jss::offers].isArray()); + BEAST_EXPECT(jrr[jss::offers].size() == 0); + + // this second offer would self-cross directly, so it causes the + // first offer by the same owner/taker to be removed + env(offer(account_to_test, USD(50), BTC(250))); + env.require(offers(account_to_test, 1)); + + // validate that we now have just the second offer...the first + // was removed + jrr = getBookOffers(env, BTC, USD); + BEAST_EXPECT(jrr[jss::offers].isArray()); + BEAST_EXPECT(jrr[jss::offers].size() == 0); + + BEAST_EXPECT(isOffer(env, account_to_test, USD(50), BTC(250))); + }; + testHelper2TokensMix(test); + } + + void + testNegativeBalance(FeatureBitset features) + { + // This test creates an offer test for negative balance + // with transfer fees and miniscule funds. + testcase("Negative Balance"); + + using namespace jtx; + FeatureBitset const localFeatures = features | fixReducedOffersV2; + + Env env{*this, localFeatures}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + // these *interesting* amounts were taken + // from the original JS test that was ported here + auto const gw_initial_balance = drops(1'149'999'730); + auto const alice_initial_balance = drops(499'946'999'680); + auto const bob_initial_balance = drops(10'199'999'920); + + env.fund(gw_initial_balance, gw); + env.fund(alice_initial_balance, alice); + env.fund(bob_initial_balance, bob); + + MPTTester const MUSD( + {.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 5'000}); + MPT const USD = MUSD; + auto const small_amount = STAmount{USD, 1}; + + env(pay(gw, alice, USD(50))); + env(pay(gw, bob, small_amount)); + + env(offer(alice, USD(50), XRP(150'000))); + + // unfund the offer + env(pay(alice, gw, USD(50))); + + // verify balances + auto jrr = ledgerEntryMPT(env, alice, USD); + // this represents 0 since MPTAmount is a default field + BEAST_EXPECT(!jrr[jss::node].isMember(sfMPTAmount.fieldName)); + + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1"); + + // create crossing offer + std::uint32_t const bobOfferSeq = env.seq(bob); + env(offer(bob, XRP(2000), USD(1))); + + // With the rounding introduced by fixReducedOffersV2, bob's + // offer does not cross alice's offer and goes straight into + // the ledger. + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1"); + + Json::Value const bobOffer = ledgerEntryOffer(env, bob, bobOfferSeq)[jss::node]; + BEAST_EXPECT(bobOffer[sfTakerGets.jsonName][jss::value] == "1"); + BEAST_EXPECT(bobOffer[sfTakerPays.jsonName] == "2000000000"); + } + + void + testOfferCrossWithXRP(bool reverse_order, FeatureBitset features) + { + testcase( + std::string("Offer Crossing with XRP, ") + (reverse_order ? "Reverse" : "Normal") + + " order"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(10'000), gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, alice, USD(500))); + + if (reverse_order) + env(offer(bob, USD(1), XRP(4'000))); + + env(offer(alice, XRP(150'000), USD(50))); + + if (!reverse_order) + env(offer(bob, USD(1), XRP(4000))); + + // Existing offer pays better than this wants. + // Fully consume existing offer. + // Pay 1 USD, get 4000 XRP. + + auto jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1"); + jrr = ledgerEntryRoot(env, bob); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string( + (XRP(10000) - XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) + .xrp())); + + jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "499"); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string( + (XRP(10000) + XRP(reverse_order ? 4000 : 3000) - env.current()->fees().base * 2) + .xrp())); + } + + void + testOfferCrossWithLimitOverride(FeatureBitset features) + { + testcase("Offer Crossing with Limit Override"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(100000), gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + env(pay(gw, alice, USD(500))); + + env(offer(alice, XRP(150'000), USD(50))); + env(offer(bob, USD(1), XRP(3'000))); + + auto jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "1"); + jrr = ledgerEntryRoot(env, bob); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string((XRP(100'000) - XRP(3'000) - env.current()->fees().base * 1).xrp())); + + jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "499"); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string((XRP(100'000) + XRP(3'000) - env.current()->fees().base * 2).xrp())); + } + + void + testOfferAcceptThenCancel(FeatureBitset features) + { + testcase("Offer Accept then Cancel."); + + using namespace jtx; + + Env env{*this, features}; + + MPT const USD = MPTTester({.env = env, .issuer = env.master}); + + auto const nextOfferSeq = env.seq(env.master); + env(offer(env.master, XRP(500), USD(100))); + env.close(); + + env(offer_cancel(env.master, nextOfferSeq)); + BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2); + + // ledger_accept, call twice and verify no odd behavior + env.close(); + env.close(); + BEAST_EXPECT(env.seq(env.master) == nextOfferSeq + 2); + } + + void + testCurrencyConversionEntire(FeatureBitset features) + { + testcase("Currency Conversion: Entire Offer"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(10'000), gw, alice, bob); + env.require(owners(bob, 0)); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env.require(owners(alice, 1), owners(bob, 1)); + + env(pay(gw, alice, USD(100))); + auto const bobOfferSeq = env.seq(bob); + env(offer(bob, USD(100), XRP(500))); + + env.require(owners(alice, 1), owners(bob, 2)); + auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(500).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(100).value().getJson(JsonOptions::none)); + + env(pay(alice, alice, XRP(500)), sendmax(USD(100))); + + auto jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(!jrr[jss::node].isMember(sfMPTAmount.fieldName)); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string((XRP(10'000) + XRP(500) - env.current()->fees().base * 2).xrp())); + + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100"); + + jro = ledgerEntryOffer(env, bob, bobOfferSeq); + BEAST_EXPECT(jro[jss::error] == "entryNotFound"); + + env.require(owners(alice, 1), owners(bob, 1)); + } + + void + testCurrencyConversionIntoDebt(FeatureBitset features) + { + testcase("Currency Conversion: Offerer Into Debt"); + + using namespace jtx; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env{*this, features}; + + env.fund(XRP(10'000), alice, bob, carol); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = alice, .holders = {bob}}); + auto const EURC = + issue2({.env = env, .token = "EUC", .issuer = carol, .holders = {alice}}); + auto const EURB = + issue3({.env = env, .token = "EUB", .issuer = bob, .holders = {carol}}); + + auto const bobOfferSeq = env.seq(bob); + env(offer(bob, USD(50), EURC(200)), ter(tecUNFUNDED_OFFER)); + + env(offer(alice, EURC(200), USD(50))); + + auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); + BEAST_EXPECT(jro[jss::error] == "entryNotFound"); + }; + testHelper3TokensMix(test); + } + + void + testCurrencyConversionInParts(FeatureBitset features) + { + testcase("Currency Conversion: In Parts"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(10'000), gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, alice, USD(200))); + + auto const bobOfferSeq = env.seq(bob); + env(offer(bob, USD(100), XRP(500))); + + env(pay(alice, alice, XRP(200)), sendmax(USD(100))); + + // The previous payment reduced the remaining offer amount by 200 XRP + auto jro = ledgerEntryOffer(env, bob, bobOfferSeq); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(300).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(60).value().getJson(JsonOptions::none)); + + // the balance between alice and gw is 160 USD..200 less the 40 taken + // by the offer + auto jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "160"); + // alice now has 200 more XRP from the payment + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string((XRP(10'000) + XRP(200) - env.current()->fees().base * 2).xrp())); + + // bob got 40 USD from partial consumption of the offer + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "40"); + + // Alice converts USD to XRP which should fail + // due to PartialPayment. + env(pay(alice, alice, XRP(600)), sendmax(USD(100)), ter(tecPATH_PARTIAL)); + + // Alice converts USD to XRP, should succeed because + // we permit partial payment + env(pay(alice, alice, XRP(600)), sendmax(USD(100)), txflags(tfPartialPayment)); + + // Verify the offer was consumed + jro = ledgerEntryOffer(env, bob, bobOfferSeq); + BEAST_EXPECT(jro[jss::error] == "entryNotFound"); + + // verify balances look right after the partial payment + // only 300 XRP should have been payed since that's all + // that remained in the offer from bob. The alice balance is now + // 100 USD because another 60 USD were transferred to bob in the second + // payment + jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100"); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + to_string((XRP(10'000) + XRP(200) + XRP(300) - env.current()->fees().base * 4).xrp())); + + // bob now has 100 USD - 40 from the first payment and 60 from the + // second (partial) payment + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100"); + } + + void + testCrossCurrencyStartXRP(FeatureBitset features) + { + testcase("Cross Currency Payment: Start with XRP"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {carol, bob}}); + + env(pay(gw, carol, USD(500))); + + auto const carolOfferSeq = env.seq(carol); + env(offer(carol, XRP(500), USD(50))); + + env(pay(alice, bob, USD(25)), sendmax(XRP(333))); + + auto jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "25"); + + jrr = ledgerEntryMPT(env, carol, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "475"); + + auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == USD(25).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(250).value().getText()); + } + + void + testCrossCurrencyEndXRP(FeatureBitset features) + { + testcase("Cross Currency Payment: End with XRP"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + + env.fund(XRP(10'000), gw, alice, bob, carol); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, carol}}); + + env(pay(gw, alice, USD(500))); + + auto const carolOfferSeq = env.seq(carol); + env(offer(carol, USD(50), XRP(500))); + + env(pay(alice, bob, XRP(250)), sendmax(USD(333))); + + auto jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "475"); + + jrr = ledgerEntryMPT(env, carol, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "25"); + + jrr = ledgerEntryRoot(env, bob); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + std::to_string(XRP(10'000).value().mantissa() + XRP(250).value().mantissa())); + + auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(250).value().getText()); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == USD(25).value().getJson(JsonOptions::none)); + } + + void + testCrossCurrencyBridged(FeatureBitset features) + { + testcase("Cross Currency Payment: Bridged"); + + using namespace jtx; + auto const gw1 = Account{"gateway_1"}; + auto const gw2 = Account{"gateway_2"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + auto const carol = Account{"carol"}; + auto const dan = Account{"dan"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(10'000), gw1, gw2, alice, bob, carol, dan); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw1, .holders = {alice, carol}}); + auto const EUR = + issue1({.env = env, .token = "EUR", .issuer = gw2, .holders = {bob, dan}}); + + env(pay(gw1, alice, USD(500))); + env(pay(gw2, dan, EUR(400))); + + auto const carolOfferSeq = env.seq(carol); + env(offer(carol, USD(50), XRP(500))); + + auto const danOfferSeq = env.seq(dan); + env(offer(dan, XRP(500), EUR(50))); + + Json::Value jtp{Json::arrayValue}; + jtp[0u][0u][jss::currency] = "XRP"; + env(pay(alice, bob, EUR(30)), json(jss::Paths, jtp), sendmax(USD(333))); + + BEAST_EXPECT(env.balance(alice, USD) == USD(470)); + BEAST_EXPECT(env.balance(bob, EUR) == EUR(30)); + BEAST_EXPECT(env.balance(carol, USD) == USD(30)); + BEAST_EXPECT(env.balance(dan, EUR) == EUR(370)); + + auto jro = ledgerEntryOffer(env, carol, carolOfferSeq); + BEAST_EXPECT(jro[jss::node][jss::TakerGets] == XRP(200).value().getText()); + BEAST_EXPECT( + jro[jss::node][jss::TakerPays] == USD(20).value().getJson(JsonOptions::none)); + + jro = ledgerEntryOffer(env, dan, danOfferSeq); + BEAST_EXPECT( + jro[jss::node][jss::TakerGets] == EUR(20).value().getJson(JsonOptions::none)); + BEAST_EXPECT(jro[jss::node][jss::TakerPays] == XRP(200).value().getText()); + }; + testHelper2TokensMix(test); + } + + void + testBridgedSecondLegDry(FeatureBitset features) + { + // At least with Taker bridging, a sensitivity was identified if the + // second leg goes dry before the first one. This test exercises that + // case. + testcase("Auto Bridged Second Leg Dry"); + + using namespace jtx; + Account const alice{"alice"}; + Account const bob{"bob"}; + Account const carol{"carol"}; + Account const gw{"gateway"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(100'000'000), alice, bob, carol, gw); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice, carol}}); + auto const EUR = issue1({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}}); + + env(pay(gw, alice, USD(10))); + env(pay(gw, carol, USD(3))); + + env(offer(alice, EUR(2), XRP(1))); + env(offer(alice, EUR(2), XRP(1))); + + env(offer(alice, XRP(1), USD(4))); + env(offer(carol, XRP(1), USD(3))); + env.close(); + + // Bob offers to buy 10 USD for 10 EUR. + // 1. He spends 2 EUR taking Alice's auto-bridged offers and + // gets 4 USD for that. + // 2. He spends another 2 EUR taking Alice's last EUR->XRP offer + // and + // Carol's XRP-USD offer. He gets 3 USD for that. + // The key for this test is that Alice's XRP->USD leg goes dry + // before Alice's EUR->XRP. The XRP->USD leg is the second leg + // which showed some sensitivity. + env(pay(gw, bob, EUR(10))); + env.close(); + env(offer(bob, USD(10), EUR(10))); + env.close(); + + env.require(balance(bob, USD(7))); + env.require(balance(bob, EUR(6))); + env.require(offers(bob, 1)); + env.require(owners(bob, 3)); + + env.require(balance(alice, USD(6))); + env.require(balance(alice, EUR(4))); + env.require(offers(alice, 0)); + env.require(owners(alice, 2)); + + env.require(balance(carol, USD(0))); + env.require(balance(carol, EUR(none))); + + env.require(offers(carol, 0)); + env.require(owners(carol, 1)); + }; + testHelper2TokensMix(test); + } + + void + testOfferFeesConsumeFunds(FeatureBitset features) + { + testcase("Offer Fees Consume Funds"); + + using namespace jtx; + auto const gw1 = Account{"gateway_1"}; + auto const gw2 = Account{"gateway_2"}; + auto const gw3 = Account{"gateway_3"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + auto test = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env{*this, features}; + + // Provide micro amounts to compensate for fees to make results + // round nice. reserve: Alice has 3 entries in the ledger, via trust + // lines fees: + // 1 for each trust limit == 3 (alice < mtgox/amazon/bitstamp) + + // 1 for payment == 4 + auto const base = env.current()->fees().base; + auto const starting_xrp = XRP(100) + env.current()->fees().accountReserve(3) + base * 4; + + env.fund(starting_xrp, gw1, gw2, gw3, alice, bob); + env.close(); + + auto const USD1 = + issue1({.env = env, .token = "US1", .issuer = gw1, .holders = {alice, bob}}); + auto const USD2 = + issue2({.env = env, .token = "US2", .issuer = gw2, .holders = {alice, bob}}); + auto const USD3 = + issue3({.env = env, .token = "US3", .issuer = gw3, .holders = {alice}}); + + env(pay(gw1, bob, USD1(500))); + + env(offer(bob, XRP(200), USD1(200))); + // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 + // available. Ask for more than available to prove reserve works. + env(offer(alice, USD1(200), XRP(200))); + + BEAST_EXPECT(env.balance(alice, USD1) == USD1(100)); + BEAST_EXPECT(env.balance(alice) == STAmount(env.current()->fees().accountReserve(3))); + + BEAST_EXPECT(env.balance(bob, USD1) == USD1(400)); + }; + testHelper3TokensMix(test); + } + + void + testOfferCreateThenCross(FeatureBitset features) + { + testcase("Offer Create, then Cross"); + + using namespace jtx; + + Env env{*this, features}; + env.enableFeature(fixUniversalNumber); + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(10'000), gw, alice, bob); + + MPT const CUR = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .transferFee = 5'000}); + + env(pay(gw, bob, CUR(100))); + + env(offer(alice, CUR(50'000), XRP(150'000))); + env(offer(bob, XRP(100), CUR(100))); + + auto jrr = ledgerEntryMPT(env, alice, CUR); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "34"); + + jrr = ledgerEntryMPT(env, bob, CUR); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "64"); + } + + void + testSellFlagBasic(FeatureBitset features) + { + testcase("Offer tfSell: Basic Sell"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; + + env.fund(starting_xrp, gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, bob, USD(500))); + + env(offer(bob, XRP(200), USD(200)), json(jss::Flags, tfSell)); + // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available. + // Alice has 350 + fees - a reserve of 50 = 250 reserve = 100 available. + // Ask for more than available to prove reserve works. + env(offer(alice, USD(200), XRP(200)), json(jss::Flags, tfSell)); + + auto jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "100"); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + STAmount(env.current()->fees().accountReserve(1)).getText()); + + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "400"); + } + + void + testSellFlagExceedLimit(FeatureBitset features) + { + testcase("Offer tfSell: 2x Sell Exceed Limit"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + auto const starting_xrp = + XRP(100) + env.current()->fees().accountReserve(1) + env.current()->fees().base * 2; + + env.fund(starting_xrp, gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, bob, USD(500))); + + env(offer(bob, XRP(100), USD(200))); + // Alice has 350 fees - a reserve of 50 = 250 reserve = 100 available. + // Ask for more than available to prove reserve works. + // Taker pays 100 USD for 100 XRP. + // Selling XRP. + // Will sell all 100 XRP and get more USD than asked for. + env(offer(alice, USD(100), XRP(100)), json(jss::Flags, tfSell)); + + auto jrr = ledgerEntryMPT(env, alice, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "200"); + jrr = ledgerEntryRoot(env, alice); + BEAST_EXPECT( + jrr[jss::node][sfBalance.fieldName] == + STAmount(env.current()->fees().accountReserve(1)).getText()); + + jrr = ledgerEntryMPT(env, bob, USD); + BEAST_EXPECT(jrr[jss::node][sfMPTAmount.fieldName] == "300"); + } + + void + testGatewayCrossCurrency(FeatureBitset features) + { + testcase("Client Issue #535: Gateway Cross Currency"); + + using namespace jtx; + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + auto const base = env.current()->fees().base; + auto const starting_xrp = + XRP(100.1) + env.current()->fees().accountReserve(1) + base * 2; + + env.fund(starting_xrp, gw, alice, bob); + env.close(); + + auto const XTS = + issue1({.env = env, .token = "XTS", .issuer = gw, .holders = {alice, bob}}); + auto const XXX = + issue2({.env = env, .token = "XXX", .issuer = gw, .holders = {alice, bob}}); + env.close(); + + env(pay(gw, alice, XTS(1'000))); + env(pay(gw, alice, XXX(100))); + env(pay(gw, bob, XTS(1'000))); + env(pay(gw, bob, XXX(100))); + + env(offer(alice, XTS(1'000), XXX(100))); + + // WS client is used here because the RPC client could not + // be convinced to pass the build_path argument + auto wsc = makeWSClient(env.app().config()); + Json::Value payment; + payment[jss::secret] = toBase58(generateSeed("bob")); + payment[jss::id] = env.seq(bob); + payment[jss::build_path] = true; + payment[jss::tx_json] = pay(bob, bob, XXX(1)); + payment[jss::tx_json][jss::Sequence] = + env.current()->read(keylet::account(bob.id()))->getFieldU32(sfSequence); + payment[jss::tx_json][jss::Fee] = to_string(env.current()->fees().base); + payment[jss::tx_json][jss::SendMax] = XTS(15).value().getJson(JsonOptions::none); + auto jrr = wsc->invoke("submit", payment); + BEAST_EXPECT(jrr[jss::status] == "success"); + BEAST_EXPECT(jrr[jss::result][jss::engine_result] == "tesSUCCESS"); + if (wsc->version() == 2) + { + BEAST_EXPECT(jrr.isMember(jss::jsonrpc) && jrr[jss::jsonrpc] == "2.0"); + BEAST_EXPECT(jrr.isMember(jss::ripplerpc) && jrr[jss::ripplerpc] == "2.0"); + BEAST_EXPECT(jrr.isMember(jss::id) && jrr[jss::id] == 5); + } + + BEAST_EXPECT(env.balance(alice, XTS) == XTS(1010)); + BEAST_EXPECT(env.balance(alice, XXX) == XXX(99)); + + BEAST_EXPECT(env.balance(bob, XTS) == XTS(990)); + BEAST_EXPECT(env.balance(bob, XXX) == XXX(101)); + }; + testHelper2TokensMix(test); + } + + void + testPartialCross(FeatureBitset features) + { + // Test a number of different corner cases regarding adding a + // possibly crossable offer to an account. The test is table + // driven so it should be easy to add or remove tests. + testcase("Partial Crossing"); + + using namespace jtx; + + auto const gw = Account("gateway"); + + Env env{*this, features}; + + env.fund(XRP(10'000'000), gw); + env.close(); + + auto MUSD = MPTTester({.env = env, .issuer = gw}); + MPT const USD = MUSD; + + // The fee that's charged for transactions + auto const f = env.current()->fees().base; + + // To keep things simple all offers are 1 : 1 for XRP : USD. + enum preAuthType { noPreAuth, acctPreAuth }; + struct TestData + { + std::string account; // Account operated on + STAmount fundXrp; // Account funded with + int bookAmount; // USD -> XRP offer on the books + preAuthType preAuth; // If true, pre-auth MPToken + int offerAmount; // Account offers this much XRP -> USD + TER tec; // Returned tec code + STAmount spentXrp; // Amount removed from fundXrp + PrettyAmount balanceUsd; // Balance on account end + int offers; // Offers on account + int owners; // Owners on account + int scale = 1; // Scale MPT + }; + + // clang-format off + TestData const tests[]{ + // acct fundXrp bookAmt preTrust offerAmt tec spentXrp balanceUSD offers owners scale + {"ann", reserve(env, 0) + 0 * f, 1, noPreAuth, 1000, tecUNFUNDED_OFFER, f, USD( 0), 0, 0}, // Account is at the reserve, and will dip below once fees are subtracted. + {"bev", reserve(env, 0) + 1 * f, 1, noPreAuth, 1000, tecUNFUNDED_OFFER, f, USD( 0), 0, 0}, // Account has just enough for the reserve and the fee. + {"cam", reserve(env, 0) + 2 * f, 0, noPreAuth, 1000, tecINSUF_RESERVE_OFFER, f, USD( 0), 0, 0}, // Account has enough for the reserve, the fee and the offer, and a bit more, but not enough for the reserve after the offer is placed. + {"deb", reserve(env, 0) + 2 * f, 1, noPreAuth, 1000, tesSUCCESS, 2 * f, USD( 1), 0, 1, 100000}, // Account has enough to buy a little USD then the offer runs dry. + {"eve", reserve(env, 1) + 0 * f, 0, noPreAuth, 1000, tesSUCCESS, f, USD( 0), 1, 1}, // No offer to cross + {"flo", reserve(env, 1) + 0 * f, 1, noPreAuth, 1000, tesSUCCESS, XRP( 1) + f, USD( 1), 0, 1}, + {"gay", reserve(env, 1) + 1 * f, 1000, noPreAuth, 1000, tesSUCCESS, XRP( 50) + f, USD( 50), 0, 1}, + {"hye", XRP(1000) + 1 * f, 1000, noPreAuth, 1000, tesSUCCESS, XRP( 800) + f, USD( 800), 0, 1}, + {"ivy", XRP( 1) + reserve(env, 1) + 1 * f, 1, noPreAuth, 1000, tesSUCCESS, XRP( 1) + f, USD( 1), 0, 1}, + {"joy", XRP( 1) + reserve(env, 2) + 1 * f, 1, noPreAuth, 1000, tesSUCCESS, XRP( 1) + f, USD( 1), 1, 2}, + {"kim", XRP( 900) + reserve(env, 2) + 1 * f, 999, noPreAuth, 1000, tesSUCCESS, XRP( 999) + f, USD( 999), 0, 1}, + {"liz", XRP( 998) + reserve(env, 0) + 1 * f, 999, noPreAuth, 1000, tesSUCCESS, XRP( 998) + f, USD( 998), 0, 1}, + {"meg", XRP( 998) + reserve(env, 1) + 1 * f, 999, noPreAuth, 1000, tesSUCCESS, XRP( 999) + f, USD( 999), 0, 1}, + {"nia", XRP( 998) + reserve(env, 2) + 1 * f, 999, noPreAuth, 1000, tesSUCCESS, XRP( 999) + f, USD( 999), 1, 2}, + {"ova", XRP( 999) + reserve(env, 0) + 1 * f, 1000, noPreAuth, 1000, tesSUCCESS, XRP( 999) + f, USD( 999), 0, 1}, + {"pam", XRP( 999) + reserve(env, 1) + 1 * f, 1000, noPreAuth, 1000, tesSUCCESS, XRP(1000) + f, USD( 1000), 0, 1}, + {"rae", XRP( 999) + reserve(env, 2) + 1 * f, 1000, noPreAuth, 1000, tesSUCCESS, XRP(1000) + f, USD( 1000), 0, 1}, + {"sue", XRP(1000) + reserve(env, 2) + 1 * f, 0, noPreAuth, 1000, tesSUCCESS, f, USD( 0), 1, 1}, + //---------------- Pre-created MPT --------------------- + // Unlike from IOU, an issuer can't pre-create MPToken for an account (see similar tests in Offer_test.cpp) + {"ned", reserve(env, 1) + 0 * f, 1, acctPreAuth, 1000, tecUNFUNDED_OFFER, 2 * f, USD( 0), 0, 1}, + {"ole", reserve(env, 1) + 1 * f, 1, acctPreAuth, 1000, tecUNFUNDED_OFFER, 2 * f, USD( 0), 0, 1}, + {"pat", reserve(env, 1) + 2 * f, 0, acctPreAuth, 1000, tecUNFUNDED_OFFER, 2 * f, USD( 0), 0, 1}, + {"quy", reserve(env, 1) + 2 * f, 1, acctPreAuth, 1000, tecUNFUNDED_OFFER, 2 * f, USD( 0), 0, 1}, + {"ron", reserve(env, 1) + 3 * f, 0, acctPreAuth, 1000, tecINSUF_RESERVE_OFFER, 2 * f, USD( 0), 0, 1}, + {"syd", reserve(env, 1) + 3 * f, 1, acctPreAuth, 1000, tesSUCCESS, 3 * f, USD( 1), 0, 1, 100000}, + {"ted", XRP( 20) + reserve(env, 1) + 2 * f, 1000, acctPreAuth, 1000, tesSUCCESS, XRP(20) + 2 * f, USD( 20), 0, 1}, + {"uli", reserve(env, 2) + 0 * f, 0, acctPreAuth, 1000, tecINSUF_RESERVE_OFFER, 2 * f, USD( 0), 0, 1}, + {"vic", reserve(env, 2) + 0 * f, 1, acctPreAuth, 1000, tesSUCCESS, XRP( 1) + 2 * f, USD( 1), 0, 1}, + {"wes", reserve(env, 2) + 1 * f, 0, acctPreAuth, 1000, tesSUCCESS, 2 * f, USD( 0), 1, 2}, + {"xan", reserve(env, 2) + 1 * f, 1, acctPreAuth, 1000, tesSUCCESS, XRP( 1) + 2 * f, USD( 1), 1, 2}, + }; + // clang-format on + + for (auto const& t : tests) + { + auto const acct = Account(t.account); + env.fund(t.fundXrp, acct); + env.close(); + + // Make sure gateway has no current offers. + env.require(offers(gw, 0)); + + // The gateway optionally creates an offer that would be crossed. + auto const book = t.bookAmount; + if (book != 0) + env(offer(gw, XRP(book), USD(book * t.scale))); + env.close(); + std::uint32_t const gwOfferSeq = env.seq(gw) - 1; + + // Optionally pre-authorize MPT for acct. + // Note this is not really part of the test, so we expect there + // to be enough XRP reserve for acct to create the trust line. + if (t.preAuth == acctPreAuth) + MUSD.authorize({.account = acct}); + env.close(); + + { + // Acct creates an offer. This is the heart of the test. + auto const acctOffer = t.offerAmount; + env(offer(acct, USD(acctOffer * t.scale), XRP(acctOffer)), ter(t.tec)); + env.close(); + } + std::uint32_t const acctOfferSeq = env.seq(acct) - 1; + + auto const expBalanceUsd = [&]() { + if (t.scale == 1) + return t.balanceUsd; + // crossed offer has XRP available balance of 1 fee + // mpt to XRP ratio is 10 + return USD(f.value() / 10); + }(); + BEAST_EXPECT(env.balance(acct, USD) == expBalanceUsd); + BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); + env.require(offers(acct, t.offers)); + env.require(owners(acct, t.owners)); + + auto acctOffers = offersOnAccount(env, acct); + BEAST_EXPECT(acctOffers.size() == t.offers); + if (!acctOffers.empty() && t.offers != 0) + { + auto const& acctOffer = *(acctOffers.front()); + + auto const leftover = t.offerAmount - t.bookAmount; + BEAST_EXPECT(acctOffer[sfTakerGets] == XRP(leftover)); + BEAST_EXPECT(acctOffer[sfTakerPays] == USD(leftover)); + } + + if (t.preAuth == noPreAuth) + { + if (t.balanceUsd.value().signum() != 0) + { + // Verify the correct contents of MPT + BEAST_EXPECT(env.balance(acct, USD) == expBalanceUsd); + } + else + { + // Verify that no MPT was created. + auto const sle = env.le(keylet::mptoken(USD.issuanceID, acct)); + BEAST_EXPECT(!sle); + } + } + + // Give the next loop a clean slate by canceling any left-overs + // in the offers. + env(offer_cancel(acct, acctOfferSeq)); + env(offer_cancel(gw, gwOfferSeq)); + env.close(); + } + } + + void + testXRPDirectCross(FeatureBitset features) + { + testcase("XRP Direct Crossing"); + + using namespace jtx; + + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw, bob); + env.close(); + + // The fee that's charged for transactions. + auto const fee = env.current()->fees().base; + + // alice's account has enough for the reserve, one trust line plus two + // offers, and two fees. + env.fund(reserve(env, 2) + fee * 2, alice); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + auto const usdOffer = USD(1'000); + auto const xrpOffer = XRP(1'000); + + env(pay(gw, alice, usdOffer)); + env.close(); + env.require(balance(alice, usdOffer), offers(alice, 0), offers(bob, 0)); + + // The scenario: + // o alice has USD but wants XRP. + // o bob has XRP but wants USD. + auto const aliceXRP = env.balance(alice); + auto const bobsXRP = env.balance(bob); + + env(offer(alice, xrpOffer, usdOffer)); + env.close(); + env(offer(bob, usdOffer, xrpOffer)); + + env.close(); + env.require( + balance(alice, USD(0)), + balance(bob, usdOffer), + balance(alice, aliceXRP + xrpOffer - fee), + balance(bob, bobsXRP - xrpOffer - fee), + offers(alice, 0), + offers(bob, 0)); + + BEAST_EXPECT(env.balance(bob, USD) == usdOffer); + + // Make two more offers that leave one of the offers non-dry. + env(offer(alice, USD(999), XRP(999))); + env(offer(bob, xrpOffer, usdOffer)); + + env.close(); + env.require(balance(alice, USD(999))); + env.require(balance(bob, USD(1))); + env.require(offers(alice, 0)); + BEAST_EXPECT(env.balance(bob, USD) == USD(1)); + { + auto const bobsOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobsOffers.size() == 1); + auto const& bobsOffer = *(bobsOffers.front()); + + BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); + BEAST_EXPECT(bobsOffer[sfTakerPays] == XRP(1)); + } + } + + void + testDirectCross(FeatureBitset features) + { + testcase("Direct Crossing"); + + using namespace jtx; + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(1000000), gw); + env.close(); + + // The fee that's charged for transactions. + auto const fee = env.current()->fees().base; + + // Each account has enough for the reserve, two MPT's, one + // offer, and two fees. + env.fund(reserve(env, 3) + fee * 3, alice); + env.fund(reserve(env, 3) + fee * 2, bob); + env.close(); + + auto const USD = issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice}}); + auto const EUR = issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {bob}}); + + auto const usdOffer = USD(1'000); + auto const eurOffer = EUR(1'000); + + env(pay(gw, alice, usdOffer)); + env(pay(gw, bob, eurOffer)); + env.close(); + + env.require(balance(alice, usdOffer), balance(bob, eurOffer)); + + // The scenario: + // o alice has USD but wants EUR. + // o bob has EUR but wants USD. + env(offer(alice, eurOffer, usdOffer)); + env(offer(bob, usdOffer, eurOffer)); + + env.close(); + env.require( + balance(alice, eurOffer), balance(bob, usdOffer), offers(alice, 0), offers(bob, 0)); + + // Alice's offer crossing created a default EUR trustline and + // Bob's offer crossing created a default USD trustline: + BEAST_EXPECT(env.balance(alice, EUR) == eurOffer); + BEAST_EXPECT(env.balance(bob, USD) == usdOffer); + + // Make two more offers that leave one of the offers non-dry. + // Guarantee the order of application by putting a close() + // between them. + env(offer(bob, eurOffer, usdOffer)); + env.close(); + + env(offer(alice, USD(999), eurOffer)); + env.close(); + + env.require(offers(alice, 0)); + env.require(offers(bob, 1)); + + env.require(balance(alice, USD(999))); + env.require(balance(alice, EUR(1))); + env.require(balance(bob, USD(1))); + env.require(balance(bob, EUR(999))); + + { + auto bobsOffers = offersOnAccount(env, bob); + if (BEAST_EXPECT(bobsOffers.size() == 1)) + { + auto const& bobsOffer = *(bobsOffers.front()); + + BEAST_EXPECT(bobsOffer[sfTakerGets] == USD(1)); + BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(1)); + } + } + + // alice makes one more offer that cleans out bob's offer. + env(offer(alice, USD(1), EUR(1))); + env.close(); + + env.require(balance(alice, USD(1'000))); + env.require(balance(alice, EUR(none))); + env.require(balance(bob, USD(none))); + env.require(balance(bob, EUR(1'000))); + env.require(offers(alice, 0)); + env.require(offers(bob, 0)); + + // The two MPT that were generated by the offers still here + // Unlike IOU, MPToken is not automatically deleted + if constexpr (std::is_same_v, MPT>) + { + BEAST_EXPECT(env.le(keylet::mptoken(EUR.issuanceID, alice))); + auto MEUR = MPTTester(env, gw, EUR, {bob}); + // Delete created MPToken to free up reserve + MEUR.authorize({.account = alice, .flags = tfMPTUnauthorize}); + } + if constexpr (std::is_same_v, MPT>) + { + BEAST_EXPECT(env.le(keylet::mptoken(USD.issuanceID, bob))); + auto MUSD = MPTTester(env, gw, USD, {alice}); + // Delete created MPToken to free up reserve + MUSD.authorize({.account = bob, .flags = tfMPTUnauthorize}); + } + + // Make two more offers that leave one of the offers non-dry. We + // need to properly sequence the transactions: + env(offer(alice, EUR(999), usdOffer)); + env.close(); + + env(offer(bob, usdOffer, eurOffer)); + env.close(); + + env.require(offers(alice, 0)); + env.require(offers(bob, 0)); + + env.require(balance(alice, USD(0))); + env.require(balance(alice, EUR(999))); + env.require(balance(bob, USD(1'000))); + env.require(balance(bob, EUR(1))); + }; + testHelper2TokensMix(test); + } + + void + testBridgedCross(FeatureBitset features) + { + testcase("Bridged Crossing"); + + using namespace jtx; + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw, alice, bob, carol); + env.close(); + + auto const USD = issue1({.env = env, .token = "USD", .issuer = gw, .holders = {alice}}); + auto const EUR = issue2({.env = env, .token = "EUR", .issuer = gw, .holders = {carol}}); + + auto const usdOffer = USD(1'000); + auto const eurOffer = EUR(1'000); + + env(pay(gw, alice, usdOffer)); + env(pay(gw, carol, eurOffer)); + env.close(); + + // The scenario: + // o alice has USD but wants XRP. + // o bob has XRP but wants EUR. + // o carol has EUR but wants USD. + // Note that carol's offer must come last. If carol's offer is + // placed before bob's or alice's, then autobridging will not occur. + env(offer(alice, XRP(1'000), usdOffer)); + env(offer(bob, eurOffer, XRP(1'000))); + auto const bobXrpBalance = env.balance(bob); + env.close(); + + // carol makes an offer that partially consumes alice and bob's + // offers. + env(offer(carol, USD(400), EUR(400))); + env.close(); + + env.require( + balance(alice, USD(600)), + balance(bob, EUR(400)), + balance(carol, USD(400)), + balance(bob, bobXrpBalance - XRP(400)), + offers(carol, 0)); + BEAST_EXPECT(env.balance(bob, EUR) == EUR(400)); + BEAST_EXPECT(env.balance(carol, USD) == USD(400)); + { + auto const aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + auto const& aliceOffer = *(aliceOffers.front()); + + BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(aliceOffer[sfTakerGets] == USD(600)); + BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(600)); + } + { + auto const bobsOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobsOffers.size() == 1); + auto const& bobsOffer = *(bobsOffers.front()); + + BEAST_EXPECT(bobsOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(bobsOffer[sfTakerGets] == XRP(600)); + BEAST_EXPECT(bobsOffer[sfTakerPays] == EUR(600)); + } + + // carol makes an offer that exactly consumes alice and bob's + // offers. + env(offer(carol, USD(600), EUR(600))); + env.close(); + + env.require( + balance(alice, USD(0)), + balance(bob, eurOffer), + balance(carol, usdOffer), + balance(bob, bobXrpBalance - XRP(1'000)), + offers(bob, 0), + offers(carol, 0)); + BEAST_EXPECT(env.balance(bob, EUR) == EUR(1'000)); + BEAST_EXPECT(env.balance(carol, USD) == USD(1'000)); + + // In pre-flow code alice's offer is left empty in the ledger. + auto const aliceOffers = offersOnAccount(env, alice); + if (!aliceOffers.empty()) + { + BEAST_EXPECT(aliceOffers.size() == 1); + auto const& aliceOffer = *(aliceOffers.front()); + + BEAST_EXPECT(aliceOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(aliceOffer[sfTakerGets] == USD(0)); + BEAST_EXPECT(aliceOffer[sfTakerPays] == XRP(0)); + } + }; + testHelper2TokensMix(test); + } + + void + testSellOffer(FeatureBitset features) + { + // Test a number of different corner cases regarding offer crossing + // when the tfSell flag is set. The test is table driven so it + // should be easy to add or remove tests. + testcase("Sell Offer"); + + using namespace jtx; + + auto const gw = Account("gateway"); + + Env env{*this, features}; + + env.fund(XRP(10'000'000), gw); + + auto MUSD = MPTTester({.env = env, .issuer = gw}); + MPT const USD = MUSD; + + // The fee that's charged for transactions + auto const f = env.current()->fees().base; + + // To keep things simple all offers are 1 : 1 for XRP : USD. + struct TestData + { + std::string account; // Account operated on + STAmount fundXrp; // XRP acct funded with + STAmount fundUSD; // USD acct funded with + STAmount gwGets; // gw's offer + STAmount gwPays; // + STAmount acctGets; // acct's offer + STAmount acctPays; // + TER tec; // Returned tec code + STAmount spentXrp; // Amount removed from fundXrp + STAmount finalUsd; // Final USD balance on acct + int offers; // Offers on acct + int owners; // Owners on acct + STAmount takerGets; // Remainder of acct's offer + STAmount takerPays; // + + // Constructor with takerGets/takerPays + TestData( + std::string&& account_, // Account operated on + STAmount const& fundXrp_, // XRP acct funded with + STAmount const& fundUSD_, // USD acct funded with + STAmount const& gwGets_, // gw's offer + STAmount const& gwPays_, // + STAmount const& acctGets_, // acct's offer + STAmount const& acctPays_, // + TER tec_, // Returned tec code + STAmount const& spentXrp_, // Amount removed from fundXrp + STAmount const& finalUsd_, // Final USD balance on acct + int offers_, // Offers on acct + int owners_, // Owners on acct + STAmount const& takerGets_, // Remainder of acct's offer + STAmount const& takerPays_) // + : account(std::move(account_)) + , fundXrp(fundXrp_) + , fundUSD(fundUSD_) + , gwGets(gwGets_) + , gwPays(gwPays_) + , acctGets(acctGets_) + , acctPays(acctPays_) + , tec(tec_) + , spentXrp(spentXrp_) + , finalUsd(finalUsd_) + , offers(offers_) + , owners(owners_) + , takerGets(takerGets_) + , takerPays(takerPays_) + { + } + + // Constructor without takerGets/takerPays + TestData( + std::string&& account_, // Account operated on + STAmount const& fundXrp_, // XRP acct funded with + STAmount const& fundUSD_, // USD acct funded with + STAmount const& gwGets_, // gw's offer + STAmount const& gwPays_, // + STAmount const& acctGets_, // acct's offer + STAmount const& acctPays_, // + TER tec_, // Returned tec code + STAmount const& spentXrp_, // Amount removed from fundXrp + STAmount const& finalUsd_, // Final USD balance on acct + int offers_, // Offers on acct + int owners_) // Owners on acct + : TestData( + std::move(account_), + fundXrp_, + fundUSD_, + gwGets_, + gwPays_, + acctGets_, + acctPays_, + tec_, + spentXrp_, + finalUsd_, + offers_, + owners_, + STAmount{0}, + STAmount{0}) + { + } + }; + + // clang-format off + TestData const tests[]{ + // acct pays XRP + // acct fundXrp fundUSD gwGets gwPays acctGets acctPays tec spentXrp finalUSD offers owners takerGets takerPays + {"ann", XRP(10) + reserve(env, 0) + 1 * f, USD( 0), XRP(10), USD( 5), USD(10), XRP(10), tecINSUF_RESERVE_OFFER, XRP( 0) + (1 * f), USD( 0), 0, 0}, + {"bev", XRP(10) + reserve(env, 1) + 1 * f, USD( 0), XRP(10), USD( 5), USD(10), XRP(10), tesSUCCESS, XRP( 0) + (1 * f), USD( 0), 1, 1, XRP(10), USD(10)}, + {"cam", XRP(10) + reserve(env, 0) + 1 * f, USD( 0), XRP(10), USD(10), USD(10), XRP(10), tesSUCCESS, XRP( 10) + (1 * f), USD(10), 0, 1}, + {"deb", XRP(10) + reserve(env, 0) + 1 * f, USD( 0), XRP(10), USD(20), USD(10), XRP(10), tesSUCCESS, XRP( 10) + (1 * f), USD(20), 0, 1}, + {"eve", XRP(10) + reserve(env, 0) + 1 * f, USD( 0), XRP(10), USD(20), USD( 5), XRP( 5), tesSUCCESS, XRP( 5) + (1 * f), USD(10), 0, 1}, + {"flo", XRP(10) + reserve(env, 0) + 1 * f, USD( 0), XRP(10), USD(20), USD(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), USD(20), 0, 1}, + {"gay", XRP(20) + reserve(env, 1) + 1 * f, USD( 0), XRP(10), USD(20), USD(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), USD(20), 0, 1}, + {"hye", XRP(20) + reserve(env, 2) + 1 * f, USD( 0), XRP(10), USD(20), USD(20), XRP(20), tesSUCCESS, XRP( 10) + (1 * f), USD(20), 1, 2, XRP(10), USD(10)}, + // acct pays USD + {"meg", reserve(env, 1) + 2 * f, USD(10), USD(10), XRP( 5), XRP(10), USD(10), tecINSUF_RESERVE_OFFER, XRP( 0) + (2 * f), USD(10), 0, 1}, + {"nia", reserve(env, 2) + 2 * f, USD(10), USD(10), XRP( 5), XRP(10), USD(10), tesSUCCESS, XRP( 0) + (2 * f), USD(10), 1, 2, USD(10), XRP(10)}, + {"ova", reserve(env, 1) + 2 * f, USD(10), USD(10), XRP(10), XRP(10), USD(10), tesSUCCESS, XRP(-10) + (2 * f), USD( 0), 0, 1}, + {"pam", reserve(env, 1) + 2 * f, USD(10), USD(10), XRP(20), XRP(10), USD(10), tesSUCCESS, XRP(-20) + (2 * f), USD( 0), 0, 1}, + {"qui", reserve(env, 1) + 2 * f, USD(10), USD(20), XRP(40), XRP(10), USD(10), tesSUCCESS, XRP(-20) + (2 * f), USD( 0), 0, 1}, + {"rae", reserve(env, 2) + 2 * f, USD(10), USD( 5), XRP( 5), XRP(10), USD(10), tesSUCCESS, XRP( -5) + (2 * f), USD( 5), 1, 2, USD( 5), XRP( 5)}, + {"sue", reserve(env, 2) + 2 * f, USD(10), USD( 5), XRP(10), XRP(10), USD(10), tesSUCCESS, XRP(-10) + (2 * f), USD( 5), 1, 2, USD( 5), XRP( 5)}, + }; + // clang-format on + + auto const zeroUsd = USD(0); + for (auto const& t : tests) + { + // Make sure gateway has no current offers. + env.require(offers(gw, 0)); + + auto const acct = Account(t.account); + + env.fund(t.fundXrp, acct); + env.close(); + + // Optionally give acct some USD. This is not part of the test, + // so we assume that acct has sufficient USD to cover the reserve + // on the trust line. + if (t.fundUSD != zeroUsd) + { + MUSD.authorize({.account = acct}); + env.close(); + env(pay(gw, acct, t.fundUSD)); + env.close(); + } + + env(offer(gw, t.gwGets, t.gwPays)); + env.close(); + std::uint32_t const gwOfferSeq = env.seq(gw) - 1; + + // Acct creates a tfSell offer. This is the heart of the test. + env(offer(acct, t.acctGets, t.acctPays, tfSell), ter(t.tec)); + env.close(); + std::uint32_t const acctOfferSeq = env.seq(acct) - 1; + + // Check results + BEAST_EXPECT(env.balance(acct, USD) == t.finalUsd); + BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); + env.require(offers(acct, t.offers)); + env.require(owners(acct, t.owners)); + + if (t.offers != 0) + { + auto const acctOffers = offersOnAccount(env, acct); + if (!acctOffers.empty()) + { + BEAST_EXPECT(acctOffers.size() == 1); + auto const& acctOffer = *(acctOffers.front()); + + BEAST_EXPECT(acctOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(acctOffer[sfTakerGets] == t.takerGets); + BEAST_EXPECT(acctOffer[sfTakerPays] == t.takerPays); + } + } + + // Give the next loop a clean slate by canceling any left-overs + // in the offers. + env(offer_cancel(acct, acctOfferSeq)); + env(offer_cancel(gw, gwOfferSeq)); + env.close(); + } + } + + void + testSellWithFillOrKill(FeatureBitset features) + { + // Test a number of different corner cases regarding offer crossing + // when both the tfSell flag and tfFillOrKill flags are set. + testcase("Combine tfSell with tfFillOrKill"); + + using namespace jtx; + + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + Env env{*this, features}; + + env.fund(XRP(10'000'000), gw, alice, bob); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {bob}}); + + // bob offers XRP for USD. + env(pay(gw, bob, USD(100))); + env.close(); + env(offer(bob, XRP(2'000), USD(20))); + env.close(); + { + // alice submits a tfSell | tfFillOrKill offer that does not cross. + env(offer(alice, USD(21), XRP(2'100), tfSell | tfFillOrKill), ter(tecKILLED)); + env.close(); + env.require(balance(alice, USD(none))); + env.require(offers(alice, 0)); + env.require(balance(bob, USD(100))); + } + { + // alice submits a tfSell | tfFillOrKill offer that crosses. + // Even though tfSell is present it doesn't matter this time. + env(offer(alice, USD(20), XRP(2'000), tfSell | tfFillOrKill)); + env.close(); + env.require(balance(alice, USD(20))); + env.require(offers(alice, 0)); + env.require(balance(bob, USD(80))); + } + { + // alice submits a tfSell | tfFillOrKill offer that crosses and + // returns more than was asked for (because of the tfSell flag). + env(offer(bob, XRP(2'000), USD(20))); + env.close(); + env(offer(alice, USD(10), XRP(1'500), tfSell | tfFillOrKill)); + env.close(); + env.require(balance(alice, USD(35))); + env.require(offers(alice, 0)); + env.require(balance(bob, USD(65))); + } + { + // alice submits a tfSell | tfFillOrKill offer that doesn't cross. + // This would have succeeded with a regular tfSell, but the + // fillOrKill prevents the transaction from crossing since not + // all of the offer is consumed. + + // We're using bob's left-over offer for XRP(500), USD(5) + env(offer(alice, USD(1), XRP(501), tfSell | tfFillOrKill), ter(tecKILLED)); + env.close(); + env.require(balance(alice, USD(35))); + env.require(offers(alice, 0)); + env.require(balance(bob, USD(65))); + } + { + // Alice submits a tfSell | tfFillOrKill offer that finishes + // off the remainder of bob's offer. + + // We're using bob's left-over offer for XRP(500), USD(5) + env(offer(alice, USD(1), XRP(500), tfSell | tfFillOrKill)); + env.close(); + env.require(balance(alice, USD(40))); + env.require(offers(alice, 0)); + env.require(balance(bob, USD(60))); + } + } + + void + testTransferRateOffer(FeatureBitset features) + { + testcase("Transfer Rate Offer"); + + using namespace jtx; + auto const gw1 = Account("gateway1"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + // The fee that's charged for transactions. + auto const fee = env.current()->fees().base; + + env.fund(XRP(100'000), gw1); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = gw1, .transferFee = 25'000}); + using tUSD = std::decay_t; + { + auto const ann = Account("ann"); + auto const bob = Account("bob"); + env.fund(XRP(100) + reserve(env, 2) + (fee * 2), ann, bob); + env.close(); + + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = ann}); + MUSD.authorize({.account = bob}); + } + else + { + env(trust(ann, USD(20'000))); + env(trust(bob, USD(20'000))); + env.close(); + } + + env(pay(gw1, bob, USD(12'500))); + env.close(); + + // bob offers to sell USD(100) for XRP. alice takes bob's + // offer. Notice that although bob only offered USD(100), + // USD(125) was removed from his account due to the gateway fee. + // + // A comparable payment would look like this: + // env (pay (bob, alice, USD(100)), sendmax(USD(125))) + env(offer(bob, XRP(1), USD(10'000))); + env.close(); + + env(offer(ann, USD(10'000), XRP(1))); + env.close(); + + env.require(balance(ann, USD(10'000))); + env.require(balance(ann, XRP(99) + reserve(env, 2))); + env.require(offers(ann, 0)); + + env.require(balance(bob, USD(0))); + env.require(balance(bob, XRP(101) + reserve(env, 2))); + env.require(offers(bob, 0)); + } + { + // Reverse the order, so the offer in the books is to sell XRP + // in return for USD. Gateway rate should still apply + // identically. + auto const che = Account("che"); + auto const deb = Account("deb"); + env.fund(XRP(100) + reserve(env, 2) + (fee * 2), che, deb); + env.close(); + + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = che}); + MUSD.authorize({.account = deb}); + } + else + { + env(trust(che, USD(20'000))); + env(trust(deb, USD(20'000))); + env.close(); + } + + env(pay(gw1, deb, USD(12'500))); + env.close(); + + env(offer(che, USD(10'000), XRP(1))); + env.close(); + + env(offer(deb, XRP(1), USD(10'000))); + env.close(); + + env.require(balance(che, USD(10'000))); + env.require(balance(che, XRP(99) + reserve(env, 2))); + env.require(offers(che, 0)); + + env.require(balance(deb, USD(0))); + env.require(balance(deb, XRP(101) + reserve(env, 2))); + env.require(offers(deb, 0)); + } + { + auto const eve = Account("eve"); + auto const fyn = Account("fyn"); + + env.fund(XRP(20'000) + (fee * 2), eve, fyn); + env.close(); + + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = eve}); + MUSD.authorize({.account = fyn}); + } + else + { + env(trust(eve, USD(20'000))); + env(trust(fyn, USD(20'000))); + env.close(); + } + + env(pay(gw1, eve, USD(10'000))); + env(pay(gw1, fyn, USD(10'000))); + env.close(); + + // This test verifies that the amount removed from an offer + // accounts for the transfer fee that is removed from the + // account but not from the remaining offer. + env(offer(eve, USD(1'000), XRP(4'000))); + env.close(); + std::uint32_t const eveOfferSeq = env.seq(eve) - 1; + + env(offer(fyn, XRP(2'000), USD(500))); + env.close(); + + env.require(balance(eve, USD(10'500))); + env.require(balance(eve, XRP(18'000))); + auto const evesOffers = offersOnAccount(env, eve); + BEAST_EXPECT(evesOffers.size() == 1); + if (!evesOffers.empty()) + { + auto const& evesOffer = *(evesOffers.front()); + BEAST_EXPECT(evesOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(evesOffer[sfTakerGets] == XRP(2'000)); + BEAST_EXPECT(evesOffer[sfTakerPays] == USD(500)); + } + env(offer_cancel(eve, eveOfferSeq)); // For later tests + + env.require(balance(fyn, USD(9'375))); + env.require(balance(fyn, XRP(22'000))); + env.require(offers(fyn, 0)); + } + // Start messing with two non-native currencies. + auto const gw2 = Account("gateway2"); + + env.fund(XRP(100'000), gw2); + env.close(); + + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = gw2, .transferFee = 50'000}); + using tEUR = std::decay_t; + { + // Remove XRP from the equation. Give the two currencies two + // different transfer rates so we can see both transfer rates + // apply in the same transaction. + auto const gay = Account("gay"); + auto const hal = Account("hal"); + env.fund(reserve(env, 3) + (fee * 3), gay, hal); + env.close(); + + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = gay}); + MUSD.authorize({.account = hal}); + } + else + { + env(trust(gay, USD(20'000))); + env(trust(hal, USD(20'000))); + env.close(); + } + if constexpr (std::is_same_v) + { + auto MEUR = MPTTester(env, gw2, EUR); + MEUR.authorize({.account = gay}); + MEUR.authorize({.account = hal}); + } + else + { + env(trust(gay, EUR(20'000))); + env(trust(hal, EUR(20'000))); + env.close(); + } + + env(pay(gw1, gay, USD(12'500))); + env(pay(gw2, hal, EUR(150))); + env.close(); + + env(offer(gay, EUR(100), USD(10'000))); + env.close(); + + env(offer(hal, USD(10'000), EUR(100))); + env.close(); + + env.require(balance(gay, USD(0))); + env.require(balance(gay, EUR(100))); + env.require(balance(gay, reserve(env, 3))); + env.require(offers(gay, 0)); + + env.require(balance(hal, USD(10'000))); + env.require(balance(hal, EUR(0))); + env.require(balance(hal, reserve(env, 3))); + env.require(offers(hal, 0)); + } + + { + // Make sure things work right when we're auto-bridging as well. + auto const ova = Account("ova"); + auto const pat = Account("pat"); + auto const qae = Account("qae"); + env.fund(XRP(2) + reserve(env, 3) + (fee * 3), ova, pat, qae); + env.close(); + + // o ova has USD but wants XRP. + // o pat has XRP but wants EUR. + // o qae has EUR but wants USD. + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = ova}); + MUSD.authorize({.account = pat}); + MUSD.authorize({.account = qae}); + } + else + { + env(trust(ova, USD(20'000))); + env(trust(pat, USD(20'000))); + env(trust(qae, USD(20'000))); + env.close(); + } + if constexpr (std::is_same_v) + { + auto MEUR = MPTTester(env, gw2, EUR); + MEUR.authorize({.account = ova}); + MEUR.authorize({.account = pat}); + MEUR.authorize({.account = qae}); + } + else + { + env(trust(ova, EUR(20'000))); + env(trust(pat, EUR(20'000))); + env(trust(qae, EUR(20'000))); + env.close(); + } + + env(pay(gw1, ova, USD(12'500))); + env(pay(gw2, qae, EUR(150))); + env.close(); + + env(offer(ova, XRP(2), USD(10'000))); + env(offer(pat, EUR(100), XRP(2))); + env.close(); + + env(offer(qae, USD(10'000), EUR(100))); + env.close(); + + env.require(balance(ova, USD(0))); + env.require(balance(ova, EUR(0))); + env.require(balance(ova, XRP(4) + reserve(env, 3))); + + // In pre-flow code ova's offer is left empty in the ledger. + auto const ovasOffers = offersOnAccount(env, ova); + if (!ovasOffers.empty()) + { + BEAST_EXPECT(ovasOffers.size() == 1); + auto const& ovasOffer = *(ovasOffers.front()); + + BEAST_EXPECT(ovasOffer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(ovasOffer[sfTakerGets] == USD(0)); + BEAST_EXPECT(ovasOffer[sfTakerPays] == XRP(0)); + } + + env.require(balance(pat, USD(0))); + env.require(balance(pat, EUR(100))); + env.require(balance(pat, XRP(0) + reserve(env, 3))); + env.require(offers(pat, 0)); + + env.require(balance(qae, USD(10'000))); + env.require(balance(qae, EUR(0))); + env.require(balance(qae, XRP(2) + reserve(env, 3))); + env.require(offers(qae, 0)); + } + }; + testHelper2TokensMix(test); + } + + void + testSelfCrossOffer1(FeatureBitset features) + { + // The following test verifies some correct but slightly surprising + // behavior in offer crossing. The scenario: + // + // o An entity has created one or more offers. + // o The entity creates another offer that can be directly crossed + // (not autobridged) by the previously created offer(s). + // o Rather than self crossing the offers, delete the old offer(s). + // + // See a more complete explanation in the comments for + // BookOfferCrossingStep::limitSelfCrossQuality(). + // + // Note that, in this particular example, one offer causes several + // crossable offers (worth considerably more than the new offer) + // to be removed from the book. + using namespace jtx; + + auto const gw = Account("gateway"); + + Env env{*this, features}; + + // The fee that's charged for transactions. + auto const fee = env.current()->fees().base; + auto const startBalance = XRP(1'000'000); + + env.fund(startBalance + (fee * 5), gw); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw}); + + env(offer(gw, USD(60), XRP(600))); + env.close(); + env(offer(gw, USD(60), XRP(600))); + env.close(); + env(offer(gw, USD(60), XRP(600))); + env.close(); + + // three offers + MPTokenIssuance + env.require(owners(gw, 4)); + env.require(balance(gw, startBalance + fee)); + + auto gwOffers = offersOnAccount(env, gw); + BEAST_EXPECT(gwOffers.size() == 3); + for (auto const& offerPtr : gwOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == XRP(600)); + BEAST_EXPECT(offer[sfTakerPays] == USD(60)); + } + + // Since this offer crosses the first offers, the previous offers + // will be deleted and this offer will be put on the order book. + env(offer(gw, XRP(1'000), USD(100))); + env.close(); + env.require(owners(gw, 2)); + env.require(offers(gw, 1)); + env.require(balance(gw, startBalance)); + + gwOffers = offersOnAccount(env, gw); + BEAST_EXPECT(gwOffers.size() == 1); + for (auto const& offerPtr : gwOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == USD(100)); + BEAST_EXPECT(offer[sfTakerPays] == XRP(1'000)); + } + } + + void + testSelfCrossOffer2(FeatureBitset features) + { + using namespace jtx; + + auto const gw1 = Account("gateway1"); + auto const gw2 = Account("gateway2"); + auto const alice = Account("alice"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + env.fund(XRP(1'000'000), gw1, gw2); + env.close(); + + auto const USD = issue1({.env = env, .token = "USD", .issuer = gw1}); + using tUSD = std::decay_t; + auto const EUR = issue2({.env = env, .token = "EUR", .issuer = gw2}); + using tEUR = std::decay_t; + + // The fee that's charged for transactions. + auto const f = env.current()->fees().base; + + // Test cases + struct TestData + { + std::string acct; // Account operated on + STAmount fundXRP; // XRP acct funded with + STAmount fundUSD; // USD acct funded with + STAmount fundEUR; // EUR acct funded with + TER firstOfferTec; // tec code on first offer + TER secondOfferTec; // tec code on second offer + }; + + // clang-format off + TestData const tests[]{ + // acct fundXRP fundUSD fundEUR firstOfferTec secondOfferTec + {"ann", reserve(env, 3) + f * 4, USD(1000), EUR(1000), tesSUCCESS, tesSUCCESS}, + {"bev", reserve(env, 3) + f * 4, USD( 1), EUR(1000), tesSUCCESS, tesSUCCESS}, + {"cam", reserve(env, 3) + f * 4, USD(1000), EUR( 1), tesSUCCESS, tesSUCCESS}, + {"deb", reserve(env, 3) + f * 4, USD( 0), EUR( 1), tesSUCCESS, tecUNFUNDED_OFFER}, + {"eve", reserve(env, 3) + f * 4, USD( 1), EUR( 0), tecUNFUNDED_OFFER, tesSUCCESS}, + {"flo", reserve(env, 3) + 0, USD(1000), EUR(1000), tecINSUF_RESERVE_OFFER, tecINSUF_RESERVE_OFFER}, + }; + //clang-format on + + for (auto const& t : tests) + { + auto const acct = Account{t.acct}; + env.fund(t.fundXRP, acct); + env.close(); + + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw1, USD); + MUSD.authorize({.account = acct}); + } + else + { + env(trust(acct, USD(1'000))); + env.close(); + } + if constexpr (std::is_same_v) + { + auto MEUR = MPTTester(env, gw2, EUR); + MEUR.authorize({.account = acct}); + } + else + { + env(trust(acct, EUR(1'000))); + env.close(); + } + + if (t.fundUSD > USD(0)) + env(pay(gw1, acct, t.fundUSD)); + if (t.fundEUR > EUR(0)) + env(pay(gw2, acct, t.fundEUR)); + env.close(); + + env(offer(acct, USD(500), EUR(600)), ter(t.firstOfferTec)); + env.close(); + std::uint32_t const firstOfferSeq = env.seq(acct) - 1; + + int offerCount = t.firstOfferTec == tesSUCCESS ? 1 : 0; + env.require(owners(acct, 2 + offerCount)); + env.require(balance(acct, t.fundUSD)); + env.require(balance(acct, t.fundEUR)); + + auto acctOffers = offersOnAccount(env, acct); + BEAST_EXPECT(acctOffers.size() == offerCount); + for (auto const& offerPtr : acctOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == EUR(600)); + BEAST_EXPECT(offer[sfTakerPays] == USD(500)); + } + + env(offer(acct, EUR(600), USD(500)), ter(t.secondOfferTec)); + env.close(); + std::uint32_t const secondOfferSeq = env.seq(acct) - 1; + + offerCount = t.secondOfferTec == tesSUCCESS ? 1 : offerCount; + env.require(owners(acct, 2 + offerCount)); + env.require(balance(acct, t.fundUSD)); + env.require(balance(acct, t.fundEUR)); + + acctOffers = offersOnAccount(env, acct); + BEAST_EXPECT(acctOffers.size() == offerCount); + for (auto const& offerPtr : acctOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + if (offer[sfSequence] == firstOfferSeq) + { + BEAST_EXPECT(offer[sfTakerGets] == EUR(600)); + BEAST_EXPECT(offer[sfTakerPays] == USD(500)); + } + else + { + BEAST_EXPECT(offer[sfTakerGets] == USD(500)); + BEAST_EXPECT(offer[sfTakerPays] == EUR(600)); + } + } + + // Remove any offers from acct for the next pass. + env(offer_cancel(acct, firstOfferSeq)); + env.close(); + env(offer_cancel(acct, secondOfferSeq)); + env.close(); + } + }; + testHelper2TokensMix(test); + } + + void + testSelfCrossOffer(FeatureBitset features) + { + testcase("Self Cross Offer"); + testSelfCrossOffer1(features); + testSelfCrossOffer2(features); + } + + void + testSelfIssueOffer(FeatureBitset features) + { + // Folks who issue their own currency have, in effect, as many + // funds as they are trusted for. This test used to fail because + // self-issuing was not properly checked. Verify that it works + // correctly now. + using namespace jtx; + + Env env{*this, features}; + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const f = env.current()->fees().base; + + env.fund(XRP(50'000) + f, alice, bob); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = bob}); + + env(offer(alice, USD(5'000), XRP(50'000))); + env.close(); + + // This offer should take alice's offer up to Alice's reserve. + env(offer(bob, XRP(50'000), USD(5'000))); + env.close(); + + // alice's offer should have been removed, since she's down to her + // XRP reserve. + env.require(balance(alice, XRP(250))); + env.require(owners(alice, 1)); + env.require(mptokens(alice, 1)); + + // However bob's offer should be in the ledger, since it was not + // fully crossed. + auto const bobOffers = offersOnAccount(env, bob); + BEAST_EXPECT(bobOffers.size() == 1); + for (auto const& offerPtr : bobOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == USD(25)); + BEAST_EXPECT(offer[sfTakerPays] == XRP(250)); + } + } + + void + testDirectToDirectPath(FeatureBitset features) + { + // The offer crossing code expects that a DirectStep is always + // preceded by a BookStep. In one instance the default path + // was not matching that assumption. Here we recreate that case + // so we can prove the bug stays fixed. + testcase("Direct to Direct path"); + + using namespace jtx; + auto const ann = Account("ann"); + auto const bob = Account("bob"); + auto const cam = Account("cam"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + auto const fee = env.current()->fees().base; + env.fund(reserve(env, 4) + (fee * 5), ann, bob, cam); + env.close(); + + auto const A_BUX = issue1( + {.env = env, .token = "AUX", .issuer = ann, .holders = {cam}}); + auto const B_BUX = issue2( + {.env = env, + .token = "BUX", + .issuer = bob, + .holders = {ann, cam}}); + + env(pay(ann, cam, A_BUX(35))); + env(pay(bob, cam, B_BUX(35))); + + env(offer(bob, A_BUX(30), B_BUX(30))); + env.close(); + + // cam puts an offer on the books that her upcoming offer could + // cross. But this offer should be deleted, not crossed, by her + // upcoming offer. + env(offer(cam, A_BUX(29), B_BUX(30), tfPassive)); + env.close(); + env.require(balance(cam, A_BUX(35))); + env.require(balance(cam, B_BUX(35))); + env.require(offers(cam, 1)); + + // This offer caused the assert. + env(offer(cam, B_BUX(30), A_BUX(30))); + env.close(); + + env.require(balance(bob, A_BUX(30))); + env.require(balance(cam, A_BUX(5))); + env.require(balance(cam, B_BUX(65))); + env.require(offers(cam, 0)); + }; + testHelper2TokensMix(test); + } + + void + testSelfCrossLowQualityOffer(FeatureBitset features) + { + // The Flow offer crossing code used to assert if an offer was made + // for more XRP than the offering account held. This unit test + // reproduces that failing case. + testcase("Self crossing low quality offer"); + + using namespace jtx; + + Env env{*this, features}; + + auto const ann = Account("ann"); + auto const gw = Account("gateway"); + + auto const fee = env.current()->fees().base; + env.fund(reserve(env, 2) + drops(9999640) + (fee), ann); + env.fund(reserve(env, 2) + (fee * 4), gw); + env.close(); + + MPT const BTC = MPTTester( + {.env = env, .issuer = gw, .holders = {ann}, .transferFee = 2'000}); + + env(pay(gw, ann, BTC(2'856))); + env.close(); + + env(offer(ann, drops(365'611'702'030), BTC(5'713))); + env.close(); + + // This offer caused the assert. + env(offer(ann, BTC(687), drops(20'000'000'000)), + ter(tecINSUF_RESERVE_OFFER)); + } + + void + testOfferInScaling(FeatureBitset features) + { + // The Flow offer crossing code had a case where it was not rounding + // the offer crossing correctly after a partial crossing. The + // failing case was found on the network. Here we add the case to + // the unit tests. + testcase("Offer In Scaling"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + auto const fee = env.current()->fees().base; + env.fund(reserve(env, 2) + drops(400'000'000'000) + (fee), alice, bob); + env.fund(reserve(env, 2) + (fee * 4), gw); + env.close(); + + MPT const CNY = MPTTester({.env = env, .issuer = gw, .holders = {bob}}); + + env(pay(gw, bob, CNY(3'000'000))); + env.close(); + + env(offer(bob, drops(5'400'000'000), CNY(2'160'540))); + env.close(); + + // This offer did not round result of partial crossing correctly. + env(offer(alice, CNY(135'620'001), drops(339'000'000'000))); + env.close(); + + auto const aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + BEAST_EXPECT(offer[sfTakerGets] == drops(333'599'446'582)); + BEAST_EXPECT(offer[sfTakerPays] == CNY(13'3459'461)); + } + } + + void + testOfferInScalingWithXferRate(FeatureBitset features) + { + // After adding the previous case, there were still failing rounding + // cases in Flow offer crossing. This one was because the gateway + // transfer rate was not being correctly handled. + testcase("Offer In Scaling With Xfer Rate"); + + using namespace jtx; + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + + auto const fee = env.current()->fees().base; + env.fund( + reserve(env, 2) + drops(400'000'000'000) + fee, + alice, + bob); + env.fund(reserve(env, 2) + (fee * 4), gw); + env.close(); + + auto const JPY = issue1( + {.env = env, + .token = "JPY", + .issuer = gw, + .holders = {alice}, + .limit = maxMPTokenAmount, + .transferFee = 2'000}); + auto const BTC = issue2( + {.env = env, + .token = "BTC", + .issuer = gw, + .holders = {bob}, + .limit = maxMPTokenAmount, + .transferFee = 2'000}); + + env(pay(gw, alice, JPY(3'699'034'802'280'317))); + env(pay(gw, bob, BTC(115'672'255'914'031'100))); + env.close(); + + env(offer( + bob, JPY(1'241'913'390'770'747), BTC(1'969'825'690'469'254))); + env.close(); + + // This offer did not round result of partial crossing correctly. + env(offer( + alice, BTC(5'507'568'706'427'876), JPY(3'472'696'773'391'072))); + env.close(); + + auto const aliceOffers = offersOnAccount(env, alice); + BEAST_EXPECT(aliceOffers.size() == 1); + for (auto const& offerPtr : aliceOffers) + { + auto const& offer = *offerPtr; + BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); + // This test is similar to corresponding Offer_test, except + // that JPY is scaled by 10**12 and BTC is scaled by 10**17. + // There is a difference in the expected results. + // Offer_test expects values + // takerGets:2230.682446713524, takerPays: 0.035378 + // MPT test has the same order of magnitude for the scaled + // values and the first 5 digits match. Is the difference due to + // int arithmetics? + BEAST_EXPECT(offer[sfTakerGets] == JPY(2'230'659'191'281'247)); + BEAST_EXPECT(offer[sfTakerPays] == BTC(3'537'743'015'958'622)); + } + }; + testHelper2TokensMix(test); + } + + void + testSelfPayXferFeeOffer(FeatureBitset features) + { + testcase("Self Pay Xfer Fee"); + // The old offer crossing code does not charge a transfer fee + // if alice pays alice. That's different from how payments work. + // Payments always charge a transfer fee even if the money is staying + // in the same hands. + // + // What's an example where alice pays alice? There are three actors: + // gw, alice, and bob. + // + // 1. gw issues BTC and USD. gw charges a 0.2% transfer fee. + // + // 2. alice makes an offer to buy XRP and sell USD. + // 3. bob makes an offer to buy BTC and sell XRP. + // + // 4. alice now makes an offer to sell BTC and buy USD. + // + // This last offer crosses using auto-bridging. + // o alice's last offer sells BTC to... + // o bob' offer which takes alice's BTC and sells XRP to... + // o alice's first offer which takes bob's XRP and sells USD to... + // o alice's last offer. + // + // So alice sells USD to herself. + // + // There are six cases that we need to test: + // o alice crosses her own offer on the first leg (BTC). + // o alice crosses her own offer on the second leg (USD). + // o alice crosses her own offers on both legs. + // All three cases need to be tested: + // o In reverse (alice has enough BTC to cover her offer) and + // o Forward (alice owns less BTC than is in her final offer. + // + // It turns out that two of the forward cases fail for a different + // reason. They are therefore commented out here, But they are + // revisited in the testSelfPayUnlimitedFunds() unit test. + + using namespace jtx; + auto const gw = Account("gw"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + auto const baseFee = env.current()->fees().base.drops(); + + auto const startXrpBalance = XRP(4'000'000); + + env.fund(startXrpBalance, gw); + env.close(); + + auto const BTC = issue1( + {.env = env, + .token = "BTC", + .issuer = gw, + .transferFee = 25'000}); + using tBTC = std::decay_t; + env.close(); + auto const USD = issue2( + {.env = env, + .token = "USD", + .issuer = gw, + .transferFee = 25'000}); + using tUSD = std::decay_t; + env.close(); + + // Test cases + struct Actor + { + Account acct; + int offers{}; // offers on account after crossing + PrettyAmount xrp; // final expected after crossing + PrettyAmount btc; // final expected after crossing + PrettyAmount usd; // final expected after crossing + }; + struct TestData + { + // The first three integers give the *index* in actors + // to assign each of the three roles. By using indices it is + // easy for alice to own the offer in the first leg, the second + // leg, or both. + std::size_t self{}; + std::size_t leg0{}; + std::size_t leg1{}; + PrettyAmount btcStart; + std::vector actors; + }; + + // clang-format off + TestData const tests[]{ + // btcStart --------------------- actor[0] --------------------- -------------------- actor[1] ------------------- + {0, 0, 1, BTC(200), {{"ann", 0, drops(3900000'000000 - (4 * baseFee)), BTC(200), USD(3000)}, {"abe", 0, drops(4100000'000000 - (3 * baseFee)), BTC( 0), USD(750)}}}, // no BTC xfer fee + {0, 1, 0, BTC(200), {{"bev", 0, drops(4100000'000000 - (4 * baseFee)), BTC( 75), USD(2000)}, {"bob", 0, drops(3900000'000000 - (3 * baseFee)), BTC(100), USD( 0)}}}, // no USD xfer fee + {0, 0, 0, BTC(200), {{"cam", 0, drops(4000000'000000 - (5 * baseFee)), BTC(200), USD(2000)} }}, // no xfer fee + {0, 1, 0, BTC( 50), {{"deb", 1, drops(4040000'000000 - (4 * baseFee)), BTC( 0), USD(2000)}, {"dan", 1, drops(3960000'000000 - (3 * baseFee)), BTC( 40), USD( 0)}}}, // no USD xfer fee + }; + // clang-format on + + for (auto const& t : tests) + { + Account const& self = t.actors[t.self].acct; + Account const& leg0 = t.actors[t.leg0].acct; + Account const& leg1 = t.actors[t.leg1].acct; + + for (auto const& actor : t.actors) + { + env.fund(XRP(4'000'000), actor.acct); + env.close(); + + if constexpr (std::is_same_v) + { + auto MBTC = MPTTester(env, gw, BTC); + MBTC.authorize({.account = actor.acct}); + } + else + { + env(trust(actor.acct, BTC(400))); + env.close(); + } + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw, USD); + MUSD.authorize({.account = actor.acct}); + } + else + { + env(trust(actor.acct, USD(8000))); + env.close(); + } + env.close(); + } + + env(pay(gw, self, t.btcStart)); + env(pay(gw, self, USD(2'000))); + if (self.id() != leg1.id()) + env(pay(gw, leg1, USD(2'000))); + env.close(); + + // Get the initial offers in place. Remember their sequences + // so we can delete them later. + env(offer(leg0, BTC(100), XRP(100'000), tfPassive)); + env.close(); + std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1; + + env(offer(leg1, XRP(100'000), USD(1'000), tfPassive)); + env.close(); + std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1; + + // This is the offer that matters. + env(offer(self, USD(1'000), BTC(100))); + env.close(); + std::uint32_t const selfOfferSeq = env.seq(self) - 1; + + // Verify results. + for (auto const& actor : t.actors) + { + // Sometimes Taker crossing gets lazy about deleting offers. + // Treat an empty offer as though it is deleted. + auto actorOffers = offersOnAccount(env, actor.acct); + auto const offerCount = std::distance( + actorOffers.begin(), + std::remove_if( + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); + BEAST_EXPECT(offerCount == actor.offers); + + env.require(balance(actor.acct, actor.xrp)); + env.require(balance(actor.acct, actor.btc)); + env.require(balance(actor.acct, actor.usd)); + } + // Remove any offers that might be left hanging around. They + // could bollix up later loops. + env(offer_cancel(leg0, leg0OfferSeq)); + env.close(); + env(offer_cancel(leg1, leg1OfferSeq)); + env.close(); + env(offer_cancel(self, selfOfferSeq)); + env.close(); + } + }; + testHelper2TokensMix(test); + } + + void + testSelfPayUnlimitedFunds(FeatureBitset features) + { + testcase("Self Pay Unlimited Funds"); + // The Taker offer crossing code recognized when Alice was paying + // Alice the same denomination. In this case, as long as Alice + // has a little bit of that denomination, it treats Alice as though + // she has unlimited funds in that denomination. + // + // Huh? What kind of sense does that make? + // + // One way to think about it is to break a single payment into a + // series of very small payments executed sequentially but very + // quickly. Alice needs to pay herself 1 USD, but she only has + // 0.01 USD. Alice says, "Hey Alice, let me pay you a penny." + // Alice does this, taking the penny out of her pocket and then + // putting it back in her pocket. Then she says, "Hey Alice, + // I found another penny. I can pay you another penny." Repeat + // these steps 100 times and Alice has paid herself 1 USD even though + // she only owns 0.01 USD. + // + // That's all very nice, but the payment code does not support this + // optimization. In part that's because the payment code can + // operate on a whole batch of offers. As a matter of fact, it can + // deal in two consecutive batches of offers. It would take a great + // deal of sorting out to figure out which offers in the two batches + // had the same owner and give them special processing. And, + // honestly, it's a weird little corner case. + // + // So, since Flow offer crossing uses the payments engine, Flow + // offer crossing no longer supports this optimization. + // + // The following test shows the difference in the behaviors between + // Taker offer crossing and Flow offer crossing. + + using namespace jtx; + auto const gw = Account("gw"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env{*this, features}; + auto const baseFee = env.current()->fees().base.drops(); + + auto const startXrpBalance = XRP(4'000'000); + + env.fund(startXrpBalance, gw); + env.close(); + + auto const BTC = issue1( + {.env = env, .token = "BTC", .issuer = gw, .limit = 40, .transferFee = 25'000}); + using tBTC = std::decay_t; + auto const USD = issue2( + {.env = env, .token = "USD", .issuer = gw, .limit = 8'000, .transferFee = 25'000}); + using tUSD = std::decay_t; + env.close(); + + // Test cases + struct Actor + { + Account acct; + int offers{}; // offers on account after crossing + PrettyAmount xrp; // final expected after crossing + PrettyAmount btc; // final expected after crossing + PrettyAmount usd; // final expected after crossing + }; + struct TestData + { + // The first three integers give the *index* in actors + // to assign each of the three roles. By using indices it is + // easy for alice to own the offer in the first leg, the second + // leg, or both. + std::size_t self{}; + std::size_t leg0{}; + std::size_t leg1{}; + PrettyAmount btcStart; + std::vector actors; + }; + + // clang-format off + TestData const flowTests[]{ + // btcStart ------------------- actor[0] -------------------- ------------------- actor[1] -------------------- + {0, 0, 1, BTC(5), {{"gay", 1, drops(3950000'000000 - (4 * baseFee)), BTC(5), USD (2500)}, {"gar", 1, drops(4050000'000000 - (3 * baseFee)), BTC(0), USD(1375)}}}, // no BTC xfer fee + {0, 0, 0, BTC(5), {{"hye", 2, drops(4000000'000000 - (5 * baseFee)), BTC(5), USD (2000)} }} // no xfer fee + }; + // clang-format on + + for (auto const& t : flowTests) + { + Account const& self = t.actors[t.self].acct; + Account const& leg0 = t.actors[t.leg0].acct; + Account const& leg1 = t.actors[t.leg1].acct; + + for (auto const& actor : t.actors) + { + env.fund(XRP(4'000'000), actor.acct); + env.close(); + + if constexpr (std::is_same_v) + { + auto MBTC = MPTTester(env, gw, BTC); + MBTC.authorize({.account = actor.acct}); + } + else + { + env(trust(actor.acct, BTC(40))); + env.close(); + } + if constexpr (std::is_same_v) + { + auto MUSD = MPTTester(env, gw, USD); + MUSD.authorize({.account = actor.acct}); + } + else + { + env(trust(actor.acct, USD(8'000))); + env.close(); + } + } + + env(pay(gw, self, t.btcStart)); + env(pay(gw, self, USD(2'000))); + if (self.id() != leg1.id()) + env(pay(gw, leg1, USD(2'000))); + env.close(); + + // Get the initial offers in place. Remember their sequences + // so we can delete them later. + env(offer(leg0, BTC(10), XRP(100'000), tfPassive)); + env.close(); + std::uint32_t const leg0OfferSeq = env.seq(leg0) - 1; + + env(offer(leg1, XRP(100'000), USD(1'000), tfPassive)); + env.close(); + std::uint32_t const leg1OfferSeq = env.seq(leg1) - 1; + + // This is the offer that matters. + env(offer(self, USD(1'000), BTC(10))); + env.close(); + std::uint32_t const selfOfferSeq = env.seq(self) - 1; + + // Verify results. + for (auto const& actor : t.actors) + { + // Sometimes Taker offer crossing gets lazy about deleting + // offers. Treat an empty offer as though it is deleted. + auto actorOffers = offersOnAccount(env, actor.acct); + auto const offerCount = std::distance( + actorOffers.begin(), + std::remove_if( + actorOffers.begin(), + actorOffers.end(), + [](std::shared_ptr& offer) { + return (*offer)[sfTakerGets].signum() == 0; + })); + BEAST_EXPECT(offerCount == actor.offers); + + env.require(balance(actor.acct, actor.xrp)); + env.require(balance(actor.acct, actor.btc)); + env.require(balance(actor.acct, actor.usd)); + } + // Remove any offers that might be left hanging around. They + // could bollix up later loops. + env(offer_cancel(leg0, leg0OfferSeq)); + env.close(); + env(offer_cancel(leg1, leg1OfferSeq)); + env.close(); + env(offer_cancel(self, selfOfferSeq)); + env.close(); + } + }; + testHelper2TokensMix(test); + } + + void + testRequireAuth(FeatureBitset features) + { + testcase("lsfRequireAuth"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account("gw"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + env.fund(XRP(400'000), gw, alice, bob); + env.close(); + + // GW requires authorization for holders of its IOUs + auto gwMUSD = + MPTTester({.env = env, .issuer = gw, .flags = MPTDEXFlags | tfMPTRequireAuth}); + MPT const gwUSD = gwMUSD; + + // Have gw authorize bob and alice + gwMUSD.authorize({.account = alice}); + gwMUSD.authorize({.account = gw, .holder = alice}); + gwMUSD.authorize({.account = bob}); + gwMUSD.authorize({.account = gw, .holder = bob}); + // Alice is able to place the offer since the GW has authorized her + env(offer(alice, gwUSD(40), XRP(4'000))); + env.close(); + + env.require(offers(alice, 1)); + env.require(balance(alice, gwUSD(0))); + + env(pay(gw, bob, gwUSD(50))); + env.close(); + + env.require(balance(bob, gwUSD(50))); + + // Bob's offer should cross Alice's + env(offer(bob, XRP(4'000), gwUSD(40))); + env.close(); + + env.require(offers(alice, 0)); + env.require(balance(alice, gwUSD(40))); + + env.require(offers(bob, 0)); + env.require(balance(bob, gwUSD(10))); + } + + void + testMissingAuth(FeatureBitset features) + { + testcase("Missing Auth"); + // 1. gw creates MPTokenIssuance, which requires authorization. + // alice creates an offer to acquire USD/gw, an asset for which + // she does not own MPToken. This offer fails since alice + // doesn't own MPToken and authorization is required. + // + // 2. Next, alice creates MPT, but it's not authorized. + // alice attempts to create an offer and again fails. + // + // 3. Finally, gw authorizes alice to own USD/gw. + // At this point alice successfully + // creates and crosses an offer for USD/gw. + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account("gw"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + env.fund(XRP(400'000), gw, alice, bob); + env.close(); + + auto gwMUSD = + MPTTester({.env = env, .issuer = gw, .flags = MPTDEXFlags | tfMPTRequireAuth}); + MPT const gwUSD = gwMUSD; + + // alice can't create an offer because alice doesn't own + // MPToken and MPTokenIssuance requires authorization + env(offer(alice, gwUSD(40), XRP(4'000)), ter(tecNO_AUTH)); + env.close(); + + env.require(offers(alice, 0)); + env.require(balance(alice, gwUSD(none))); + + gwMUSD.authorize({.account = bob}); + gwMUSD.authorize({.account = gw, .holder = bob}); + + env(pay(gw, bob, gwUSD(50))); + env.close(); + env.require(balance(bob, gwUSD(50))); + + // bob can create an offer since bob owns MPToken + // and it is authorized. + env(offer(bob, XRP(4'000), gwUSD(40))); + env.close(); + std::uint32_t const bobOfferSeq = env.seq(bob) - 1; + + env.require(offers(alice, 0)); + + // alice creates MPToken, which is still not authorized. alice + // should still not be able to create an offer for USD/gw. + gwMUSD.authorize({.account = alice}); + + env(offer(alice, gwUSD(40), XRP(4'000)), ter(tecNO_AUTH)); + env.close(); + + env.require(offers(alice, 0)); + env.require(balance(alice, gwUSD(0))); + + env.require(offers(bob, 1)); + env.require(balance(bob, gwUSD(50))); + + // Delete bob's offer so alice can create an offer without crossing. + env(offer_cancel(bob, bobOfferSeq)); + env.close(); + env.require(offers(bob, 0)); + + // Finally, gw authorizes alice. Now alice's + // offer should succeed. + gwMUSD.authorize({.account = gw, .holder = alice}); + + env(offer(alice, gwUSD(40), XRP(4'000))); + env.close(); + + env.require(offers(alice, 1)); + + // Now bob creates his offer again. alice's offer should cross. + env(offer(bob, XRP(4'000), gwUSD(40))); + env.close(); + + env.require(offers(alice, 0)); + env.require(balance(alice, gwUSD(40))); + + env.require(offers(bob, 0)); + env.require(balance(bob, gwUSD(10))); + } + + void + testSelfAuth(FeatureBitset features) + { + testcase("Self Auth"); + + using namespace jtx; + + Env env{*this, features}; + + auto const gw = Account("gw"); + auto const alice = Account("alice"); + + env.fund(XRP(400'000), gw, alice); + env.close(); + + auto gwMUSD = + MPTTester({.env = env, .issuer = gw, .flags = MPTDEXFlags | tfMPTRequireAuth}); + MPT const gwUSD = gwMUSD; + + // Test that gw can create an offer to buy gw's currency. + env(offer(gw, gwUSD(40), XRP(4'000))); + env.close(); + std::uint32_t const gwOfferSeq = env.seq(gw) - 1; + env.require(offers(gw, 1)); + + // Cancel gw's offer + env(offer_cancel(gw, gwOfferSeq)); + env.close(); + env.require(offers(gw, 0)); + + // Before DepositPreauth an account with lsfRequireAuth set could not + // create an offer to buy their own currency. After DepositPreauth + // they can. + env(offer(gw, gwUSD(40), XRP(4'000))); + env.close(); + + env.require(offers(gw, 1)); + + // The rest of the test verifies DepositPreauth behavior. + + // Create/authorize alice's MPToken + gwMUSD.authorize({.account = alice}); + gwMUSD.authorize({.account = gw, .holder = alice}); + + env(pay(gw, alice, gwUSD(50))); + env.close(); + + env.require(balance(alice, gwUSD(50))); + + // alice's offer should cross gw's + env(offer(alice, XRP(4'000), gwUSD(40))); + env.close(); + + env.require(offers(alice, 0)); + env.require(balance(alice, gwUSD(10))); + + env.require(offers(gw, 0)); + } + + void + testDeletedOfferIssuer(FeatureBitset features) + { + // Show that an offer who's issuer has been deleted cannot be crossed. + using namespace jtx; + + testcase("Deleted offer issuer"); + + auto MPTokenExists = + [](jtx::Env const& env, AccountID const& account, MPTID const& issuanceID) -> bool { + return bool(env.le(keylet::mptoken(issuanceID, account))); + }; + + Account const alice("alice"); + Account const becky("becky"); + Account const carol("carol"); + Account const gw("gateway"); + + Env env{*this, features}; + + env.fund(XRP(10'000), alice, becky, carol, noripple(gw)); + + auto MUSD = MPTTester({.env = env, .issuer = gw}); + MPT const USD = MUSD; + + MUSD.authorize({.account = becky}); + BEAST_EXPECT(MPTokenExists(env, becky, USD.issuanceID)); + env(pay(gw, becky, USD(5))); + env.close(); + + auto MBUX = MPTTester({.env = env, .issuer = alice}); + MPT const BUX = MBUX; + + // Make offers that produce USD and can be crossed two ways: + // direct XRP -> USD + // direct BUX -> USD + env(offer(becky, XRP(2), USD(2)), txflags(tfPassive)); + std::uint32_t const beckyBuxUsdSeq{env.seq(becky)}; + env(offer(becky, BUX(3), USD(3)), txflags(tfPassive)); + env.close(); + + // becky keeps the offers, but removes MPT. + env(pay(becky, gw, USD(5))); + MUSD.authorize({.account = becky, .flags = tfMPTUnauthorize}); + + BEAST_EXPECT(!MPTokenExists(env, becky, USD.issuanceID)); + BEAST_EXPECT(isOffer(env, becky, XRP(2), USD(2))); + BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); + + // Have to delete MPTokenIssuance in order to delete + // the issuer account. + MUSD.destroy({}); + + // Delete gw's account. + { + // The ledger sequence needs to far enough ahead of the account + // sequence before the account can be deleted. + int const delta = [&env, &gw, openLedgerSeq = env.current()->seq()]() -> int { + std::uint32_t const gwSeq{env.seq(gw)}; + if (gwSeq + 255 > openLedgerSeq) + return gwSeq - openLedgerSeq + 255; + return 0; + }(); + + for (int i = 0; i < delta; ++i) + env.close(); + + // Account deletion has a high fee. Account for that. + env(acctdelete(gw, alice), fee(drops(env.current()->fees().increment))); + env.close(); + + // Verify that gw's account root is gone from the ledger. + BEAST_EXPECT(!env.closed()->exists(keylet::account(gw.id()))); + } + + // alice crosses becky's first offer. The offer create fails because + // the USD issuer is not in the ledger. + env(offer(alice, USD(2), XRP(2)), ter(tecNO_ISSUER)); + env.close(); + env.require(offers(alice, 0)); + BEAST_EXPECT(isOffer(env, becky, XRP(2), USD(2))); + BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); + + // alice crosses becky's second offer. Again, the offer create fails + // because the USD issuer is not in the ledger. + env(offer(alice, USD(3), BUX(3)), ter(tecNO_ISSUER)); + env.require(offers(alice, 0)); + BEAST_EXPECT(isOffer(env, becky, XRP(2), USD(2))); + BEAST_EXPECT(isOffer(env, becky, BUX(3), USD(3))); + + // Cancel becky's BUX -> USD offer so we can try auto-bridging. + env(offer_cancel(becky, beckyBuxUsdSeq)); + env.close(); + BEAST_EXPECT(!isOffer(env, becky, BUX(3), USD(3))); + + // alice creates an offer that can be auto-bridged with becky's + // remaining offer. + MBUX.authorize({.account = carol}); + env(pay(alice, carol, BUX(2))); + + env(offer(alice, BUX(2), XRP(2))); + env.close(); + + // carol attempts the auto-bridge. Again, the offer create fails + // because the USD issuer is not in the ledger. + env(offer(carol, USD(2), BUX(2)), ter(tecNO_ISSUER)); + env.close(); + BEAST_EXPECT(isOffer(env, alice, BUX(2), XRP(2))); + BEAST_EXPECT(isOffer(env, becky, XRP(2), USD(2))); + } + + // Helper function that returns offers on an account sorted by sequence. + static std::vector> + sortedOffersOnAccount(jtx::Env& env, jtx::Account const& acct) + { + std::vector> offers{offersOnAccount(env, acct)}; + std::sort( + offers.begin(), + offers.end(), + [](std::shared_ptr const& rhs, std::shared_ptr const& lhs) { + return (*rhs)[sfSequence] < (*lhs)[sfSequence]; + }); + return offers; + } + + void + testTicketOffer(FeatureBitset features) + { + testcase("Ticket Offers"); + + using namespace jtx; + + // Two goals for this test. + // + // o Verify that offers can be created using tickets. + // + // o Show that offers in the _same_ order book remain in + // chronological order regardless of sequence/ticket numbers. + Env env{*this, features}; + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + auto const bob = Account{"bob"}; + + env.fund(XRP(10'000), gw, alice, bob); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + env(pay(gw, alice, USD(200))); + env.close(); + + // Create four offers from the same account with identical quality + // so they go in the same order book. Each offer goes in a different + // ledger so the chronology is clear. + std::uint32_t const offerId_0{env.seq(alice)}; + env(offer(alice, XRP(50), USD(50))); + env.close(); + + // Create two tickets. + std::uint32_t const ticketSeq{env.seq(alice) + 1}; + env(ticket::create(alice, 2)); + env.close(); + + // Create another sequence-based offer. + std::uint32_t const offerId_1{env.seq(alice)}; + BEAST_EXPECT(offerId_1 == offerId_0 + 4); + env(offer(alice, XRP(50), USD(50))); + env.close(); + + // Create two ticket based offers in reverse order. + std::uint32_t const offerId_2{ticketSeq + 1}; + env(offer(alice, XRP(50), USD(50)), ticket::use(offerId_2)); + env.close(); + + // Create the last offer. + std::uint32_t const offerId_3{ticketSeq}; + env(offer(alice, XRP(50), USD(50)), ticket::use(offerId_3)); + env.close(); + + // Verify that all of alice's offers are present. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 4); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_0); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_3); + BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId_2); + BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerId_1); + env.require(balance(alice, USD(200))); + env.require(owners(alice, 5)); + } + + // Cross alice's first offer. + env(offer(bob, USD(50), XRP(50))); + env.close(); + + // Verify that the first offer alice created was consumed. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 3); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_2); + BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerId_1); + } + + // Cross alice's second offer. + env(offer(bob, USD(50), XRP(50))); + env.close(); + + // Verify that the second offer alice created was consumed. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 2); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerId_2); + } + + // Cross alice's third offer. + env(offer(bob, USD(50), XRP(50))); + env.close(); + + // Verify that the third offer alice created was consumed. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 1); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerId_3); + } + + // Cross alice's last offer. + env(offer(bob, USD(50), XRP(50))); + env.close(); + + // Verify that the third offer alice created was consumed. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.empty()); + } + env.require(balance(alice, USD(0))); + env.require(owners(alice, 1)); + env.require(balance(bob, USD(200))); + env.require(owners(bob, 1)); + } + + void + testTicketCancelOffer(FeatureBitset features) + { + testcase("Ticket Cancel Offers"); + + using namespace jtx; + + // Verify that offers created with or without tickets can be canceled + // by transactions with or without tickets. + Env env{*this, features}; + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + + env.fund(XRP(10'000), gw, alice); + env.close(); + + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice}}); + + env.require(owners(alice, 1), tickets(alice, 0)); + + env(pay(gw, alice, USD(200))); + env.close(); + + // Create the first of four offers using a sequence. + std::uint32_t const offerSeqId_0{env.seq(alice)}; + env(offer(alice, XRP(50), USD(50))); + env.close(); + env.require(owners(alice, 2), tickets(alice, 0)); + + // Create four tickets. + std::uint32_t const ticketSeq{env.seq(alice) + 1}; + env(ticket::create(alice, 4)); + env.close(); + env.require(owners(alice, 6), tickets(alice, 4)); + + // Create the second (also sequence-based) offer. + std::uint32_t const offerSeqId_1{env.seq(alice)}; + BEAST_EXPECT(offerSeqId_1 == offerSeqId_0 + 6); + env(offer(alice, XRP(50), USD(50))); + env.close(); + + // Create the third (ticket-based) offer. + std::uint32_t const offerTixId_0{ticketSeq + 1}; + env(offer(alice, XRP(50), USD(50)), ticket::use(offerTixId_0)); + env.close(); + + // Create the last offer. + std::uint32_t const offerTixId_1{ticketSeq}; + env(offer(alice, XRP(50), USD(50)), ticket::use(offerTixId_1)); + env.close(); + + // Verify that all of alice's offers are present. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 4); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId_0); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId_1); + BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerTixId_0); + BEAST_EXPECT(offers[3]->getFieldU32(sfSequence) == offerSeqId_1); + env.require(balance(alice, USD(200))); + env.require(owners(alice, 7)); + } + + // Use a ticket to cancel an offer created with a sequence. + env(offer_cancel(alice, offerSeqId_0), ticket::use(ticketSeq + 2)); + env.close(); + + // Verify that offerSeqId_0 was canceled. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 3); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId_1); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerTixId_0); + BEAST_EXPECT(offers[2]->getFieldU32(sfSequence) == offerSeqId_1); + } + + // Use a ticket to cancel an offer created with a ticket. + env(offer_cancel(alice, offerTixId_0), ticket::use(ticketSeq + 3)); + env.close(); + + // Verify that offerTixId_0 was canceled. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 2); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerTixId_1); + BEAST_EXPECT(offers[1]->getFieldU32(sfSequence) == offerSeqId_1); + } + + // All of alice's tickets should now be used up. + env.require(owners(alice, 3), tickets(alice, 0)); + + // Use a sequence to cancel an offer created with a ticket. + env(offer_cancel(alice, offerTixId_1)); + env.close(); + + // Verify that offerTixId_1 was canceled. + { + auto offers = sortedOffersOnAccount(env, alice); + BEAST_EXPECT(offers.size() == 1); + BEAST_EXPECT(offers[0]->getFieldU32(sfSequence) == offerSeqId_1); + } + + // Use a sequence to cancel an offer created with a sequence. + env(offer_cancel(alice, offerSeqId_1)); + env.close(); + + // Verify that offerSeqId_1 was canceled. + // All of alice's tickets should now be used up. + env.require(owners(alice, 1), tickets(alice, 0), offers(alice, 0)); + } + + void + testFillOrKill(FeatureBitset features) + { + testcase("fixFillOrKill"); + using namespace jtx; + Account const issuer("issuer"); + Account const maker("maker"); + Account const taker("taker"); + + auto test = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(1'000), issuer); + env.fund(XRP(1'000), maker, taker); + env.close(); + + auto const USD = + issue1({.env = env, .token = "USD", .issuer = issuer, .holders = {maker, taker}}); + auto const EUR = + issue2({.env = env, .token = "EUR", .issuer = issuer, .holders = {maker, taker}}); + + env(pay(issuer, maker, USD(1'000))); + env(pay(issuer, taker, USD(1'000))); + env(pay(issuer, maker, EUR(1'000))); + env.close(); + + auto makerUSDBalance = env.balance(maker, USD).value(); + auto takerUSDBalance = env.balance(taker, USD).value(); + auto makerEURBalance = env.balance(maker, EUR).value(); + auto takerEURBalance = env.balance(taker, EUR).value(); + auto makerXRPBalance = env.balance(maker, XRP).value(); + auto takerXRPBalance = env.balance(taker, XRP).value(); + + // tfFillOrKill, TakerPays must be filled + { + TER const err = features[fixFillOrKill] ? TER(tesSUCCESS) : tecKILLED; + + env(offer(maker, XRP(100), USD(100))); + env.close(); + + env(offer(taker, USD(100), XRP(101)), txflags(tfFillOrKill), ter(err)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + if (err == tesSUCCESS) + { + makerUSDBalance -= USD(100); + takerUSDBalance += USD(100); + makerXRPBalance += XRP(100).value(); + takerXRPBalance -= XRP(100).value(); + } + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(100), XRP(100))); + env.close(); + + env(offer(taker, XRP(100), USD(101)), txflags(tfFillOrKill), ter(err)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + if (err == tesSUCCESS) + { + makerUSDBalance += USD(100); + takerUSDBalance -= USD(100); + makerXRPBalance -= XRP(100).value(); + takerXRPBalance += XRP(100).value(); + } + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(100), EUR(100))); + env.close(); + + env(offer(taker, EUR(100), USD(101)), txflags(tfFillOrKill), ter(err)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + if (err == tesSUCCESS) + { + makerUSDBalance += USD(100); + takerUSDBalance -= USD(100); + makerEURBalance -= EUR(100); + takerEURBalance += EUR(100); + } + BEAST_EXPECT(expectOffers(env, taker, 0)); + } + + // tfFillOrKill + tfSell, TakerGets must be filled + { + env(offer(maker, XRP(101), USD(101))); + env.close(); + + env(offer(taker, USD(100), XRP(101)), txflags(tfFillOrKill | tfSell)); + env.close(); + + makerUSDBalance -= USD(101); + takerUSDBalance += USD(101); + makerXRPBalance += XRP(101).value() - txfee(env, 1); + takerXRPBalance -= XRP(101).value() + txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(101), XRP(101))); + env.close(); + + env(offer(taker, XRP(100), USD(101)), txflags(tfFillOrKill | tfSell)); + env.close(); + + makerUSDBalance += USD(101); + takerUSDBalance -= USD(101); + makerXRPBalance -= XRP(101).value() + txfee(env, 1); + takerXRPBalance += XRP(101).value() - txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(101), EUR(101))); + env.close(); + + env(offer(taker, EUR(100), USD(101)), txflags(tfFillOrKill | tfSell)); + env.close(); + + makerUSDBalance += USD(101); + takerUSDBalance -= USD(101); + makerEURBalance -= EUR(101); + takerEURBalance += EUR(101); + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + } + + // Fail regardless of fixFillOrKill amendment + for (auto const flags : {tfFillOrKill, tfFillOrKill + tfSell}) + { + env(offer(maker, XRP(100), USD(100))); + env.close(); + + env(offer(taker, USD(100), XRP(99)), txflags(flags), ter(tecKILLED)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(100), XRP(100))); + env.close(); + + env(offer(taker, XRP(100), USD(99)), txflags(flags), ter(tecKILLED)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + + env(offer(maker, USD(100), EUR(100))); + env.close(); + + env(offer(taker, EUR(100), USD(99)), txflags(flags), ter(tecKILLED)); + env.close(); + + makerXRPBalance -= txfee(env, 1); + takerXRPBalance -= txfee(env, 1); + BEAST_EXPECT(expectOffers(env, taker, 0)); + } + + BEAST_EXPECT( + env.balance(maker, USD) == makerUSDBalance && + env.balance(taker, USD) == takerUSDBalance && + env.balance(maker, EUR) == makerEURBalance && + env.balance(taker, EUR) == takerEURBalance && + env.balance(maker, XRP) == makerXRPBalance && + env.balance(taker, XRP) == takerXRPBalance); + }; + testHelper2TokensMix(test); + } + + void + testTickSize(FeatureBitset features) + { + testcase("Tick Size"); + + using namespace jtx; + + auto const gw = Account{"gateway"}; + auto const alice = Account{"alice"}; + + auto getIOU = [&](Env& env) -> PrettyAsset { + static int i = 0; + std::string const name = "IO" + std::to_string(i++); + auto const iou = gw[name]; + env(trust(alice, iou(1'000))); + env(pay(gw, alice, iou(100))); + env.close(); + return iou; + }; + auto getMPT = [&](Env& env) -> PrettyAsset { + MPT const mpt = + MPTTester({.env = env, .issuer = gw, .holders = {alice}, .pay = 1'000'000'000}); + return mpt; + }; + auto getXRP = [&](Env& env) -> PrettyAsset { return XRP; }; + + using ToAsset = std::function; + struct TestInfo + { + ToAsset toAsset1; + ToAsset toAsset2; + int val1; + int val2; + }; + // XRP/MPT, MPT/XRP, MPT/MPT offers are not adjusted for TickSize + // IOU/IOU, XRP/IOU, IOU/XRP offers have TickSize logic unchanged + // IOU/MPT, MPT/IOU have TickSize logic applied to adjust IOU only + std::vector const tests = { + {getIOU, getIOU, 10, 30}, + {getIOU, getXRP, 10, 30'000'000}, + {getXRP, getIOU, 10'000'000, 30}, + {getMPT, getXRP, 10'000'000, 30'000'000}, + {getXRP, getMPT, 10'000'000, 30'000'000}, + {getIOU, getMPT, 10, 30'000'000}, + {getMPT, getIOU, 10'000'000, 30}, + {getMPT, getMPT, 10'000'000, 30'000'000}}; + for (TestInfo const& t : tests) + { + Env env{*this, features}; + env.fund(XRP(10'000), gw, alice); + env.close(); + + auto const XTS = t.toAsset1(env); + auto const XXX = t.toAsset2(env); + + auto tokenType = [](PrettyAsset const& asset) -> std::string { + return asset.raw().visit( + [&](Issue const& issue) { return issue.native() ? "XRPIssue" : "Issue"; }, + [&](MPTIssue const&) { return "MPTIssue"; }); + }; + + testcase << "offer: " << tokenType(XTS) << "/" << tokenType(XXX); + + { + // Gateway sets its tick size to 5 + auto txn = noop(gw); + txn[sfTickSize.fieldName] = 5; + env(txn); + BEAST_EXPECT((*env.le(gw))[sfTickSize] == 5); + } + + env(offer(alice, XTS(t.val1), XXX(t.val2))); + env(offer(alice, XTS(t.val2), XXX(t.val1))); + env(offer(alice, XTS(t.val1), XXX(t.val2)), json(jss::Flags, tfSell)); + env(offer(alice, XTS(t.val2), XXX(t.val1)), json(jss::Flags, tfSell)); + + std::map> offers; + forEachItem(*env.current(), alice, [&](std::shared_ptr const& sle) { + if (sle->getType() == ltOFFER) + { + offers.emplace( + (*sle)[sfSequence], + std::make_pair((*sle)[sfTakerPays], (*sle)[sfTakerGets])); + } + }); + + // first offer + auto it = offers.begin(); + BEAST_EXPECT(it != offers.end()); + if (XXX.native() && !XTS.holds()) + { + BEAST_EXPECT( + it->second.first == XTS(t.val1) && it->second.second == XRPAmount(29'999'400)); + } + else if (!XXX.integral()) + { + BEAST_EXPECT( + it->second.first == XTS(t.val1) && it->second.second < XXX(t.val2) && + it->second.second > STAmount(XXX, 29'9994, -4)); + } + else + { + BEAST_EXPECT(it->second.first == XTS(t.val1) && it->second.second == XXX(t.val2)); + } + + // second offer + ++it; + BEAST_EXPECT(it != offers.end()); + BEAST_EXPECT(it->second.first == XTS(t.val2) && it->second.second == XXX(t.val1)); + + // third offer + ++it; + BEAST_EXPECT(it != offers.end()); + if (XTS.native() && !XXX.holds()) + { + BEAST_EXPECT( + it->second.first == XRPAmount(10'000'200) && it->second.second == XXX(t.val2)); + } + else if (!XTS.integral()) + { + BEAST_EXPECT( + it->second.first == STAmount(XTS, 10'0002, -4) && + it->second.second == XXX(t.val2)); + } + else + { + BEAST_EXPECT(it->second.first == XTS(t.val1) && it->second.second == XXX(t.val2)); + } + + // fourth offer + // exact TakerPays is XTS(1/.033333) + ++it; + BEAST_EXPECT(it != offers.end()); + BEAST_EXPECT(it->second.first == XTS(t.val2) && it->second.second == XXX(t.val1)); + + BEAST_EXPECT(++it == offers.end()); + } + } + + void + testAll(FeatureBitset features) + { + testCanceledOffer(features); + testRmFundedOffer(features); + testTinyPayment(features); + testXRPTinyPayment(features); + testInsufficientReserve(features); + testFillModes(features); + testMalformed(features); + testExpiration(features); + testUnfundedCross(features); + testSelfCross(false, features); + testSelfCross(true, features); + testNegativeBalance(features); + testOfferCrossWithXRP(true, features); + testOfferCrossWithXRP(false, features); + testOfferCrossWithLimitOverride(features); + testOfferAcceptThenCancel(features); + testCurrencyConversionEntire(features); + testCurrencyConversionIntoDebt(features); + testCurrencyConversionInParts(features); + testCrossCurrencyStartXRP(features); + testCrossCurrencyEndXRP(features); + testCrossCurrencyBridged(features); + testBridgedSecondLegDry(features); + testOfferFeesConsumeFunds(features); + testOfferCreateThenCross(features); + testSellFlagBasic(features); + testSellFlagExceedLimit(features); + testGatewayCrossCurrency(features); + testPartialCross(features); + testXRPDirectCross(features); + testDirectCross(features); + testBridgedCross(features); + testSellOffer(features); + testSellWithFillOrKill(features); + testTransferRateOffer(features); + testSelfCrossOffer(features); + testSelfIssueOffer(features); + testDirectToDirectPath(features); + testSelfCrossLowQualityOffer(features); + testOfferInScaling(features); + testOfferInScalingWithXferRate(features); + testSelfPayXferFeeOffer(features); + testSelfPayUnlimitedFunds(features); + testRequireAuth(features); + testMissingAuth(features); + testSelfAuth(features); + testDeletedOfferIssuer(features); + testTicketOffer(features); + testTicketCancelOffer(features); + testRmSmallIncreasedQOffersXRP(features); + testRmSmallIncreasedQOffersMPT(features); + testFillOrKill(features); + testTickSize(features); + } + + void + run() override + { + using namespace jtx; + static FeatureBitset const all{testable_amendments()}; + testAll(all); + } +}; + +BEAST_DEFINE_TESTSUITE_PRIO(OfferMPT, tx, xrpl, 2); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/Offer_test.cpp b/src/test/app/Offer_test.cpp index ad6ec656cb..1aeeb728f2 100644 --- a/src/test/app/Offer_test.cpp +++ b/src/test/app/Offer_test.cpp @@ -420,7 +420,7 @@ public: auto tinyAmount = [&](IOU const& iou) -> PrettyAmount { STAmount const amt( - iou.issue(), + iou, /*mantissa*/ 1, /*exponent*/ -81); return PrettyAmount(amt, iou.account.name()); @@ -709,7 +709,7 @@ public: // Helper function that returns the Offers on an account. static std::vector> - offersOnAccount(jtx::Env& env, jtx::Account account) + offersOnAccount(jtx::Env& env, jtx::Account const& account) { std::vector> result; forEachItem(*env.current(), account, [&result](std::shared_ptr const& sle) { @@ -1203,7 +1203,6 @@ public: BEAST_EXPECT(jrr[jss::offers].isArray()); BEAST_EXPECT(jrr[jss::offers].size() == 0); - // NOTE : // At this point, all offers are expected to be consumed. { auto acctOffers = offersOnAccount(env, account_to_test); @@ -1279,7 +1278,7 @@ public: auto const gw_initial_balance = drops(1149999730); auto const alice_initial_balance = drops(499946999680); auto const bob_initial_balance = drops(10199999920); - auto const small_amount = STAmount{bob["USD"].issue(), UINT64_C(2710505431213761), -33}; + auto const small_amount = STAmount{bob["USD"], UINT64_C(2710505431213761), -33}; env.fund(gw_initial_balance, gw); env.fund(alice_initial_balance, alice); @@ -2136,18 +2135,18 @@ public: jtx::Account const& account, jtx::PrettyAmount const& expectBalance) { - auto const sleTrust = env.le(keylet::line(account.id(), expectBalance.value().issue())); + Issue const& issue = expectBalance.value().get(); + auto const sleTrust = env.le(keylet::line(account.id(), issue)); BEAST_EXPECT(sleTrust); if (sleTrust) { - Issue const issue = expectBalance.value().issue(); bool const accountLow = account.id() < issue.account; STAmount low{issue}; STAmount high{issue}; - low.setIssuer(accountLow ? account.id() : issue.account); - high.setIssuer(accountLow ? issue.account : account.id()); + low.get().account = (accountLow ? account.id() : issue.account); + high.get().account = (accountLow ? issue.account : account.id()); BEAST_EXPECT(sleTrust->getFieldAmount(sfLowLimit) == low); BEAST_EXPECT(sleTrust->getFieldAmount(sfHighLimit) == high); @@ -2278,7 +2277,7 @@ public: } std::uint32_t const acctOfferSeq = env.seq(acct) - 1; - BEAST_EXPECT(env.balance(acct, USD.issue()) == t.balanceUsd); + BEAST_EXPECT(env.balance(acct, USD) == t.balanceUsd); BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); @@ -2304,7 +2303,7 @@ public: else { // Verify that no trustline was created. - auto const sleTrust = env.le(keylet::line(acct, USD.issue())); + auto const sleTrust = env.le(keylet::line(acct, USD)); BEAST_EXPECT(!sleTrust); } } @@ -2489,8 +2488,8 @@ public: env.require(offers(bob, 0)); // The two trustlines that were generated by offers should be gone. - BEAST_EXPECT(!env.le(keylet::line(alice.id(), EUR.issue()))); - BEAST_EXPECT(!env.le(keylet::line(bob.id(), USD.issue()))); + BEAST_EXPECT(!env.le(keylet::line(alice.id(), EUR))); + BEAST_EXPECT(!env.le(keylet::line(bob.id(), USD))); // Make two more offers that leave one of the offers non-dry. We // need to properly sequence the transactions: @@ -2768,7 +2767,7 @@ public: std::uint32_t const acctOfferSeq = env.seq(acct) - 1; // Check results - BEAST_EXPECT(env.balance(acct, USD.issue()) == t.finalUsd); + BEAST_EXPECT(env.balance(acct, USD) == t.finalUsd); BEAST_EXPECT(env.balance(acct, xrpIssue()) == t.fundXrp - t.spentXrp); env.require(offers(acct, t.offers)); env.require(owners(acct, t.owners)); @@ -3675,7 +3674,7 @@ public: BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT( offer[sfTakerGets] == - STAmount(JPY.issue(), std::uint64_t(2230682446713524ul), -12)); + STAmount(JPY, std::uint64_t(2230682446713524ul), -12)); BEAST_EXPECT(offer[sfTakerPays] == BTC(0.035378)); } } @@ -3712,24 +3711,24 @@ public: env( pay(gw1, alice, - STAmount{USD.issue(), std::uint64_t(2185410179555600), -14})); + STAmount{USD, std::uint64_t(2185410179555600), -14})); env( pay(gw2, bob, - STAmount{JPY.issue(), std::uint64_t(6351823459548956), -12})); + STAmount{JPY, std::uint64_t(6351823459548956), -12})); env.close(); env(offer( bob, - STAmount{USD.issue(), std::uint64_t(4371257532306000), -17}, - STAmount{JPY.issue(), std::uint64_t(4573216636606000), -15})); + STAmount{USD, std::uint64_t(4371257532306000), -17}, + STAmount{JPY, std::uint64_t(4573216636606000), -15})); env.close(); // This offer did not partially cross correctly. env(offer( alice, - STAmount{JPY.issue(), std::uint64_t(2291181510070762), -12}, - STAmount{USD.issue(), std::uint64_t(2190218999914694), -14})); + STAmount{JPY, std::uint64_t(2291181510070762), -12}, + STAmount{USD, std::uint64_t(2190218999914694), -14})); env.close(); auto const aliceOffers = offersOnAccount(env, alice); @@ -3740,10 +3739,10 @@ public: BEAST_EXPECT(offer[sfLedgerEntryType] == ltOFFER); BEAST_EXPECT( offer[sfTakerGets] == - STAmount(USD.issue(), std::uint64_t(2185847305256635), -14)); + STAmount(USD, std::uint64_t(2185847305256635), -14)); BEAST_EXPECT( offer[sfTakerPays] == - STAmount(JPY.issue(), std::uint64_t(2286608293434156), -12)); + STAmount(JPY, std::uint64_t(2286608293434156), -12)); } } @@ -3772,21 +3771,21 @@ public: // Place alice's tiny offer in the book first. Let's see what happens // when a reasonable offer crosses it. STAmount const aliceCnyOffer{ - CNY.issue(), std::uint64_t(4926000000000000), -23}; + CNY, std::uint64_t(4926000000000000), -23}; env(offer(alice, aliceCnyOffer, drops(1), tfPassive)); env.close(); // bob places an ordinary offer STAmount const bobCnyStartBalance{ - CNY.issue(), std::uint64_t(3767479960090235), -15}; + CNY, std::uint64_t(3767479960090235), -15}; env(pay(gw, bob, bobCnyStartBalance)); env.close(); env(offer( bob, drops(203), - STAmount{CNY.issue(), std::uint64_t(1000000000000000), -20})); + STAmount{CNY, std::uint64_t(1000000000000000), -20})); env.close(); env.require(balance(alice, aliceCnyOffer)); diff --git a/src/test/app/PathMPT_test.cpp b/src/test/app/PathMPT_test.cpp new file mode 100644 index 0000000000..9562f1478f --- /dev/null +++ b/src/test/app/PathMPT_test.cpp @@ -0,0 +1,443 @@ +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace xrpl { +namespace test { +namespace detail { + +static Json::Value +rpf(jtx::Account const& src, + jtx::Account const& dst, + xrpl::test::jtx::MPT const& USD, + std::vector const& num_src) +{ + Json::Value jv = Json::objectValue; + jv[jss::command] = "ripple_path_find"; + jv[jss::source_account] = toBase58(src); + + if (!num_src.empty()) + { + auto& sc = (jv[jss::source_currencies] = Json::arrayValue); + Json::Value j = Json::objectValue; + for (auto const& id : num_src) + { + j[jss::mpt_issuance_id] = to_string(id); + sc.append(j); + } + } + + auto const d = toBase58(dst); + jv[jss::destination_account] = d; + + Json::Value& j = (jv[jss::destination_amount] = Json::objectValue); + j[jss::mpt_issuance_id] = to_string(USD.mpt()); + j[jss::value] = "1"; + + return jv; +} + +} // namespace detail + +//------------------------------------------------------------------------------ + +class PathMPT_test : public beast::unit_test::suite +{ + jtx::Env + pathTestEnv() + { + // These tests were originally written with search parameters that are + // different from the current defaults. This function creates an env + // with the search parameters that the tests were written for. + using namespace jtx; + return Env(*this, envconfig([](std::unique_ptr cfg) { + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; + return cfg; + })); + } + +public: + void + source_currencies_limit() + { + testcase("source currency limits"); + using namespace std::chrono_literals; + using namespace jtx; + Env env = pathTestEnv(); + auto const gw = Account("gateway"); + auto const alice = Account("alice"); + auto const bob = Account("bob"); + + env.fund(XRP(10'000), "alice", "bob", gw); + + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 100}); + + auto& app = env.app(); + Resource::Charge loadType = Resource::feeReferenceRPC; + Resource::Consumer c; + + RPC::JsonContext context{ + {env.journal, + app, + loadType, + app.getOPs(), + app.getLedgerMaster(), + c, + Role::USER, + {}, + {}, + RPC::apiVersionIfUnspecified}, + {}, + {}}; + Json::Value result; + gate g; + // Test RPC::Tuning::max_src_cur source currencies. + std::vector num_src; + num_src.reserve(RPC::Tuning::max_src_cur); + for (std::uint8_t i = 0; i < RPC::Tuning::max_src_cur; ++i) + num_src.push_back(makeMptID(i, bob)); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = xrpl::test::detail::rpf(alice, bob, USD, num_src); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); + BEAST_EXPECT(g.wait_for(5s)); + BEAST_EXPECT(!result.isMember(jss::error)); + + // Test more than RPC::Tuning::max_src_cur source currencies. + num_src.push_back(makeMptID(RPC::Tuning::max_src_cur, bob)); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = xrpl::test::detail::rpf(alice, bob, USD, num_src); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); + BEAST_EXPECT(g.wait_for(5s)); + BEAST_EXPECT(result.isMember(jss::error)); + + // Test RPC::Tuning::max_auto_src_cur source currencies. + num_src.clear(); + for (auto i = 0; i < (RPC::Tuning::max_auto_src_cur - 1); ++i) + { + auto CURM = MPTTester({.env = env, .issuer = alice, .holders = {bob}}); + num_src.push_back(CURM.issuanceID()); + } + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = xrpl::test::detail::rpf(alice, bob, USD, {}); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); + BEAST_EXPECT(g.wait_for(5s)); + BEAST_EXPECT(!result.isMember(jss::error)); + + // Test more than RPC::Tuning::max_auto_src_cur source currencies. + auto CURM = MPTTester({.env = env, .issuer = alice, .holders = {bob}}); + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = xrpl::test::detail::rpf(alice, bob, USD, {}); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); + BEAST_EXPECT(g.wait_for(5s)); + BEAST_EXPECT(result.isMember(jss::error)); + } + + void + no_direct_path_no_intermediary_no_alternatives() + { + testcase("no direct path no intermediary no alternatives"); + using namespace jtx; + + Env env = pathTestEnv(); + + env.fund(XRP(10'000), "alice", "bob"); + + auto USDM = MPTTester({.env = env, .issuer = "bob"}); + + auto const result = find_paths(env, "alice", "bob", USDM(5)); + BEAST_EXPECT(std::get<0>(result).empty()); + } + + void + direct_path_no_intermediary() + { + testcase("direct path no intermediary"); + using namespace jtx; + Env env = pathTestEnv(); + env.fund(XRP(10'000), "alice", "bob"); + + MPT const USD = MPTTester({.env = env, .issuer = "alice", .holders = {"bob"}}); + + STPathSet st; + STAmount sa; + std::tie(st, sa, std::ignore) = find_paths(env, "alice", "bob", USD(5)); + BEAST_EXPECT(st.empty()); + BEAST_EXPECT(equal(sa, USD(5))); + } + + void + payment_auto_path_find() + { + testcase("payment auto path find"); + using namespace jtx; + Env env = pathTestEnv(); + auto const gw = Account("gateway"); + env.fund(XRP(10'000), "alice", "bob", gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {"alice", "bob"}}); + env(pay(gw, "alice", USD(70))); + env(pay("alice", "bob", USD(24))); + env.require(balance("alice", USD(46))); + env.require(balance("bob", USD(24))); + } + + void + path_find(bool const domainEnabled) + { + testcase(std::string("path find") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + using namespace jtx; + Env env = pathTestEnv(); + auto const gw = Account("gateway"); + env.fund(XRP(10'000), "alice", "bob", gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {"alice", "bob"}}); + env(pay(gw, "alice", USD(70))); + env(pay(gw, "bob", USD(50))); + + std::optional domainID; + if (domainEnabled) + domainID = setupDomain(env, {"alice", "bob", gw}); + + STPathSet st; + STAmount sa; + STAmount da; + std::tie(st, sa, da) = find_paths( + env, "alice", "bob", USD(5), std::nullopt, std::nullopt, std::nullopt, domainID); + // Note, a direct IOU payment will have "gateway" as alternative path + // since IOU supports rippling + BEAST_EXPECT(st.empty()); + BEAST_EXPECT(equal(sa, USD(5))); + BEAST_EXPECT(equal(da, USD(5))); + } + + void + path_find_consume_all(bool const domainEnabled) + { + testcase( + std::string("path find consume all") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + using namespace jtx; + + { + Env env = pathTestEnv(); + auto const gw = Account("gateway"); + env.fund(XRP(10'000), "alice", "bob", "carol", gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {"bob", "carol"}}); + MPT const AUD(makeMptID(0, gw)); + env(pay(gw, "carol", USD(100))); + std::optional domainID; + if (domainEnabled) + { + domainID = setupDomain(env, {"alice", "bob", "carol", "gateway"}); + env(offer("carol", XRP(100), USD(100)), domain(*domainID)); + } + else + { + env(offer("carol", XRP(100), USD(100))); + } + env.close(); + + STPathSet st; + STAmount sa; + STAmount da; + std::tie(st, sa, da) = find_paths( + env, + "alice", + "bob", + AUD(-1), + std::optional(XRP(100'000'000)), + std::nullopt, + std::nullopt, + domainID); + BEAST_EXPECT(st.empty()); + std::tie(st, sa, da) = find_paths( + env, + "alice", + "bob", + USD(-1), + std::optional(XRP(100'000'000)), + std::nullopt, + std::nullopt, + domainID); + if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) + { + auto const& pathElem = st[0][0]; + BEAST_EXPECT( + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && + pathElem.getMPTID() == USD.issuanceID); + } + BEAST_EXPECT(sa == XRP(100)); + BEAST_EXPECT(equal(da, USD(100))); + + // if domain is used, finding path in the open offerbook will return + // empty result + if (domainEnabled) + { + std::tie(st, sa, da) = find_paths( + env, + "alice", + "bob", + Account("bob")["USD"](-1), + std::optional(XRP(1000000)), + std::nullopt, + std::nullopt); // not specifying a domain + BEAST_EXPECT(st.empty()); + } + } + } + + void + alternative_paths_consume_best_transfer(bool const domainEnabled) + { + testcase( + std::string("alternative path consume best transfer") + + (domainEnabled ? " w/ " : " w/o ") + "domain"); + using namespace jtx; + Env env = pathTestEnv(); + auto const gw = Account("gateway"); + auto const gw2 = Account("gateway2"); + env.fund(XRP(10'000), "alice", "bob", gw, gw2); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {"alice", "bob"}}); + MPT const gw2_USD = MPTTester( + {.env = env, .issuer = gw2, .holders = {"alice", "bob"}, .transferFee = 1'000}); + std::optional domainID; + if (domainEnabled) + { + domainID = setupDomain(env, {"alice", "bob", "gateway", "gateway2"}); + env(pay(gw, "alice", USD(70)), domain(*domainID)); + env(pay(gw2, "alice", gw2_USD(70)), domain(*domainID)); + env(pay("alice", "bob", USD(70)), domain(*domainID)); + } + else + { + env(pay(gw, "alice", USD(70))); + env(pay(gw2, "alice", gw2_USD(70))); + env(pay("alice", "bob", USD(70))); + } + env.require(balance("alice", USD(0))); + env.require(balance("alice", gw2_USD(70))); + env.require(balance("bob", USD(70))); + env.require(balance("bob", gw2_USD(0))); + } + + void + receive_max(bool const domainEnabled) + { + testcase(std::string("Receive max") + (domainEnabled ? " w/ " : " w/o ") + "domain"); + using namespace jtx; + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const charlie = Account("charlie"); + auto const gw = Account("gw"); + { + // XRP -> MPT receive max + Env env = pathTestEnv(); + env.fund(XRP(10'000), alice, bob, charlie, gw); + env.close(); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, charlie}}); + env(pay(gw, charlie, USD(10))); + env.close(); + std::optional domainID; + if (domainEnabled) + { + domainID = setupDomain(env, {alice, bob, charlie, gw}); + env(offer(charlie, XRP(10), USD(10)), domain(*domainID)); + } + else + { + env(offer(charlie, XRP(10), USD(10))); + } + env.close(); + auto [st, sa, da] = find_paths( + env, alice, bob, USD(-1), XRP(100).value(), std::nullopt, std::nullopt, domainID); + BEAST_EXPECT(sa == XRP(10)); + BEAST_EXPECT(equal(da, USD(10))); + if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) + { + auto const& pathElem = st[0][0]; + BEAST_EXPECT( + pathElem.isOffer() && pathElem.getIssuerID() == gw.id() && + pathElem.getMPTID() == USD.mpt()); + } + } + { + // MPT -> XRP receive max + Env env = pathTestEnv(); + env.fund(XRP(10'000), alice, bob, charlie, gw); + env.close(); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob, charlie}}); + env(pay(gw, alice, USD(10))); + env.close(); + std::optional domainID; + if (domainEnabled) + { + domainID = setupDomain(env, {alice, bob, charlie, gw}); + env(offer(charlie, USD(10), XRP(10)), domain(*domainID)); + } + else + { + env(offer(charlie, USD(10), XRP(10))); + } + env.close(); + auto [st, sa, da] = find_paths( + env, alice, bob, drops(-1), USD(100).value(), std::nullopt, std::nullopt, domainID); + BEAST_EXPECT(sa == USD(10)); + BEAST_EXPECT(equal(da, XRP(10))); + if (BEAST_EXPECT(st.size() == 1 && st[0].size() == 1)) + { + auto const& pathElem = st[0][0]; + BEAST_EXPECT( + pathElem.isOffer() && pathElem.getIssuerID() == xrpAccount() && + pathElem.getCurrency() == xrpCurrency()); + } + } + } + + void + run() override + { + source_currencies_limit(); + no_direct_path_no_intermediary_no_alternatives(); + direct_path_no_intermediary(); + payment_auto_path_find(); + for (auto const domainEnabled : {false, true}) + { + path_find(domainEnabled); + path_find_consume_all(domainEnabled); + alternative_paths_consume_best_transfer(domainEnabled); + receive_max(domainEnabled); + } + } +}; + +BEAST_DEFINE_TESTSUITE(PathMPT, app, xrpl); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/Path_test.cpp b/src/test/app/Path_test.cpp index 841847d183..7e7354c9ee 100644 --- a/src/test/app/Path_test.cpp +++ b/src/test/app/Path_test.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include @@ -16,12 +17,9 @@ #include #include -#include -#include #include #include #include -#include namespace xrpl { namespace test { @@ -848,7 +846,7 @@ public: })", jv); - auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) + auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"])) ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); @@ -890,15 +888,14 @@ public: })", jv); - auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) + auto const jv_l = env.le(keylet::line(Account("bob").id(), Account("alice")["USD"])) ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env.trust(Account("bob")["USD"](0), "alice"); env.trust(Account("alice")["USD"](0), "bob"); - BEAST_EXPECT( - env.le(keylet::line(Account("bob").id(), Account("alice")["USD"].issue())) == nullptr); + BEAST_EXPECT(env.le(keylet::line(Account("bob").id(), Account("alice")["USD"])) == nullptr); } void @@ -941,14 +938,13 @@ public: })", jv); - auto const jv_l = env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) + auto const jv_l = env.le(keylet::line(Account("alice").id(), Account("bob")["USD"])) ->getJson(JsonOptions::none); for (auto it = jv.begin(); it != jv.end(); ++it) BEAST_EXPECT(*it == jv_l[it.memberName()]); env(pay("alice", "bob", Account("alice")["USD"](50))); - BEAST_EXPECT( - env.le(keylet::line(Account("alice").id(), Account("bob")["USD"].issue())) == nullptr); + BEAST_EXPECT(env.le(keylet::line(Account("alice").id(), Account("bob")["USD"])) == nullptr); } void diff --git a/src/test/app/PayStrandMPT_test.cpp b/src/test/app/PayStrandMPT_test.cpp new file mode 100644 index 0000000000..cfeeaa5d35 --- /dev/null +++ b/src/test/app/PayStrandMPT_test.cpp @@ -0,0 +1,627 @@ +#include + +#include +#include +#include +#include + +namespace xrpl { +namespace test { + +struct PayStrandMPT_test : public beast::unit_test::suite +{ + static jtx::DirectStepInfo + makeEndpointStep(jtx::Account const& src, jtx::Account const& dst, jtx::IOU const& iou) + { + return jtx::DirectStepInfo{src, dst, iou.currency}; + } + static jtx::MPTEndpointStepInfo + makeEndpointStep(jtx::Account const& src, jtx::Account const& dst, jtx::MPT const& mpt) + { + return jtx::MPTEndpointStepInfo{src, dst, mpt.mpt()}; + } + + void + testToStrand(FeatureBitset features) + { + testcase("To Strand"); + + using namespace jtx; + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + auto const gw = Account("gw"); + + using M = MPTEndpointStepInfo; + using B = xrpl::Book; + using XRPS = XRPEndpointStepInfo; + + AMMContext ammContext(alice, false); + + auto test = [&, this]( + jtx::Env& env, + Asset const& deliver, + std::optional const& sendMaxIssue, + STPath const& path, + TER expTer, + auto&&... expSteps) { + auto [ter, strand] = toStrand( + *env.current(), + alice, + bob, + deliver, + std::nullopt, + sendMaxIssue, + path, + true, + OfferCrossing::no, + ammContext, + std::nullopt, + env.app().getLogs().journal("Flow")); + BEAST_EXPECT(ter == expTer); + if (sizeof...(expSteps) != 0) + BEAST_EXPECT(jtx::equal(strand, std::forward(expSteps)...)); + }; + + { + auto testMultiToken = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, gw); + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 1'000}); + auto const bobUSD = issue1( + {.env = env, + .token = "USD", + .issuer = bob, + .holders = {alice}, + .limit = 1'000}); + MPT const EUR = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 1'000}); + auto const bobEUR = issue2( + {.env = env, + .token = "EUR", + .issuer = bob, + .holders = {alice}, + .limit = 1'000}); + env(pay(gw, alice, EUR(100))); + + { + // Original test is + // STPath({ipe(bob["USD"]), cpe(EUR.currency)}); + // which ripples through same currency, different issuer. + // This results in 5 steps: + // 1 DirectStep alice -> gw EUR/gw + // 2 Book EUR/gw USD/bob + // 3 Book USD/bob EUR/bob + // 4 Book EUR/bob XRP + // 5 XRPEndpoint + // This is somewhat equivalent path with MPT + STPath const path = STPath({ipe(bobUSD), ipe(bobEUR), cpe(xrpCurrency())}); + auto [ter, _] = toStrand( + *env.current(), + alice, + alice, + /*deliver*/ xrpIssue(), + /*limitQuality*/ std::nullopt, + /*sendMaxIssue*/ EUR, + path, + true, + OfferCrossing::no, + ammContext, + std::nullopt, + env.app().getLogs().journal("Flow")); + (void)_; + BEAST_EXPECT(ter == tesSUCCESS); + } + { + STPath const path = STPath({ipe(USD), cpe(xrpCurrency())}); + auto [ter, _] = toStrand( + *env.current(), + alice, + alice, + /*deliver*/ xrpIssue(), + /*limitQuality*/ std::nullopt, + /*sendMaxIssue*/ EUR, + path, + true, + OfferCrossing::no, + ammContext, + std::nullopt, + env.app().getLogs().journal("Flow")); + (void)_; + BEAST_EXPECT(ter == tesSUCCESS); + } + }; + testHelper2TokensMix(testMultiToken); + } + { + auto testMultiToken = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, carol, gw); + auto USD = issue1({.env = env, .token = "USD", .issuer = gw, .limit = 1'000}); + using tUSD = std::decay_t; + auto EUR = issue2({.env = env, .token = "EUR", .issuer = gw, .limit = 1'000}); + using tEUR = std::decay_t; + + auto const err = [&]() { + if constexpr (std::is_same_v) + { + return tecNO_AUTH; + } + else + { + return terNO_LINE; + } + }(); + test(env, USD, std::nullopt, STPath(), err); + + if constexpr (std::is_same_v) + { + MPTTester(env, gw, USD).authorizeHolders({alice, bob, carol}); + } + else + { + env.trust(USD(1'000), alice, bob, carol); + } + + test(env, USD, std::nullopt, STPath(), tecPATH_DRY); + + env(pay(gw, alice, USD(100))); + env(pay(gw, carol, USD(100))); + + // Insert implied account + test( + env, + USD, + std::nullopt, + STPath(), + tesSUCCESS, + makeEndpointStep(alice, gw, USD), + makeEndpointStep(gw, bob, USD)); + if constexpr (std::is_same_v) + { + MPTTester(env, gw, EUR).authorizeHolders({alice, bob}); + } + else + { + env.trust(EUR(1'000), alice, bob); + } + + // Insert implied offer + test( + env, + EUR, + USD, + STPath(), + tesSUCCESS, + makeEndpointStep(alice, gw, USD), + B{USD, EUR, std::nullopt}, + makeEndpointStep(gw, bob, EUR)); + + // Path with explicit offer + test( + env, + EUR, + USD, + STPath({ipe(EUR)}), + tesSUCCESS, + makeEndpointStep(alice, gw, USD), + B{USD, EUR, std::nullopt}, + makeEndpointStep(gw, bob, EUR)); + + // Path with XRP src currency + test( + env, + USD, + xrpIssue(), + STPath({ipe(USD)}), + tesSUCCESS, + XRPS{alice}, + B{XRP, USD, std::nullopt}, + makeEndpointStep(gw, bob, USD)); + + // Path with XRP dst currency. + test( + env, + xrpIssue(), + USD, + STPath({STPathElement{ + STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), + tesSUCCESS, + makeEndpointStep(alice, gw, USD), + B{USD, XRP, std::nullopt}, + XRPS{bob}); + + // Path with XRP cross currency bridged payment + test( + env, + EUR, + USD, + STPath({cpe(xrpCurrency())}), + tesSUCCESS, + makeEndpointStep(alice, gw, USD), + B{USD, XRP, std::nullopt}, + B{XRP, EUR, std::nullopt}, + makeEndpointStep(gw, bob, EUR)); + + // Create an offer with the same in/out issue + test(env, EUR, USD, STPath({ipe(USD), ipe(EUR)}), temBAD_PATH); + + // The same offer can't appear more than once on a path + test(env, EUR, USD, STPath({ipe(EUR), ipe(USD), ipe(EUR)}), temBAD_PATH_LOOP); + }; + testHelper2TokensMix(testMultiToken); + } + + { + // cannot have more than one offer with the same output issue + + using namespace jtx; + + auto testMultiToken = [&](auto&& issue1, auto&& issue2) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000}); + + env(pay(gw, bob, USD(100))); + env(pay(gw, bob, EUR(100))); + + env(offer(bob, XRP(100), USD(100))); + env(offer(bob, USD(100), EUR(100)), txflags(tfPassive)); + env(offer(bob, EUR(100), USD(100)), txflags(tfPassive)); + + // payment path: XRP -> XRP/USD -> USD/EUR -> EUR/USD + env(pay(alice, carol, USD(100)), + path(~USD, ~EUR, ~USD), + sendmax(XRP(200)), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper2TokensMix(testMultiToken); + } + + { + // check global freeze + Env env(*this, features); + env.fund(XRP(10000), alice, bob, gw); + auto USDM = MPTTester( + {.env = env, + .issuer = gw, + .holders = {alice, bob}, + .flags = MPTDEXFlags | tfMPTCanLock, + .maxAmt = 1'000}); + MPT const USD = USDM; + env(pay(gw, alice, USD(100))); + + // Account can't issue payments + USDM.set({.holder = alice, .flags = tfMPTLock}); + test(env, USD, std::nullopt, STPath(), terLOCKED); + USDM.set({.holder = alice, .flags = tfMPTUnlock}); + test(env, USD, std::nullopt, STPath(), tesSUCCESS); + + // Account can not issue funds + USDM.set({.flags = tfMPTLock}); + test(env, USD, std::nullopt, STPath(), terLOCKED); + USDM.set({.flags = tfMPTUnlock}); + test(env, USD, std::nullopt, STPath(), tesSUCCESS); + + // Account can not receive funds + USDM.set({.holder = bob, .flags = tfMPTLock}); + test(env, USD, std::nullopt, STPath(), terLOCKED); + USDM.set({.holder = bob, .flags = tfMPTUnlock}); + test(env, USD, std::nullopt, STPath(), tesSUCCESS); + } + + { + // check no auth + // An account may require authorization to receive MPTs from an + // issuer + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, gw); + auto USDM = MPTTester( + {.env = env, + .issuer = gw, + .flags = MPTDEXFlags | tfMPTRequireAuth, + .maxAmt = 1'000}); + MPT const USD = USDM; + + // Authorize alice but not bob + USDM.authorize({.account = alice}); + USDM.authorize({.holder = alice}); + env(pay(gw, alice, USD(100))); + env.require(balance(alice, USD(100))); + test(env, USD, std::nullopt, STPath(), tecNO_AUTH); + + // Check pure issue redeem still works + auto [ter, strand] = toStrand( + *env.current(), + alice, + gw, + USD, + std::nullopt, + std::nullopt, + STPath(), + true, + OfferCrossing::no, + ammContext, + std::nullopt, + env.app().getLogs().journal("Flow")); + BEAST_EXPECT(ter == tesSUCCESS); + BEAST_EXPECT(equal(strand, M{alice, gw, USD})); + } + + { + // last step xrp from offer + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, gw); + MPT const USD = + MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}, .maxAmt = 1'000}); + env(pay(gw, alice, USD(100))); + + // alice -> USD/XRP -> bob + STPath path; + path.emplace_back(std::nullopt, xrpCurrency(), std::nullopt); + + auto [ter, strand] = toStrand( + *env.current(), + alice, + bob, + XRP, + std::nullopt, + USD, + path, + false, + OfferCrossing::no, + ammContext, + std::nullopt, + env.app().getLogs().journal("Flow")); + BEAST_EXPECT(ter == tesSUCCESS); + BEAST_EXPECT( + equal(strand, M{alice, gw, USD}, B{USD, xrpIssue(), std::nullopt}, XRPS{bob})); + } + } + + void + testRIPD1373(FeatureBitset features) + { + using namespace jtx; + testcase("RIPD1373"); + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + auto const gw = Account("gw"); + + { + Env env(*this, features); + + env.fund(XRP(10000), alice, bob, carol, gw); + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .maxAmt = 10'000}); + + env(pay(gw, bob, USD(100))); + + env(offer(bob, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(bob, USD(100), XRP(100)), txflags(tfPassive)); + + // payment path: XRP -> XRP/USD -> USD/XRP + env(pay(alice, carol, XRP(100)), + path(~USD, ~XRP), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_PATHS)); + } + + { + Env env(*this, features); + + env.fund(XRP(10000), alice, bob, carol, gw); + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .maxAmt = 10'000}); + + env(pay(gw, bob, USD(100))); + + env(offer(bob, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(bob, USD(100), XRP(100)), txflags(tfPassive)); + + // payment path: XRP -> XRP/USD -> USD/XRP + env(pay(alice, carol, XRP(100)), + path(~USD, ~XRP), + sendmax(XRP(200)), + txflags(tfNoRippleDirect), + ter(temBAD_SEND_XRP_MAX)); + } + } + + void + testLoop(FeatureBitset features) + { + testcase("test loop"); + using namespace jtx; + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const carol = Account("carol"); + auto const gw = Account("gw"); + auto const EUR = gw["EUR"]; + auto const CNY = gw["CNY"]; + + { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + MPT const USD = MPTTester( + {.env = env, .issuer = gw, .holders = {alice, bob, carol}, .maxAmt = 10'000}); + + env(pay(gw, bob, USD(100))); + env(pay(gw, alice, USD(100))); + + env(offer(bob, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(bob, USD(100), XRP(100)), txflags(tfPassive)); + + // payment path: USD -> USD/XRP -> XRP/USD + env(pay(alice, carol, USD(100)), + sendmax(USD(100)), + path(~XRP, ~USD), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + } + { + auto testMultiToken = [&](auto&& issue1, auto&& issue2, auto&& issue3) { + Env env(*this, features); + + env.fund(XRP(10'000), alice, bob, carol, gw); + auto const USD = issue1( + {.env = env, + .token = "USD", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000}); + auto const EUR = issue2( + {.env = env, + .token = "EUR", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000}); + auto const CNY = issue3( + {.env = env, + .token = "CNY", + .issuer = gw, + .holders = {alice, bob, carol}, + .limit = 10'000}); + + env(pay(gw, bob, USD(100))); + env(pay(gw, bob, EUR(100))); + env(pay(gw, bob, CNY(100))); + + env(offer(bob, XRP(100), USD(100)), txflags(tfPassive)); + env(offer(bob, USD(100), EUR(100)), txflags(tfPassive)); + env(offer(bob, EUR(100), CNY(100)), txflags(tfPassive)); + + // payment path: XRP->XRP/USD->USD/EUR->USD/CNY + env(pay(alice, carol, CNY(100)), + sendmax(XRP(100)), + path(~USD, ~EUR, ~USD, ~CNY), + txflags(tfNoRippleDirect), + ter(temBAD_PATH_LOOP)); + }; + testHelper3TokensMix(testMultiToken); + } + } + + void + testNoAccount(FeatureBitset features) + { + testcase("test no account"); + using namespace jtx; + + auto const alice = Account("alice"); + auto const bob = Account("bob"); + auto const gw = Account("gw"); + + Env env(*this, features); + env.fund(XRP(10'000), alice, bob, gw); + MPT const USD = MPTTester({.env = env, .issuer = gw, .holders = {alice, bob}}); + + STAmount const sendMax{USD, 100, 1}; + STAmount const noAccountAmount{MPTIssue{0, noAccount()}, 100, 1}; + STAmount const deliver; + AccountID const srcAcc = alice.id(); + AccountID const dstAcc = bob.id(); + STPathSet const pathSet; + xrpl::path::RippleCalc::Input inputs; + inputs.defaultPathsAllowed = true; + try + { + PaymentSandbox sb{env.current().get(), tapNONE}; + { + auto const r = ::xrpl::path::RippleCalc::rippleCalculate( + sb, + sendMax, + deliver, + dstAcc, + noAccount(), + pathSet, + std::nullopt, + env.app(), + &inputs); + BEAST_EXPECT(r.result() == temBAD_PATH); + } + { + auto const r = ::xrpl::path::RippleCalc::rippleCalculate( + sb, + sendMax, + deliver, + noAccount(), + srcAcc, + pathSet, + std::nullopt, + env.app(), + &inputs); + BEAST_EXPECT(r.result() == temBAD_PATH); + } + { + auto const r = ::xrpl::path::RippleCalc::rippleCalculate( + sb, + noAccountAmount, + deliver, + dstAcc, + srcAcc, + pathSet, + std::nullopt, + env.app(), + &inputs); + BEAST_EXPECT(r.result() == temBAD_PATH); + } + { + auto const r = ::xrpl::path::RippleCalc::rippleCalculate( + sb, + sendMax, + noAccountAmount, + dstAcc, + srcAcc, + pathSet, + std::nullopt, + env.app(), + &inputs); + BEAST_EXPECT(r.result() == temBAD_PATH); + } + } + catch (...) + { + this->fail(); + } + } + + void + run() override + { + using namespace jtx; + auto const sa = testable_amendments(); + testToStrand(sa); + + testRIPD1373(sa); + + testLoop(sa); + + testNoAccount(sa); + } +}; + +BEAST_DEFINE_TESTSUITE(PayStrandMPT, app, xrpl); + +} // namespace test +} // namespace xrpl diff --git a/src/test/app/PayStrand_test.cpp b/src/test/app/PayStrand_test.cpp index 222bc2ed07..e0ead8536c 100644 --- a/src/test/app/PayStrand_test.cpp +++ b/src/test/app/PayStrand_test.cpp @@ -17,18 +17,6 @@ namespace xrpl { namespace test { -struct DirectStepInfo -{ - AccountID src; - AccountID dst; - Currency currency; -}; - -struct XRPEndpointStepInfo -{ - AccountID acc; -}; - enum class TrustFlag { freeze, auth, noripple }; /*constexpr*/ std::uint32_t @@ -69,82 +57,6 @@ getTrustFlag( return false; // silence warning } -bool -equal(std::unique_ptr const& s1, DirectStepInfo const& dsi) -{ - if (!s1) - return false; - return test::directStepEqual(*s1, dsi.src, dsi.dst, dsi.currency); -} - -bool -equal(std::unique_ptr const& s1, XRPEndpointStepInfo const& xrpStepInfo) -{ - if (!s1) - return false; - return test::xrpEndpointStepEqual(*s1, xrpStepInfo.acc); -} - -bool -equal(std::unique_ptr const& s1, xrpl::Book const& bsi) -{ - if (!s1) - return false; - return bookStepEqual(*s1, bsi); -} - -template -bool -strandEqualHelper(Iter i) -{ - // base case. all args processed and found equal. - return true; -} - -template -bool -strandEqualHelper(Iter i, StepInfo&& si, Args&&... args) -{ - if (!equal(*i, std::forward(si))) - return false; - return strandEqualHelper(++i, std::forward(args)...); -} - -template -bool -equal(Strand const& strand, Args&&... args) -{ - if (strand.size() != sizeof...(Args)) - return false; - if (strand.empty()) - return true; - return strandEqualHelper(strand.begin(), std::forward(args)...); -} - -STPathElement -ape(AccountID const& a) -{ - return STPathElement(STPathElement::typeAccount, a, xrpCurrency(), xrpAccount()); -}; - -// Issue path element -STPathElement -ipe(Issue const& iss) -{ - return STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, - xrpAccount(), - iss.currency, - iss.account); -}; - -// Issuer path element -STPathElement -iape(AccountID const& account) -{ - return STPathElement(STPathElement::typeIssuer, xrpAccount(), xrpCurrency(), account); -}; - class ElementComboIter { enum class SB /*state bit*/ @@ -644,7 +556,7 @@ struct PayStrand_test : public beast::unit_test::suite alice, /*deliver*/ xrpIssue(), /*limitQuality*/ std::nullopt, - /*sendMaxIssue*/ EUR.issue(), + /*sendMaxIssue*/ EUR, path, true, OfferCrossing::no, @@ -662,7 +574,7 @@ struct PayStrand_test : public beast::unit_test::suite alice, /*deliver*/ xrpIssue(), /*limitQuality*/ std::nullopt, - /*sendMaxIssue*/ EUR.issue(), + /*sendMaxIssue*/ EUR, path, true, OfferCrossing::no, @@ -695,7 +607,7 @@ struct PayStrand_test : public beast::unit_test::suite test( env, EUR, - USD.issue(), + USD, STPath(), tesSUCCESS, D{alice, gw, usdC}, @@ -706,7 +618,7 @@ struct PayStrand_test : public beast::unit_test::suite test( env, EUR, - USD.issue(), + USD, STPath({ipe(EUR)}), tesSUCCESS, D{alice, gw, usdC}, @@ -718,7 +630,7 @@ struct PayStrand_test : public beast::unit_test::suite test( env, carol["USD"], - USD.issue(), + USD, STPath({iape(carol)}), tesSUCCESS, D{alice, gw, usdC}, @@ -740,7 +652,7 @@ struct PayStrand_test : public beast::unit_test::suite test( env, xrpIssue(), - USD.issue(), + USD, STPath({STPathElement{ STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()}}), tesSUCCESS, @@ -752,7 +664,7 @@ struct PayStrand_test : public beast::unit_test::suite test( env, EUR, - USD.issue(), + USD, STPath({cpe(xrpCurrency())}), tesSUCCESS, D{alice, gw, usdC}, @@ -774,7 +686,7 @@ struct PayStrand_test : public beast::unit_test::suite xrpAccount(), XRP, std::nullopt, - USD.issue(), + USD, STPath(), true, OfferCrossing::no, @@ -820,7 +732,7 @@ struct PayStrand_test : public beast::unit_test::suite } // Create an offer with the same in/out issue - test(env, EUR, USD.issue(), STPath({ipe(USD), ipe(EUR)}), temBAD_PATH); + test(env, EUR, USD, STPath({ipe(USD), ipe(EUR)}), temBAD_PATH); // Path element with type zero test( @@ -836,7 +748,7 @@ struct PayStrand_test : public beast::unit_test::suite test(env, USD, std::nullopt, STPath({ape(gw), ape(carol)}), temBAD_PATH_LOOP); // The same offer can't appear more than once on a path - test(env, EUR, USD.issue(), STPath({ipe(EUR), ipe(USD), ipe(EUR)}), temBAD_PATH_LOOP); + test(env, EUR, USD, STPath({ipe(EUR), ipe(USD), ipe(EUR)}), temBAD_PATH_LOOP); } { @@ -958,7 +870,7 @@ struct PayStrand_test : public beast::unit_test::suite bob, XRP, std::nullopt, - USD.issue(), + USD, path, false, OfferCrossing::no, @@ -966,8 +878,8 @@ struct PayStrand_test : public beast::unit_test::suite std::nullopt, env.app().getJournal("Flow")); BEAST_EXPECT(isTesSuccess(ter)); - BEAST_EXPECT(equal( - strand, D{alice, gw, usdC}, B{USD.issue(), xrpIssue(), std::nullopt}, XRPS{bob})); + BEAST_EXPECT( + equal(strand, D{alice, gw, usdC}, B{USD, xrpIssue(), std::nullopt}, XRPS{bob})); } } @@ -1125,7 +1037,7 @@ struct PayStrand_test : public beast::unit_test::suite Env env(*this, features); env.fund(XRP(10000), alice, bob, gw); - STAmount const sendMax{USD.issue(), 100, 1}; + STAmount const sendMax{USD, 100, 1}; STAmount const noAccountAmount{Issue{USD.currency, noAccount()}, 100, 1}; STAmount const deliver; AccountID const srcAcc = alice.id(); diff --git a/src/test/app/PermissionedDEX_test.cpp b/src/test/app/PermissionedDEX_test.cpp index 58a041ff56..f3aed0579b 100644 --- a/src/test/app/PermissionedDEX_test.cpp +++ b/src/test/app/PermissionedDEX_test.cpp @@ -641,7 +641,7 @@ class PermissionedDEX_test : public beast::unit_test::suite PermissionedDEX(env); // Fund devin and create USD trustline - Account badDomainOwner("badDomainOwner"); + Account const badDomainOwner("badDomainOwner"); Account const devin("devin"); env.fund(XRP(1000), badDomainOwner, devin); env.close(); @@ -1163,7 +1163,7 @@ class PermissionedDEX_test : public beast::unit_test::suite PermissionedDEX(env); // Fund accounts - Account badDomainOwner("badDomainOwner"); + Account const badDomainOwner("badDomainOwner"); Account const devin("devin"); env.fund(XRP(1000), badDomainOwner, devin); env.close(); diff --git a/src/test/app/ReducedOffer_test.cpp b/src/test/app/ReducedOffer_test.cpp index b19999fecd..3aa57423b5 100644 --- a/src/test/app/ReducedOffer_test.cpp +++ b/src/test/app/ReducedOffer_test.cpp @@ -150,7 +150,7 @@ public: }; // bob's offer (the new offer) is the same every time: - Amounts const bobOffer{STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; + Amounts const bobOffer{STAmount(XRP(1)), STAmount(USD, 1, 0)}; // alice's offer has a slightly smaller TakerPays with each // iteration. This should mean that the size of the offer bob @@ -161,10 +161,10 @@ public: mantissaReduce += 20'000'000ull) { STAmount const aliceUSD{ - bobOffer.out.issue(), + bobOffer.out.asset(), bobOffer.out.mantissa() - mantissaReduce, bobOffer.out.exponent()}; - STAmount const aliceXRP{bobOffer.in.issue(), bobOffer.in.mantissa() - 1}; + STAmount const aliceXRP{bobOffer.in.asset(), bobOffer.in.mantissa() - 1}; Amounts const aliceOffer{aliceUSD, aliceXRP}; blockedCount += exerciseOfferPair(aliceOffer, bobOffer); } @@ -282,7 +282,7 @@ public: }; // alice's offer (the old offer) is the same every time: - Amounts const aliceOffer{STAmount(XRP(1)), STAmount(USD.issue(), 1, 0)}; + Amounts const aliceOffer{STAmount(XRP(1)), STAmount(USD, 1, 0)}; // bob's offer has a slightly smaller TakerPays with each iteration. // This should mean that the size of the offer alice leaves in the @@ -293,10 +293,10 @@ public: mantissaReduce += 20'000'000ull) { STAmount const bobUSD{ - aliceOffer.out.issue(), + aliceOffer.out.asset(), aliceOffer.out.mantissa() - mantissaReduce, aliceOffer.out.exponent()}; - STAmount const bobXRP{aliceOffer.in.issue(), aliceOffer.in.mantissa() - 1}; + STAmount const bobXRP{aliceOffer.in.asset(), aliceOffer.in.mantissa() - 1}; Amounts const bobOffer{bobUSD, bobXRP}; blockedCount += exerciseOfferPair(aliceOffer, bobOffer); @@ -407,7 +407,7 @@ public: auto const USD = gw["USD"]; auto const EUR = gw["EUR"]; - STAmount const tinyUSD(USD.issue(), /*mantissa*/ 1, /*exponent*/ -81); + STAmount const tinyUSD(USD, /*mantissa*/ 1, /*exponent*/ -81); { Env env{*this, testable_amendments()}; @@ -417,10 +417,10 @@ public: env.trust(USD(1000), alice, bob); env.trust(EUR(1000), alice, bob); - STAmount const eurOffer(EUR.issue(), /*mantissa*/ 2957, /*exponent*/ -76); - STAmount const usdOffer(USD.issue(), /*mantissa*/ 7109, /*exponent*/ -76); + STAmount const eurOffer(EUR, /*mantissa*/ 2957, /*exponent*/ -76); + STAmount const usdOffer(USD, /*mantissa*/ 7109, /*exponent*/ -76); - STAmount const endLoop(USD.issue(), /*mantissa*/ 50, /*exponent*/ -81); + STAmount const endLoop(USD, /*mantissa*/ 50, /*exponent*/ -81); int blockedOrderBookCount = 0; for (STAmount initialBobUSD = tinyUSD; initialBobUSD <= endLoop; @@ -595,7 +595,7 @@ public: if (badRate == 0) { STAmount const tweakedTakerGets( - aliceReducedOffer.in.issue(), + aliceReducedOffer.in.asset(), aliceReducedOffer.in.mantissa() + 1, aliceReducedOffer.in.exponent(), aliceReducedOffer.in.negative()); @@ -629,7 +629,7 @@ public: unsigned int blockedCount = 0; { STAmount increaseGets = USD(0); - STAmount const step(increaseGets.issue(), 1, -8); + STAmount const step(increaseGets.asset(), 1, -8); for (unsigned int i = 0; i < loopCount; ++i) { blockedCount += diff --git a/src/test/app/TheoreticalQuality_test.cpp b/src/test/app/TheoreticalQuality_test.cpp index d7e0882c3b..0f73b8da6a 100644 --- a/src/test/app/TheoreticalQuality_test.cpp +++ b/src/test/app/TheoreticalQuality_test.cpp @@ -223,9 +223,9 @@ class TheoreticalQuality_test : public beast::unit_test::suite PaymentSandbox const sb(closed.get(), tapNONE); AMMContext ammContext(rcp.srcAccount, false); - auto const sendMaxIssue = [&rcp]() -> std::optional { + auto const sendMaxIssue = [&rcp]() -> std::optional { if (rcp.sendMax) - return rcp.sendMax->issue(); + return rcp.sendMax->asset(); return std::nullopt; }(); @@ -235,7 +235,7 @@ class TheoreticalQuality_test : public beast::unit_test::suite sb, rcp.srcAccount, rcp.dstAccount, - rcp.dstAmt.issue(), + rcp.dstAmt.asset(), /*limitQuality*/ std::nullopt, sendMaxIssue, rcp.paths, diff --git a/src/test/app/TrustAndBalance_test.cpp b/src/test/app/TrustAndBalance_test.cpp index a71ddb140e..e4cc1d34d5 100644 --- a/src/test/app/TrustAndBalance_test.cpp +++ b/src/test/app/TrustAndBalance_test.cpp @@ -358,8 +358,7 @@ class TrustAndBalance_test : public beast::unit_test::suite { env.require(balance( alice, - STAmount( - carol["USD"].issue(), 6500000000000000ull, -14, true, STAmount::unchecked{}))); + STAmount(carol["USD"], 6500000000000000ull, -14, true, STAmount::unchecked{}))); env.require(balance(carol, gw["USD"](35))); } else diff --git a/src/test/app/Vault_test.cpp b/src/test/app/Vault_test.cpp index fd4cbd5334..95b9165feb 100644 --- a/src/test/app/Vault_test.cpp +++ b/src/test/app/Vault_test.cpp @@ -44,11 +44,11 @@ class Vault_test : public beast::unit_test::suite testSequences() { using namespace test::jtx; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; - Account charlie{"charlie"}; // authorized 3rd party - Account dave{"dave"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; + Account const charlie{"charlie"}; // authorized 3rd party + Account const dave{"dave"}; auto const testSequence = [&, this]( std::string const& prefix, @@ -1330,10 +1330,10 @@ class Vault_test : public beast::unit_test::suite return defXRP; return a + XRP(1000); } - auto defIOU = STAmount{a.issue(), 30000}; + auto defIOU = STAmount{a.asset(), 30000}; if (a <= defIOU) return defIOU; - return a + STAmount{a.issue(), 1000}; + return a + STAmount{a.asset(), 1000}; }; auto const toFund1 = toFund(asset1); auto const toFund2 = toFund(asset2); @@ -1550,9 +1550,9 @@ class Vault_test : public beast::unit_test::suite MPTTester& mptt)> test, CaseArgs args = {}) { Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account issuer{"issuer"}; - Account owner{"owner"}; - Account depositor{"depositor"}; + Account const issuer{"issuer"}; + Account const owner{"owner"}; + Account const depositor{"depositor"}; env.fund(XRP(args.initialXRP), issuer, owner, depositor); env.close(); Vault vault{env}; @@ -2174,8 +2174,8 @@ class Vault_test : public beast::unit_test::suite testcase("MPT shares to a vault"); Env env{*this, testable_amendments() | featureSingleAssetVault}; - Account owner{"owner"}; - Account issuer{"issuer"}; + Account const owner{"owner"}; + Account const issuer{"issuer"}; env.fund(XRP(1000000), owner, issuer); env.close(); Vault const vault{env}; @@ -2242,6 +2242,43 @@ class Vault_test : public beast::unit_test::suite // Delete vault with zero balance env(vault.del({.owner = owner, .id = keylet.key})); }); + + { + testcase("MPT OutstandingAmount > MaximumAmount"); + + Env env{*this, testable_amendments() | featureSingleAssetVault}; + Account const alice{"alice"}; + Account const issuer{"issuer"}; + env.fund(XRP(1'000), alice, issuer); + env.close(); + Vault const vault{env}; + + MPTTester const BTC({.env = env, .issuer = issuer, .holders = {alice}, .maxAmt = 100}); + + auto [tx, k] = vault.create({.owner = issuer, .asset = BTC}); + env(tx); + env.close(); + + tx = vault.deposit({.depositor = issuer, .id = k.key, .amount = BTC(110)}); + // accountHolds is the first check and the issuer has only BTC(100) + // available + env(tx, ter{tecINSUFFICIENT_FUNDS}); + env.close(); + + // OutstandingAmount == MaximumAmount + env(pay(issuer, alice, BTC(100))); + env.close(); + + tx = vault.deposit({.depositor = issuer, .id = k.key, .amount = BTC(100)}); + // the issuer has BTC(0) available + env(tx, ter{tecINSUFFICIENT_FUNDS}); + env.close(); + + tx = vault.deposit({.depositor = alice, .id = k.key, .amount = BTC(100)}); + // alice transfers BTC(100), OutstandingAmount is 100 + env(tx); + env.close(); + } } void diff --git a/src/test/app/XChain_test.cpp b/src/test/app/XChain_test.cpp index abaeccb4ff..5386d9ecdc 100644 --- a/src/test/app/XChain_test.cpp +++ b/src/test/app/XChain_test.cpp @@ -291,7 +291,7 @@ struct BalanceTransfer bool has_happened(STAmount const& amt, STAmount const& reward, bool check_payer = true) { - auto reward_cost = multiply(reward, STAmount(reward_accounts.size()), reward.issue()); + auto reward_cost = multiply(reward, STAmount(reward_accounts.size()), reward.asset()); return check_most_balances(amt, reward) && (!check_payer || payer_.diff() == -(reward_cost + txFees_)); } @@ -1503,7 +1503,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(!scEnv.claimID(jvb, 1)); // claim id deleted - BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(3), reward.issue()))); + BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(3), reward.asset()))); } // 4,4 => should succeed @@ -1528,7 +1528,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj return result; }(); STAmount const split_reward_ = - divide(reward, STAmount(signers_.size()), reward.issue()); + divide(reward, STAmount(signers_.size()), reward.asset()); mcEnv.tx(create_bridge(mcDoor, jvb)).close(); @@ -1563,7 +1563,7 @@ struct XChain_test : public beast::unit_test::suite, public jtx::XChainBridgeObj BEAST_EXPECT(!scEnv.claimID(jvb, claimID)); // claim id deleted - BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(2), reward.issue()))); + BEAST_EXPECT(transfer.has_happened(amt, divide(reward, STAmount(2), reward.asset()))); } // 1,2 => should fail @@ -3887,7 +3887,7 @@ private: void receive(jtx::Account const& acct, STAmount amt, std::uint64_t divisor = 1) { - if (amt.issue() != xrpIssue()) + if (amt.asset() != xrpIssue()) return; auto it = accounts.find(acct); if (it == accounts.end()) @@ -3898,18 +3898,18 @@ private: else { it->second.expectedDiff += - (divisor == 1 ? amt : divide(amt, STAmount(amt.issue(), divisor), amt.issue())); + (divisor == 1 ? amt : divide(amt, STAmount(amt.asset(), divisor), amt.asset())); } } void spend(jtx::Account const& acct, STAmount amt, std::uint64_t times = 1) { - if (amt.issue() != xrpIssue()) + if (amt.asset() != xrpIssue()) return; receive( acct, - times == 1 ? -amt : -multiply(amt, STAmount(amt.issue(), times), amt.issue())); + times == 1 ? -amt : -multiply(amt, STAmount(amt.asset(), times), amt.asset())); } void @@ -4132,7 +4132,7 @@ private: assert(cr.claim_id - 1 == counters.claim_count); auto r = cr.reward; - auto reward = divide(r, STAmount(num_attestors), r.issue()); + auto reward = divide(r, STAmount(num_attestors), r.asset()); for (auto i : signers) st.receive(bridge_.signers[i].account, reward); @@ -4213,7 +4213,7 @@ private: ChainStateTrack& st = srcState(); jtx::Account const& srcdoor = srcDoor(); - if (xfer.amt.issue() != xrpIssue()) + if (xfer.amt.asset() != xrpIssue()) { st.env.tx(pay(srcdoor, xfer.from, xfer.amt)); st.spendFee(srcdoor); @@ -4233,7 +4233,7 @@ private: distribute_reward(ChainStateTrack& st) { auto r = bridge_.reward; - auto reward = divide(r, STAmount(bridge_.quorum), r.issue()); + auto reward = divide(r, STAmount(bridge_.quorum), r.asset()); for (size_t i = 0; i < num_signers; ++i) { diff --git a/src/test/jtx/AMM.h b/src/test/jtx/AMM.h index 210138f290..45f0e13797 100644 --- a/src/test/jtx/AMM.h +++ b/src/test/jtx/AMM.h @@ -12,30 +12,36 @@ #include #include +#include + namespace xrpl { namespace test { namespace jtx { class LPToken { - IOUAmount const tokens_; + Number const tokens_; + Asset asset_; public: - LPToken(std::uint64_t tokens) : tokens_(tokens) + LPToken(std::uint64_t tokens) : tokens_(tokens), asset_(xrpIssue()) { } - LPToken(IOUAmount tokens) : tokens_(tokens) + LPToken(IOUAmount tokens) : tokens_(tokens), asset_(xrpIssue()) { } - IOUAmount const& + LPToken(STAmount tokens) : tokens_(tokens), asset_(tokens.asset()) + { + } + STAmount tokens() const { - return tokens_; + return STAmount{asset_, tokens_}; } STAmount tokens(Issue const& ammIssue) const { - return STAmount{tokens_, ammIssue}; + return STAmount{ammIssue, tokens_}; } }; @@ -59,7 +65,7 @@ struct DepositArg std::optional asset2In = std::nullopt; std::optional maxEP = std::nullopt; std::optional flags = std::nullopt; - std::optional> assets = std::nullopt; + std::optional> assets = std::nullopt; std::optional seq = std::nullopt; std::optional tfee = std::nullopt; std::optional err = std::nullopt; @@ -71,9 +77,9 @@ struct WithdrawArg std::optional tokens = std::nullopt; std::optional asset1Out = std::nullopt; std::optional asset2Out = std::nullopt; - std::optional maxEP = std::nullopt; + std::optional maxEP = std::nullopt; std::optional flags = std::nullopt; - std::optional> assets = std::nullopt; + std::optional> assets = std::nullopt; std::optional seq = std::nullopt; std::optional err = std::nullopt; }; @@ -84,7 +90,7 @@ struct VoteArg std::uint32_t tfee = 0; std::optional flags = std::nullopt; std::optional seq = std::nullopt; - std::optional> assets = std::nullopt; + std::optional> assets = std::nullopt; std::optional err = std::nullopt; }; @@ -95,7 +101,17 @@ struct BidArg std::optional> bidMax = std::nullopt; std::vector authAccounts = {}; std::optional flags = std::nullopt; - std::optional> assets = std::nullopt; + std::optional> assets = std::nullopt; +}; + +struct ClawbackArg +{ + Account issuer; + Account holder; + std::optional> assets = std::nullopt; + std::optional amount = std::nullopt; + std::optional flags = std::nullopt; + std::optional err = std::nullopt; }; /** Convenience class to test AMM functionality. @@ -147,14 +163,21 @@ public: STAmount const& asset2, CreateArg const& arg); + static Json::Value + createJv( + AccountID const& account, + STAmount const& asset1, + STAmount const& asset2, + std::uint16_t const& tfee); + /** Send amm_info RPC command */ Json::Value ammRpcInfo( std::optional const& account = std::nullopt, std::optional const& ledgerIndex = std::nullopt, - std::optional issue1 = std::nullopt, - std::optional issue2 = std::nullopt, + std::optional asset1 = std::nullopt, + std::optional asset2 = std::nullopt, std::optional const& ammAccount = std::nullopt, bool ignoreParams = false, unsigned apiVersion = RPC::apiInvalidVersion) const; @@ -172,14 +195,14 @@ public: */ std::tuple balances( - Issue const& issue1, - Issue const& issue2, + Asset const& asset1, + Asset const& asset2, std::optional const& account = std::nullopt) const; std::tuple balances(std::optional const& account = std::nullopt) const { - return balances(asset1_.get(), asset2_.get(), account); + return balances(asset1_.asset(), asset2_.asset(), account); } [[nodiscard]] bool @@ -214,6 +237,9 @@ public: [[nodiscard]] bool ammExists() const; + static Json::Value + depositJv(DepositArg const& arg); + IOUAmount deposit( std::optional const& account, @@ -239,7 +265,7 @@ public: std::optional const& asset2In, std::optional const& maxEP, std::optional const& flags, - std::optional> const& assets, + std::optional> const& assets, std::optional const& seq, std::optional const& tfee = std::nullopt, std::optional const& ter = std::nullopt); @@ -247,6 +273,9 @@ public: IOUAmount deposit(DepositArg const& arg); + static Json::Value + withdrawJv(WithdrawArg const& arg); + IOUAmount withdraw( std::optional const& account, @@ -274,7 +303,7 @@ public: std::optional const& account, STAmount const& asset1Out, std::optional const& asset2Out = std::nullopt, - std::optional const& maxEP = std::nullopt, + std::optional const& maxEP = std::nullopt, std::optional const& ter = std::nullopt); IOUAmount @@ -283,22 +312,25 @@ public: std::optional const& tokens, std::optional const& asset1Out, std::optional const& asset2Out, - std::optional const& maxEP, + std::optional const& maxEP, std::optional const& flags, - std::optional> const& assets, + std::optional> const& assets, std::optional const& seq, std::optional const& ter = std::nullopt); IOUAmount withdraw(WithdrawArg const& arg); + static Json::Value + voteJv(VoteArg const& arg); + void vote( std::optional const& account, std::uint32_t feeVal, std::optional const& flags = std::nullopt, std::optional const& seq = std::nullopt, - std::optional> const& assets = std::nullopt, + std::optional> const& assets = std::nullopt, std::optional const& ter = std::nullopt); void @@ -307,6 +339,9 @@ public: Json::Value bid(BidArg const& arg); + void + clawback(ClawbackArg const& arg); + AccountID const& ammAccount() const { @@ -348,8 +383,11 @@ public: return ammRpcInfo(lp); } + static Json::Value + deleteJv(AccountID const& account, Asset const& asset1, Asset const& assets); + void - ammDelete(AccountID const& deleter, std::optional const& ter = std::nullopt); + ammDelete(AccountID const& account, std::optional const& ter = std::nullopt); void setClose(bool close) @@ -364,7 +402,75 @@ public: } void - setTokens(Json::Value& jv, std::optional> const& assets = std::nullopt); + setTokens(Json::Value& jv, std::optional> const& assets = std::nullopt); + + Asset const& + operator[](std::uint8_t i) + { + if (i > 1) + Throw("AMM: operator[], invalid index"); + return i == 0 ? asset1_.asset() : asset2_.asset(); + } + + struct Pool + { + AMM const& amm; + std::vector names; + Pool(AMM const& a, std::vector const& n = {}) : amm(a), names(n) + { + } + friend std::ostream& + operator<<(std::ostream& s, Pool const& p) + { + auto const& jr = p.amm.ammRpcInfo(); + auto out = [&](Json::Value const& jv) { + if (jv.isMember(jss::value)) + std::cout << jv[jss::value].asString(); + else + std::cout << jv.asString(); + std::cout << " "; + }; + if (p.names.empty()) + { + out(jr[jss::amm][jss::amount]); + out(jr[jss::amm][jss::amount2]); + out(jr[jss::amm][jss::lp_token]); + } + else + { + for (auto const& n : p.names) + out(jr[jss::amm][n]); + } + std::cout << std::endl; + return s; + } + }; + struct Offers + { + Json::Value const& jv; + Offers(Json::Value const& j) : jv(j) + { + } + friend std::ostream& + operator<<(std::ostream& s, Offers const& offers) + { + auto out = [&](Json::Value const& jv) { + if (jv.isMember(jss::value)) + s << jv[jss::value].asString(); + else + s << jv; + }; + for (auto const& o : offers.jv[jss::offers]) + { + s << "taker_pays: "; + out(o[jss::taker_pays]); + s << " taker_gets: "; + out(o[jss::taker_gets]); + s << std::endl; + } + return s; + } + }; private: AccountID @@ -374,22 +480,6 @@ private: std::optional const& seq = std::nullopt, std::optional const& ter = std::nullopt); - IOUAmount - deposit( - std::optional const& account, - Json::Value& jv, - std::optional> const& assets = std::nullopt, - std::optional const& seq = std::nullopt, - std::optional const& ter = std::nullopt); - - IOUAmount - withdraw( - std::optional const& account, - Json::Value& jv, - std::optional const& seq, - std::optional> const& assets = std::nullopt, - std::optional const& ter = std::nullopt); - void log(bool log) { @@ -417,17 +507,13 @@ private: }; namespace amm { -Json::Value -trust(AccountID const& account, STAmount const& amount, std::uint32_t flags = 0); -Json::Value -pay(Account const& account, AccountID const& to, STAmount const& amount); Json::Value ammClawback( Account const& issuer, Account const& holder, - Issue const& asset, - Issue const& asset2, + Asset const& asset, + Asset const& asset2, std::optional const& amount); } // namespace amm diff --git a/src/test/jtx/AMMTest.h b/src/test/jtx/AMMTest.h index a311d9c638..a3d126646d 100644 --- a/src/test/jtx/AMMTest.h +++ b/src/test/jtx/AMMTest.h @@ -13,7 +13,7 @@ namespace jtx { class AMM; -enum class Fund { All, Acct, Gw, IOUOnly }; +enum class Fund { All, Acct, Gw, TokenOnly }; struct TestAMMArg { @@ -28,7 +28,13 @@ struct TestAMMArg bool noLog = false; }; -void +// A hint to testAMM() or fund() to create/fund MPT. +// A distinct MPT is created if both AMM assets +// are MPT. The actual MPT asset can be accessed +// via AMM::operator[](0|1). +inline static auto AMMMPT = MPT("AMM"); + +[[maybe_unused]] std::vector fund( jtx::Env& env, jtx::Account const& gw, @@ -36,7 +42,7 @@ fund( std::vector const& amts, Fund how); -void +[[maybe_unused]] std::vector fund( jtx::Env& env, jtx::Account const& gw, @@ -45,13 +51,22 @@ fund( std::vector const& amts = {}, Fund how = Fund::All); -void +[[maybe_unused]] std::vector fund( jtx::Env& env, std::vector const& accounts, STAmount const& xrp, std::vector const& amts = {}, - Fund how = Fund::All); + Fund how = Fund::All, + std::optional const& mptIssuer = std::nullopt); + +struct TestAMMArgs +{ + std::optional> const& pool = std::nullopt; + std::uint16_t tfee = 0; + std::optional const& ter = std::nullopt; + std::vector const& features = {testable_amendments()}; +}; class AMMTestBase : public beast::unit_test::suite { @@ -135,24 +150,6 @@ protected: jtx::Env pathTestEnv(); - - Json::Value - find_paths_request( - jtx::Env& env, - jtx::Account const& src, - jtx::Account const& dst, - STAmount const& saDstAmount, - std::optional const& saSendMax = std::nullopt, - std::optional const& saSrcCurrency = std::nullopt); - - std::tuple - find_paths( - jtx::Env& env, - jtx::Account const& src, - jtx::Account const& dst, - STAmount const& saDstAmount, - std::optional const& saSendMax = std::nullopt, - std::optional const& saSrcCurrency = std::nullopt); }; } // namespace jtx diff --git a/src/test/jtx/Env.h b/src/test/jtx/Env.h index b494ade31c..d638d520ba 100644 --- a/src/test/jtx/Env.h +++ b/src/test/jtx/Env.h @@ -510,15 +510,8 @@ public: */ // VFALCO NOTE This should return a unit-less amount PrettyAmount - // NOLINTNEXTLINE(readability-convert-member-functions-to-static) balance(Account const& account, Asset const& asset) const; - PrettyAmount - balance(Account const& account, Issue const& issue) const; - - PrettyAmount - balance(Account const& account, MPTIssue const& mptIssue) const; - /** Returns the IOU limit on an account. Returns 0 if the trust line does not exist. */ diff --git a/src/test/jtx/PathSet.h b/src/test/jtx/PathSet.h index c522ed635e..86b38f7eaf 100644 --- a/src/test/jtx/PathSet.h +++ b/src/test/jtx/PathSet.h @@ -15,13 +15,13 @@ inline std::size_t countOffers( jtx::Env& env, jtx::Account const& account, - Issue const& takerPays, - Issue const& takerGets) + Asset const& takerPays, + Asset const& takerGets) { size_t count = 0; forEachItem(*env.current(), account, [&](std::shared_ptr const& sle) { - if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays).issue() == takerPays && - sle->getFieldAmount(sfTakerGets).issue() == takerGets) + if (sle->getType() == ltOFFER && sle->getFieldAmount(sfTakerPays).asset() == takerPays && + sle->getFieldAmount(sfTakerGets).asset() == takerGets) ++count; }); return count; @@ -58,7 +58,7 @@ isOffer( /** An offer exists */ inline bool -isOffer(jtx::Env& env, jtx::Account const& account, Issue const& takerPays, Issue const& takerGets) +isOffer(jtx::Env& env, jtx::Account const& account, Asset const& takerPays, Asset const& takerGets) { return countOffers(env, account, takerPays, takerGets) > 0; } @@ -84,6 +84,8 @@ public: Path& push_back(Issue const& iss); Path& + push_back(MPTIssue const& iss); + Path& push_back(jtx::Account const& acc); Path& push_back(STPathElement const& pe); @@ -114,10 +116,21 @@ Path::push_back(Issue const& iss) return *this; } +inline Path& +Path::push_back(MPTIssue const& iss) +{ + path.emplace_back( + STPathElement::typeMPT | STPathElement::typeIssuer, + beast::zero, + iss.getMptID(), + iss.getIssuer()); + return *this; +} + inline Path& Path::push_back(jtx::Account const& account) { - path.emplace_back(account.id(), beast::zero, beast::zero); + path.emplace_back(account.id(), Currency{beast::zero}, beast::zero); return *this; } diff --git a/src/test/jtx/TestHelpers.h b/src/test/jtx/TestHelpers.h index 4da086b05b..0beca74e90 100644 --- a/src/test/jtx/TestHelpers.h +++ b/src/test/jtx/TestHelpers.h @@ -5,14 +5,13 @@ #include #include -#include #include #include #include #include -#include #include #include +#include #include #include @@ -402,6 +401,9 @@ equal(STAmount const& sa1, STAmount const& sa2); STPathElement IPE(Issue const& iss); +STPathElement +IPE(MPTIssue const& iss); + template STPath stpath(Args const&... args) @@ -428,6 +430,79 @@ same(STPathSet const& st1, Args const&... args) return true; } +Json::Value +rpf(jtx::Account const& src, + jtx::Account const& dst, + STAmount const& dstAmount, + std::optional const& sendMax = std::nullopt, + std::optional const& srcAsset = std::nullopt, + std::optional const& srcIssuer = std::nullopt); + +jtx::Env +pathTestEnv(beast::unit_test::suite& suite); + +class gate +{ +private: + std::condition_variable cv_; + std::mutex mutex_; + bool signaled_ = false; + +public: + // Thread safe, blocks until signaled or period expires. + // Returns `true` if signaled. + template + bool + wait_for(std::chrono::duration const& rel_time) + { + std::unique_lock lk(mutex_); + auto b = cv_.wait_for(lk, rel_time, [this] { return signaled_; }); + signaled_ = false; + return b; + } + + void + signal() + { + std::lock_guard const lk(mutex_); + signaled_ = true; + cv_.notify_all(); + } +}; + +Json::Value +find_paths_request( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax = std::nullopt, + std::optional const& srcAsset = std::nullopt, + std::optional const& srcIssuer = std::nullopt, + std::optional const& domain = std::nullopt); + +std::tuple +find_paths( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax = std::nullopt, + std::optional const& srcAsset = std::nullopt, + std::optional const& srcIssuer = std::nullopt, + std::optional const& domain = std::nullopt); + +std::tuple +find_paths_by_element( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax = std::nullopt, + std::optional const& srcElement = std::nullopt, + std::optional const& srcIssuer = std::nullopt, + std::optional const& domain = std::nullopt); + /******************************************************************************/ XRPAmount @@ -453,6 +528,9 @@ expectHolding(Env& env, AccountID const& account, STAmount const& value, Amts co bool expectHolding(Env& env, AccountID const& account, None const& value); +bool +expectMPT(Env& env, AccountID const& account, STAmount const& value); + bool expectOffers( Env& env, @@ -470,6 +548,15 @@ ledgerEntryState( Account const& acct_b, std::string const& currency); +Json::Value +ledgerEntryOffer(jtx::Env& env, jtx::Account const& acct, std::uint32_t offer_seq); + +Json::Value +ledgerEntryMPT(jtx::Env& env, jtx::Account const& acct, MPTID const& mptID); + +Json::Value +getBookOffers(jtx::Env& env, Asset const& taker_pays, Asset const& taker_gets); + Json::Value accountBalance(Env& env, Account const& acct); @@ -545,13 +632,85 @@ n_offers(Env& env, std::size_t n, Account const& account, STAmount const& in, ST /* Pay Strand */ /***************************************************************/ -// Currency path element +struct DirectStepInfo +{ + AccountID src; + AccountID dst; + Currency currency; +}; + +struct MPTEndpointStepInfo +{ + AccountID src; + AccountID dst; + MPTID mptid; +}; + +struct XRPEndpointStepInfo +{ + AccountID acc; +}; + +// Currency/MPTID path element STPathElement -cpe(Currency const& c); +cpe(PathAsset const& pa); + +// Currency/MPTID and issuer path element +STPathElement +ipe(Asset const& asset); + +// Issuer path element +STPathElement +iape(AccountID const& account); + +// Account path element +STPathElement +ape(AccountID const& a); // All path element STPathElement -allPathElements(AccountID const& a, Issue const& iss); +allPathElements(AccountID const& a, Asset const& asset); + +bool +equal(std::unique_ptr const& s1, DirectStepInfo const& dsi); + +bool +equal(std::unique_ptr const& s1, MPTEndpointStepInfo const& dsi); + +bool +equal(std::unique_ptr const& s1, XRPEndpointStepInfo const& xrpStepInfo); + +bool +equal(std::unique_ptr const& s1, xrpl::Book const& bsi); + +template +bool +strandEqualHelper(Iter i) +{ + // base case. all args processed and found equal. + return true; +} + +template +bool +strandEqualHelper(Iter i, StepInfo&& si, Args&&... args) +{ + if (!jtx::equal(*i, std::forward(si))) + return false; + return strandEqualHelper(++i, std::forward(args)...); +} + +template +bool +equal(Strand const& strand, Args&&... args) +{ + if (strand.size() != sizeof...(Args)) + return false; + if (strand.empty()) + return true; + return strandEqualHelper(strand.begin(), std::forward(args)...); +} + /***************************************************************/ /* Check */ @@ -583,6 +742,12 @@ create(jtx::Account const& account, jtx::Account const& dest, STAmount const& se static constexpr FeeLevel64 baseFeeLevel{TxQ::baseLevel}; static constexpr FeeLevel64 minEscalationFeeLevel = baseFeeLevel * 500; +inline uint256 +getCheckIndex(AccountID const& account, std::uint32_t uSequence) +{ + return keylet::check(account, uSequence).key; +} + template void checkMetrics( @@ -770,6 +935,106 @@ pay(AccountID const& account, } // namespace loan +/** Set Expiration on a JTx. */ +class expiration +{ +private: + std::uint32_t const expiry_; + +public: + explicit expiration(NetClock::time_point const& expiry) + : expiry_{expiry.time_since_epoch().count()} + { + } + + void + operator()(Env&, JTx& jt) const + { + jt[sfExpiration.jsonName] = expiry_; + } +}; + +/** Set SourceTag on a JTx. */ +class source_tag +{ +private: + std::uint32_t const tag_; + +public: + explicit source_tag(std::uint32_t tag) : tag_{tag} + { + } + + void + operator()(Env&, JTx& jt) const + { + jt[sfSourceTag.jsonName] = tag_; + } +}; + +/** Set DestinationTag on a JTx. */ +class dest_tag +{ +private: + std::uint32_t const tag_; + +public: + explicit dest_tag(std::uint32_t tag) : tag_{tag} + { + } + + void + operator()(Env&, JTx& jt) const + { + jt[sfDestinationTag.jsonName] = tag_; + } +}; + +struct IssuerArgs +{ + jtx::Env& env; + // 3-letter currency if Issue, ignored if MPT + std::string token = ""; + jtx::Account issuer; + std::vector holders = {}; + // trust-limit if Issue, maxAmount if MPT + std::optional limit = std::nullopt; + // 0-50'000 (0-50%) + std::uint16_t transferFee = 0; +}; + +namespace detail { + +IOU +issueHelperIOU(IssuerArgs const& args); + +MPT +issueHelperMPT(IssuerArgs const& args); + +} // namespace detail + +template +void +testHelper2TokensMix(TTester&& tester) +{ + tester(detail::issueHelperMPT, detail::issueHelperMPT); + tester(detail::issueHelperIOU, detail::issueHelperMPT); + tester(detail::issueHelperMPT, detail::issueHelperIOU); +} + +template +void +testHelper3TokensMix(TTester&& tester) +{ + tester(detail::issueHelperMPT, detail::issueHelperMPT, detail::issueHelperMPT); + tester(detail::issueHelperMPT, detail::issueHelperMPT, detail::issueHelperIOU); + tester(detail::issueHelperMPT, detail::issueHelperIOU, detail::issueHelperMPT); + tester(detail::issueHelperMPT, detail::issueHelperIOU, detail::issueHelperIOU); + tester(detail::issueHelperIOU, detail::issueHelperMPT, detail::issueHelperMPT); + tester(detail::issueHelperIOU, detail::issueHelperMPT, detail::issueHelperIOU); + tester(detail::issueHelperIOU, detail::issueHelperIOU, detail::issueHelperMPT); +} + } // namespace jtx } // namespace test } // namespace xrpl diff --git a/src/test/jtx/amount.h b/src/test/jtx/amount.h index 1912f01330..7819a09451 100644 --- a/src/test/jtx/amount.h +++ b/src/test/jtx/amount.h @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -56,7 +57,7 @@ struct None // could change that value (however unlikely). constexpr XRPAmount dropsPerXRP{1'000'000}; -/** Represents an XRP or IOU quantity +/** Represents an XRP, IOU, or MPT quantity This customizes the string conversion and supports XRP conversions from integer and floating point. */ @@ -231,11 +232,9 @@ public: // Specifies an order book struct BookSpec { - AccountID account; - xrpl::Currency currency; + xrpl::Asset asset; - BookSpec(AccountID const& account_, xrpl::Currency const& currency_) - : account(account_), currency(currency_) + BookSpec(xrpl::Asset const& asset_) : asset(asset_) { } }; @@ -253,6 +252,10 @@ struct XRP_t { return xrpIssue(); } + operator Asset() const + { + return xrpIssue(); + } bool integral() const @@ -317,7 +320,7 @@ struct XRP_t friend BookSpec operator~(XRP_t const&) { - return BookSpec(xrpAccount(), xrpCurrency()); + return BookSpec(Issue{xrpCurrency(), xrpAccount()}); } }; @@ -413,6 +416,10 @@ public: { return issue(); } + operator Asset() const + { + return asset(); + } operator PrettyAsset() const { return asset(); @@ -447,7 +454,7 @@ public: friend BookSpec operator~(IOU const& iou) { - return BookSpec(iou.account.id(), iou.currency); + return BookSpec(Issue{iou.currency, iou.account.id()}); } }; @@ -472,6 +479,16 @@ public: MPT(std::string const& n, xrpl::MPTID const& issuanceID_) : name(n), issuanceID(issuanceID_) { } + MPT(std::string const& n = "") : name(n), issuanceID(noMPT()) + { + } + MPT(Asset const& asset) : name(""), issuanceID(asset.get()) + { + } + MPT(AccountID const& account, std::int32_t seq = 0) + : name(""), issuanceID(makeMptID(seq, account)) + { + } xrpl::MPTID const& mpt() const @@ -511,6 +528,14 @@ public: { return asset(); } + operator xrpl::Asset() const + { + return mpt(); + } + operator xrpl::MPTID() const + { + return mpt(); + } template requires(sizeof(T) >= sizeof(int) && std::is_arithmetic_v) @@ -529,15 +554,13 @@ public: None operator()(none_t) const { - return {mptIssue()}; + return {noMPT()}; } friend BookSpec operator~(MPT const& mpt) { - assert(false); - Throw("MPT is not supported"); - return BookSpec{beast::zero, noCurrency()}; + return BookSpec{Asset{mpt}}; } }; @@ -577,7 +600,7 @@ struct AnyAmount { if (!is_any) return; - value.setIssuer(id); + value.get().account = id; } }; diff --git a/src/test/jtx/flags.h b/src/test/jtx/flags.h index a203f1461e..c4fb5cb34c 100644 --- a/src/test/jtx/flags.h +++ b/src/test/jtx/flags.h @@ -104,7 +104,7 @@ fclear(Account const& account, std::uint32_t off) } /** Match set account flags */ -class flags : private detail::flags_helper +class flags : private xrpl::detail::flags_helper { private: Account account_; @@ -120,7 +120,7 @@ public: }; /** Match clear account flags */ -class nflags : private detail::flags_helper +class nflags : private xrpl::detail::flags_helper { private: Account account_; diff --git a/src/test/jtx/impl/AMM.cpp b/src/test/jtx/impl/AMM.cpp index b06353a30d..dfc0849793 100644 --- a/src/test/jtx/impl/AMM.cpp +++ b/src/test/jtx/impl/AMM.cpp @@ -49,14 +49,14 @@ AMM::AMM( , creatorAccount_(account) , asset1_(asset1) , asset2_(asset2) - , ammID_(keylet::amm(asset1_.issue(), asset2_.issue()).key) + , ammID_(keylet::amm(asset1_.asset(), asset2_.asset()).key) , log_(log) , doClose_(close) , lastPurchasePrice_(0) , msig_(ms) , fee_(fee) , ammAccount_(create(tfee, flags, seq, ter)) - , lptIssue_(xrpl::ammLPTIssue(asset1_.issue().currency, asset2_.issue().currency, ammAccount_)) + , lptIssue_(xrpl::ammLPTIssue(asset1_.asset(), asset2_.asset(), ammAccount_)) , initialLPTokens_(initialTokens()) { } @@ -105,6 +105,23 @@ AMM::AMM( { } +Json::Value +AMM::createJv( + AccountID const& account, + STAmount const& asset1, + STAmount const& asset2, + std::uint16_t const& tfee) +{ + Json::Value jv; + jv[jss::Account] = to_string(account); + jv[jss::Amount] = asset1.getJson(JsonOptions::none); + jv[jss::Amount2] = asset2.getJson(JsonOptions::none); + jv[jss::TradingFee] = tfee; + jv[jss::TransactionType] = jss::AMMCreate; + + return jv; +} + [[nodiscard]] AccountID AMM::create( std::uint32_t tfee, @@ -112,12 +129,7 @@ AMM::create( std::optional const& seq, std::optional const& ter) { - Json::Value jv; - jv[jss::Account] = creatorAccount_.human(); - jv[jss::Amount] = asset1_.getJson(JsonOptions::none); - jv[jss::Amount2] = asset2_.getJson(JsonOptions::none); - jv[jss::TradingFee] = tfee; - jv[jss::TransactionType] = jss::AMMCreate; + Json::Value jv = createJv(creatorAccount_, asset1_, asset2_, tfee); if (flags) jv[jss::Flags] = *flags; if (fee_ != 0) @@ -132,7 +144,7 @@ AMM::create( if (!ter || env_.ter() == tesSUCCESS) { - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) { return amm->getAccountID(sfAccount); } @@ -144,8 +156,8 @@ Json::Value AMM::ammRpcInfo( std::optional const& account, std::optional const& ledgerIndex, - std::optional issue1, - std::optional issue2, + std::optional asset1, + std::optional asset2, std::optional const& ammAccount, bool ignoreParams, unsigned apiVersion) const @@ -157,17 +169,17 @@ AMM::ammRpcInfo( jv[jss::ledger_index] = *ledgerIndex; if (!ignoreParams) { - if (issue1 || issue2) + if (asset1 || asset2) { - if (issue1) - jv[jss::asset] = STIssue(sfAsset, *issue1).getJson(JsonOptions::none); - if (issue2) - jv[jss::asset2] = STIssue(sfAsset2, *issue2).getJson(JsonOptions::none); + if (asset1) + jv[jss::asset] = STIssue(sfAsset, *asset1).getJson(JsonOptions::none); + if (asset2) + jv[jss::asset2] = STIssue(sfAsset2, *asset2).getJson(JsonOptions::none); } else if (!ammAccount) { - jv[jss::asset] = STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); - jv[jss::asset2] = STIssue(sfAsset2, asset2_.issue()).getJson(JsonOptions::none); + jv[jss::asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::none); + jv[jss::asset2] = STIssue(sfAsset2, asset2_.asset()).getJson(JsonOptions::none); } if (ammAccount) jv[jss::amm_account] = to_string(*ammAccount); @@ -182,18 +194,19 @@ AMM::ammRpcInfo( } std::tuple -AMM::balances(Issue const& issue1, Issue const& issue2, std::optional const& account) +AMM::balances(Asset const& asset1, Asset const& asset2, std::optional const& account) const { - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) { auto const ammAccountID = amm->getAccountID(sfAccount); auto const [asset1Balance, asset2Balance] = ammPoolHolds( *env_.current(), ammAccountID, - issue1, - issue2, + asset1, + asset2, FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, env_.journal); auto const lptAMMBalance = account ? ammLPHolds(*env_.current(), *amm, *account, env_.journal) @@ -211,7 +224,7 @@ AMM::expectBalances( std::optional const& account) const { auto const [asset1Balance, asset2Balance, lptAMMBalance] = - balances(asset1.issue(), asset2.issue(), account); + balances(asset1.asset(), asset2.asset(), account); return asset1 == asset1Balance && asset2 == asset2Balance && lptAMMBalance == STAmount{lpt, lptIssue_}; } @@ -229,7 +242,7 @@ AMM::getLPTokensBalance(std::optional const& account) const env_.journal) .iou(); } - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) return amm->getFieldAmount(sfLPTokenBalance).iou(); return IOUAmount{0}; } @@ -237,7 +250,7 @@ AMM::getLPTokensBalance(std::optional const& account) const bool AMM::expectLPTokens(AccountID const& account, IOUAmount const& expTokens) const { - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) { auto const lptAMMBalance = ammLPHolds(*env_.current(), *amm, account, env_.journal); return lptAMMBalance == STAmount{expTokens, lptIssue_}; @@ -283,7 +296,7 @@ AMM::expectAuctionSlot(std::vector const& authAccounts) const bool AMM::expectTradingFee(std::uint16_t fee) const { - auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())); + auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset())); return amm && (*amm)[sfTradingFee] == fee; } @@ -291,7 +304,7 @@ bool AMM::ammExists() const { return env_.current()->read(keylet::account(ammAccount_)) != nullptr && - env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue())) != nullptr; + env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset())) != nullptr; } bool @@ -329,14 +342,14 @@ AMM::expectAmmInfo( if (!amountFromJsonNoThrow(lptBalance, jv[jss::lp_token])) return false; // ammRpcInfo returns unordered assets - if (asset1Info.issue() != asset1.issue()) + if (asset1Info.asset() != asset1.asset()) std::swap(asset1Info, asset2Info); return asset1 == asset1Info && asset2 == asset2Info && lptBalance == STAmount{balance, lptIssue_}; } void -AMM::setTokens(Json::Value& jv, std::optional> const& assets) +AMM::setTokens(Json::Value& jv, std::optional> const& assets) { if (assets) { @@ -345,28 +358,65 @@ AMM::setTokens(Json::Value& jv, std::optional> const& as } else { - jv[jss::Asset] = STIssue(sfAsset, asset1_.issue()).getJson(JsonOptions::none); - jv[jss::Asset2] = STIssue(sfAsset, asset2_.issue()).getJson(JsonOptions::none); + jv[jss::Asset] = STIssue(sfAsset, asset1_.asset()).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, asset2_.asset()).getJson(JsonOptions::none); } } -IOUAmount -AMM::deposit( - std::optional const& account, - Json::Value& jv, - std::optional> const& assets, - std::optional const& seq, - std::optional const& ter) +Json::Value +AMM::depositJv(DepositArg const& arg) { - auto const& acct = account ? *account : creatorAccount_; - auto const lpTokens = getLPTokensBalance(acct); - jv[jss::Account] = acct.human(); - setTokens(jv, assets); + Json::Value jv; + if (!arg.account || !arg.assets) + Throw("AMM::depositJv: account or assets not set"); + + jv[jss::Account] = arg.account->human(); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::none); + if (arg.tokens) + arg.tokens->tokens().setJson(jv[jss::LPTokenOut]); + if (arg.asset1In) + arg.asset1In->setJson(jv[jss::Amount]); + if (arg.asset2In) + arg.asset2In->setJson(jv[jss::Amount2]); + if (arg.maxEP) + arg.maxEP->setJson(jv[jss::EPrice]); + if (arg.tfee) + jv[jss::TradingFee] = *arg.tfee; + std::uint32_t flags = 0; + if (arg.flags) + flags = *arg.flags; + // If including asset1In and asset2In or tokens as + // deposit min amounts then must set the flags + // explicitly instead of relying on this logic. + if ((flags & tfDepositSubTx) == 0u) + { + if (arg.tokens && !arg.asset1In) + { + flags |= tfLPToken; + } + else if (arg.tokens && arg.asset1In) + { + flags |= tfOneAssetLPToken; + } + else if (arg.asset1In && arg.asset2In) + { + flags |= tfTwoAsset; + } + else if (arg.maxEP && arg.asset1In) + { + flags |= tfLimitLPToken; + } + else if (arg.asset1In) + { + flags |= tfSingleAsset; + } + } + jv[jss::Flags] = flags; + jv[jss::TransactionType] = jss::AMMDeposit; - if (fee_ != 0) - jv[jss::Fee] = std::to_string(fee_); - submit(jv, seq, ter); - return getLPTokensBalance(acct) - lpTokens; + + return jv; } IOUAmount @@ -399,7 +449,8 @@ AMM::deposit( std::optional const& flags, std::optional const& ter) { - assert(!(asset2In && maxEP)); + if (asset2In && maxEP) + Throw("Invalid options: asset2In and maxEP"); return deposit( account, std::nullopt, @@ -421,53 +472,26 @@ AMM::deposit( std::optional const& asset2In, std::optional const& maxEP, std::optional const& flags, - std::optional> const& assets, + std::optional> const& assets, std::optional const& seq, std::optional const& tfee, std::optional const& ter) { - Json::Value jv; - if (tokens) - tokens->tokens(lptIssue_).setJson(jv[jss::LPTokenOut]); - if (asset1In) - asset1In->setJson(jv[jss::Amount]); - if (asset2In) - asset2In->setJson(jv[jss::Amount2]); - if (maxEP) - maxEP->setJson(jv[jss::EPrice]); - if (tfee) - jv[jss::TradingFee] = *tfee; - std::uint32_t jvFlags = 0; - if (flags) - jvFlags = *flags; - // If including asset1In and asset2In or tokens as - // deposit min amounts then must set the flags - // explicitly instead of relying on this logic. - if ((jvFlags & tfDepositSubTx) == 0u) - { - if (tokens && !asset1In) - { - jvFlags |= tfLPToken; - } - else if (tokens && asset1In) - { - jvFlags |= tfOneAssetLPToken; - } - else if (asset1In && asset2In) - { - jvFlags |= tfTwoAsset; - } - else if (maxEP && asset1In) - { - jvFlags |= tfLimitLPToken; - } - else if (asset1In) - { - jvFlags |= tfSingleAsset; - } - } - jv[jss::Flags] = jvFlags; - return deposit(account, jv, assets, seq, ter); + auto const acct = account ? account : creatorAccount_; + auto const lpTokens = getLPTokensBalance(acct); + Json::Value jv = depositJv( + {.account = acct, + .tokens = tokens ? tokens->tokens(lptIssue_) : tokens, + .asset1In = asset1In, + .asset2In = asset2In, + .maxEP = maxEP, + .flags = flags, + .assets = assets ? assets : std::make_pair(asset1_.asset(), asset2_.asset()), + .tfee = tfee}); + if (fee_ != 0) + jv[jss::Fee] = std::to_string(fee_); + submit(jv, seq, ter); + return getLPTokensBalance(acct) - lpTokens; } IOUAmount @@ -486,23 +510,54 @@ AMM::deposit(DepositArg const& arg) arg.err); } -IOUAmount -AMM::withdraw( - std::optional const& account, - Json::Value& jv, - std::optional const& seq, - std::optional> const& assets, - std::optional const& ter) +Json::Value +AMM::withdrawJv(WithdrawArg const& arg) { - auto const& acct = account ? *account : creatorAccount_; - auto const lpTokens = getLPTokensBalance(acct); - jv[jss::Account] = acct.human(); - setTokens(jv, assets); + Json::Value jv; + if (!arg.account || !arg.assets) + Throw("AMM::withdrawJv: account or assets not set"); + jv[jss::Account] = arg.account->human(); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::none); + if (arg.tokens) + arg.tokens->tokens().setJson(jv[jss::LPTokenIn]); + if (arg.asset1Out) + arg.asset1Out->setJson(jv[jss::Amount]); + if (arg.asset2Out) + arg.asset2Out->setJson(jv[jss::Amount2]); + if (arg.maxEP) + arg.maxEP->tokens().setJson(jv[jss::EPrice]); + std::uint32_t flags = 0; + if (arg.flags) + flags = *arg.flags; + if ((flags & tfWithdrawSubTx) == 0u) + { + if (arg.tokens && !arg.asset1Out) + { + flags |= tfLPToken; + } + else if (arg.asset1Out && arg.asset2Out) + { + flags |= tfTwoAsset; + } + else if (arg.tokens && arg.asset1Out) + { + flags |= tfOneAssetLPToken; + } + else if (arg.asset1Out && arg.maxEP) + { + flags |= tfLimitLPToken; + } + else if (arg.asset1Out) + { + flags |= tfSingleAsset; + } + } + jv[jss::Flags] = flags; + jv[jss::TransactionType] = jss::AMMWithdraw; - if (fee_ != 0) - jv[jss::Fee] = std::to_string(fee_); - submit(jv, seq, ter); - return lpTokens - getLPTokensBalance(acct); + + return jv; } IOUAmount @@ -530,10 +585,11 @@ AMM::withdraw( std::optional const& account, STAmount const& asset1Out, std::optional const& asset2Out, - std::optional const& maxEP, + std::optional const& maxEP, std::optional const& ter) { - assert(!(asset2Out && maxEP)); + if (asset2Out && maxEP) + Throw("Invalid options: asset2Out and maxEP"); return withdraw( account, std::nullopt, @@ -552,52 +608,27 @@ AMM::withdraw( std::optional const& tokens, std::optional const& asset1Out, std::optional const& asset2Out, - std::optional const& maxEP, + std::optional const& maxEP, std::optional const& flags, - std::optional> const& assets, + std::optional> const& assets, std::optional const& seq, std::optional const& ter) { - Json::Value jv; - if (tokens) - tokens->tokens(lptIssue_).setJson(jv[jss::LPTokenIn]); - if (asset1Out) - asset1Out->setJson(jv[jss::Amount]); - if (asset2Out) - asset2Out->setJson(jv[jss::Amount2]); - if (maxEP) - { - STAmount const saMaxEP{*maxEP, lptIssue_}; - saMaxEP.setJson(jv[jss::EPrice]); - } - std::uint32_t jvFlags = 0; - if (flags) - jvFlags = *flags; - if ((jvFlags & tfWithdrawSubTx) == 0u) - { - if (tokens && !asset1Out) - { - jvFlags |= tfLPToken; - } - else if (asset1Out && asset2Out) - { - jvFlags |= tfTwoAsset; - } - else if (tokens && asset1Out) - { - jvFlags |= tfOneAssetLPToken; - } - else if (asset1Out && maxEP) - { - jvFlags |= tfLimitLPToken; - } - else if (asset1Out) - { - jvFlags |= tfSingleAsset; - } - } - jv[jss::Flags] = jvFlags; - return withdraw(account, jv, seq, assets, ter); + auto const acct = account ? account : creatorAccount_; + auto const lpTokens = getLPTokensBalance(acct); + Json::Value jv = withdrawJv({ + .account = acct, + .tokens = tokens ? tokens->tokens(lptIssue_) : tokens, + .asset1Out = asset1Out, + .asset2Out = asset2Out, + .maxEP = maxEP ? maxEP->tokens(lptIssue_) : maxEP, + .flags = flags, + .assets = assets ? assets : std::make_pair(asset1_.asset(), asset2_.asset()), + }); + if (fee_ != 0) + jv[jss::Fee] = std::to_string(fee_); + submit(jv, seq, ter); + return lpTokens - getLPTokensBalance(acct); } IOUAmount @@ -615,22 +646,39 @@ AMM::withdraw(WithdrawArg const& arg) arg.err); } +Json::Value +AMM::voteJv(VoteArg const& arg) +{ + Json::Value jv; + if (!arg.account || !arg.assets) + Throw("AMM::withdrawJv: account or assets not set"); + jv[jss::Account] = arg.account->human(); + jv[jss::Asset] = STIssue(sfAsset, arg.assets->first).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, arg.assets->second).getJson(JsonOptions::none); + jv[jss::TradingFee] = arg.tfee; + if (arg.flags) + jv[jss::Flags] = *arg.flags; + + jv[jss::TransactionType] = jss::AMMVote; + + return jv; +} + void AMM::vote( std::optional const& account, std::uint32_t feeVal, std::optional const& flags, std::optional const& seq, - std::optional> const& assets, + std::optional> const& assets, std::optional const& ter) { - Json::Value jv; - jv[jss::Account] = account ? account->human() : creatorAccount_.human(); - setTokens(jv, assets); - jv[jss::TradingFee] = feeVal; - jv[jss::TransactionType] = jss::AMMVote; - if (flags) - jv[jss::Flags] = *flags; + Json::Value jv = voteJv({ + .account = account ? account : creatorAccount_, + .tfee = feeVal, + .flags = flags, + .assets = assets ? assets : std::make_pair(asset1_.asset(), asset2_.asset()), + }); if (fee_ != 0) jv[jss::Fee] = std::to_string(fee_); submit(jv, seq, ter); @@ -645,11 +693,11 @@ AMM::vote(VoteArg const& arg) Json::Value AMM::bid(BidArg const& arg) { - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) { - assert( - !env_.current()->rules().enabled(fixInnerObjTemplate) || - amm->isFieldPresent(sfAuctionSlot)); + if (env_.current()->rules().enabled(fixInnerObjTemplate) && + !amm->isFieldPresent(sfAuctionSlot)) + Throw("AMM::Bid"); if (amm->isFieldPresent(sfAuctionSlot)) { auto const& auctionSlot = @@ -708,6 +756,22 @@ AMM::bid(BidArg const& arg) return jv; } +void +AMM::clawback(ClawbackArg const& arg) +{ + auto const& [asset, asset2] = [&]() { + if (arg.assets) + return *arg.assets; + return std::make_pair(asset1_.asset(), asset2_.asset()); + }(); + auto jv = amm::ammClawback(arg.issuer, arg.holder, asset, asset2, arg.amount); + if (arg.flags) + jv[jss::Flags] = *arg.flags; + if (fee_ != 0) + jv[jss::Fee] = std::to_string(fee_); + submit(jv, std::nullopt, arg.err); +} + void AMM::submit( Json::Value const& jv, @@ -758,11 +822,11 @@ AMM::submit( bool AMM::expectAuctionSlot(auto&& cb) const { - if (auto const amm = env_.current()->read(keylet::amm(asset1_.issue(), asset2_.issue()))) + if (auto const amm = env_.current()->read(keylet::amm(asset1_.asset(), asset2_.asset()))) { - assert( - !env_.current()->rules().enabled(fixInnerObjTemplate) || - amm->isFieldPresent(sfAuctionSlot)); + if (env_.current()->rules().enabled(fixInnerObjTemplate) && + !amm->isFieldPresent(sfAuctionSlot)) + Throw("AMM::expectAuctionSlot"); if (amm->isFieldPresent(sfAuctionSlot)) { auto const& auctionSlot = @@ -785,48 +849,36 @@ AMM::expectAuctionSlot(auto&& cb) const return false; } -void -AMM::ammDelete(AccountID const& deleter, std::optional const& ter) +Json::Value +AMM::deleteJv(AccountID const& account, Asset const& asset1, Asset const& asset2) { Json::Value jv; - jv[jss::Account] = to_string(deleter); - setTokens(jv); + jv[jss::Account] = to_string(account); + jv[jss::Asset] = STIssue(sfAsset, asset1).getJson(JsonOptions::none); + jv[jss::Asset2] = STIssue(sfAsset, asset2).getJson(JsonOptions::none); + jv[jss::TransactionType] = jss::AMMDelete; + + return jv; +} + +void +AMM::ammDelete(AccountID const& account, std::optional const& ter) +{ + Json::Value jv = deleteJv(account, asset1_.asset(), asset2_.asset()); if (fee_ != 0) jv[jss::Fee] = std::to_string(fee_); submit(jv, std::nullopt, ter); } namespace amm { -Json::Value -trust(AccountID const& account, STAmount const& amount, std::uint32_t flags) -{ - if (isXRP(amount)) - Throw("trust() requires IOU"); - Json::Value jv; - jv[jss::Account] = to_string(account); - jv[jss::LimitAmount] = amount.getJson(JsonOptions::none); - jv[jss::TransactionType] = jss::TrustSet; - jv[jss::Flags] = flags; - return jv; -} -Json::Value -pay(Account const& account, AccountID const& to, STAmount const& amount) -{ - Json::Value jv; - jv[jss::Account] = account.human(); - jv[jss::Amount] = amount.getJson(JsonOptions::none); - jv[jss::Destination] = to_string(to); - jv[jss::TransactionType] = jss::Payment; - return jv; -} Json::Value ammClawback( Account const& issuer, Account const& holder, - Issue const& asset, - Issue const& asset2, + Asset const& asset, + Asset const& asset2, std::optional const& amount) { Json::Value jv; diff --git a/src/test/jtx/impl/AMMTest.cpp b/src/test/jtx/impl/AMMTest.cpp index 9d9a537210..9527dd1e4e 100644 --- a/src/test/jtx/impl/AMMTest.cpp +++ b/src/test/jtx/impl/AMMTest.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include @@ -14,7 +15,7 @@ namespace xrpl { namespace test { namespace jtx { -void +[[maybe_unused]] std::vector fund( jtx::Env& env, jtx::Account const& gw, @@ -22,16 +23,17 @@ fund( std::vector const& amts, Fund how) { - fund(env, gw, accounts, XRP(30000), amts, how); + return fund(env, gw, accounts, XRP(30000), amts, how); } -void +[[maybe_unused]] std::vector fund( jtx::Env& env, std::vector const& accounts, STAmount const& xrp, std::vector const& amts, - Fund how) + Fund how, + std::optional const& mptIssuer) { for (auto const& account : accounts) { @@ -41,18 +43,37 @@ fund( } } env.close(); + + std::vector amtsOut; for (auto const& account : accounts) { + int i = 0; for (auto const& amt : amts) { - env.trust(amt + amt, account); - env(pay(amt.issue().account, account, amt)); + auto amt_ = [&]() { + if (amtsOut.size() == amts.size()) + { + return amtsOut[i++]; + } + if (amt.holds() && mptIssuer) + { + MPTTester const mpt({.env = env, .issuer = *mptIssuer, .holders = accounts}); + return STAmount{mpt.issuanceID(), amt.mpt().value()}; + } + return amt; + }(); + if (amt.holds()) + env.trust(amt_ + amt_, account); + if (amtsOut.size() != amts.size()) + amtsOut.push_back(amt_); + env(pay(amt_.getIssuer(), account, amt_)); } } env.close(); + return amtsOut; } -void +[[maybe_unused]] std::vector fund( jtx::Env& env, jtx::Account const& gw, @@ -64,7 +85,7 @@ fund( if (how == Fund::All || how == Fund::Gw) env.fund(xrp, gw); env.close(); - fund(env, accounts, xrp, amts, how); + return fund(env, accounts, xrp, amts, how, gw); } AMMTestBase::AMMTestBase() @@ -119,31 +140,41 @@ AMMTestBase::testAMM(std::function const& cb, TestAM return defXRP; return a + XRP(1000); } - auto defIOU = STAmount{a.issue(), 30000}; - if (a <= defIOU) - return defIOU; - return a + STAmount{a.issue(), 1000}; + auto defAmt = STAmount{a.asset(), 30000}; + if (a <= defAmt) + return defAmt; + return a + STAmount{a.asset(), 1000}; }; auto const toFund1 = toFund(asset1); auto const toFund2 = toFund(asset2); BEAST_EXPECT(asset1 <= toFund1 && asset2 <= toFund2); + // asset1/asset2 could be dummy MPT. In this case real MPT + // is created by fund(), which returns the funded amounts. + // The amounts then can be used to figure out the created + // MPT if any. + std::vector funded; if (!asset1.native() && !asset2.native()) { - fund(env, gw, {alice, carol}, {toFund1, toFund2}, Fund::All); + funded = fund(env, gw, {alice, carol}, {toFund1, toFund2}, Fund::All); } else if (asset1.native()) { - fund(env, gw, {alice, carol}, toFund1, {toFund2}, Fund::All); + funded = fund(env, gw, {alice, carol}, toFund1, {toFund2}, Fund::All); + funded.insert(funded.begin(), toFund1); } else if (asset2.native()) { - fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); + funded = fund(env, gw, {alice, carol}, toFund2, {toFund1}, Fund::All); + funded.push_back(toFund2); } + auto const pool1 = STAmount{funded[0].asset(), static_cast(asset1)}; + auto const pool2 = STAmount{funded[1].asset(), static_cast(asset2)}; + AMM ammAlice( - env, alice, asset1, asset2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); - if (BEAST_EXPECT(ammAlice.expectBalances(asset1, asset2, ammAlice.tokens()))) + env, alice, pool1, pool2, CreateArg{.log = false, .tfee = arg.tfee, .err = arg.ter}); + if (BEAST_EXPECT(ammAlice.expectBalances(pool1, pool2, ammAlice.tokens()))) cb(ammAlice, env); } } @@ -173,111 +204,6 @@ AMMTest::pathTestEnv() return cfg; })); } - -Json::Value -AMMTest::find_paths_request( - jtx::Env& env, - jtx::Account const& src, - jtx::Account const& dst, - STAmount const& saDstAmount, - std::optional const& saSendMax, - std::optional const& saSrcCurrency) -{ - using namespace jtx; - - auto& app = env.app(); - Resource::Charge loadType = Resource::feeReferenceRPC; - Resource::Consumer c; - - RPC::JsonContext context{ - {env.journal, - app, - loadType, - app.getOPs(), - app.getLedgerMaster(), - c, - Role::USER, - {}, - {}, - RPC::apiVersionIfUnspecified}, - {}, - {}}; - - Json::Value params = Json::objectValue; - params[jss::command] = "ripple_path_find"; - params[jss::source_account] = toBase58(src); - params[jss::destination_account] = toBase58(dst); - params[jss::destination_amount] = saDstAmount.getJson(JsonOptions::none); - if (saSendMax) - params[jss::send_max] = saSendMax->getJson(JsonOptions::none); - if (saSrcCurrency) - { - auto& sc = params[jss::source_currencies] = Json::arrayValue; - Json::Value j = Json::objectValue; - j[jss::currency] = to_string(saSrcCurrency.value()); - sc.append(j); - } - - Json::Value result; - gate g; - app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { - context.params = std::move(params); - context.coro = coro; - RPC::doCommand(context, result); - g.signal(); - }); - - using namespace std::chrono_literals; - BEAST_EXPECT(g.wait_for(5s)); - BEAST_EXPECT(!result.isMember(jss::error)); - return result; -} - -std::tuple -AMMTest::find_paths( - jtx::Env& env, - jtx::Account const& src, - jtx::Account const& dst, - STAmount const& saDstAmount, - std::optional const& saSendMax, - std::optional const& saSrcCurrency) -{ - Json::Value result = find_paths_request(env, src, dst, saDstAmount, saSendMax, saSrcCurrency); - BEAST_EXPECT(!result.isMember(jss::error)); - - STAmount da; - if (result.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, result[jss::destination_amount]); - - STAmount sa; - STPathSet paths; - if (result.isMember(jss::alternatives)) - { - auto const& alts = result[jss::alternatives]; - if (alts.size() > 0) - { - auto const& path = alts[0u]; - - if (path.isMember(jss::source_amount)) - sa = amountFromJson(sfGeneric, path[jss::source_amount]); - - if (path.isMember(jss::destination_amount)) - da = amountFromJson(sfGeneric, path[jss::destination_amount]); - - if (path.isMember(jss::paths_computed)) - { - Json::Value p; - p["Paths"] = path[jss::paths_computed]; - STParsedJSONObject po("generic", p); - // NOLINTNEXTLINE(bugprone-unchecked-optional-access) - paths = po.object->getFieldPathSet(sfPaths); - } - } - } - - return std::make_tuple(std::move(paths), std::move(sa), std::move(da)); -} - } // namespace jtx } // namespace test } // namespace xrpl diff --git a/src/test/jtx/impl/Env.cpp b/src/test/jtx/impl/Env.cpp index a6344b5ab1..bba10439ed 100644 --- a/src/test/jtx/impl/Env.cpp +++ b/src/test/jtx/impl/Env.cpp @@ -174,54 +174,47 @@ Env::balance(Account const& account) const } PrettyAmount -Env::balance(Account const& account, Issue const& issue) const -{ - if (isXRP(issue.currency)) - return balance(account); - auto const sle = le(keylet::line(account.id(), issue)); - if (!sle) - return {STAmount(issue, 0), account.name()}; - auto amount = sle->getFieldAmount(sfBalance); - amount.setIssuer(issue.account); - if (account.id() > issue.account) - amount.negate(); - return {amount, lookup(issue.account).name()}; -} - -PrettyAmount -Env::balance(Account const& account, MPTIssue const& mptIssue) const -{ - MPTID const id = mptIssue.getMptID(); - if (!id) - return {STAmount(mptIssue, 0), account.name()}; - - AccountID const issuer = mptIssue.getIssuer(); - if (account.id() == issuer) - { - // Issuer balance - auto const sle = le(keylet::mptIssuance(id)); - if (!sle) - return {STAmount(mptIssue, 0), account.name()}; - - // Make it negative - STAmount const amount{mptIssue, sle->getFieldU64(sfOutstandingAmount), 0, true}; - return {amount, lookup(issuer).name()}; - } - - // Holder balance - auto const sle = le(keylet::mptoken(id, account)); - if (!sle) - return {STAmount(mptIssue, 0), account.name()}; - - STAmount const amount{mptIssue, sle->getFieldU64(sfMPTAmount)}; - return {amount, lookup(issuer).name()}; -} - -PrettyAmount -// NOLINTNEXTLINE(readability-convert-member-functions-to-static) Env::balance(Account const& account, Asset const& asset) const { - return std::visit([&](auto const& issue) { return balance(account, issue); }, asset.value()); + return asset.visit( + [&](Issue const& issue) -> PrettyAmount { + if (isXRP(issue.currency)) + return balance(account); + auto const sle = le(keylet::line(account.id(), issue)); + if (!sle) + return {STAmount(issue, 0), account.name()}; + auto amount = sle->getFieldAmount(sfBalance); + amount.get().account = issue.account; + if (account.id() > issue.account) + amount.negate(); + return {amount, lookup(issue.account).name()}; + }, + [&](MPTIssue const& mptIssue) -> PrettyAmount { + MPTID const& id = mptIssue.getMptID(); + if (!id) + return {STAmount(mptIssue, 0), account.name()}; + + AccountID const& issuer = mptIssue.getIssuer(); + if (account.id() == issuer) + { + // Issuer balance + auto const sle = le(keylet::mptIssuance(id)); + if (!sle) + return {STAmount(mptIssue, 0), account.name()}; + + // Make it negative + STAmount const amount{mptIssue, sle->getFieldU64(sfOutstandingAmount), 0, true}; + return {amount, lookup(issuer).name()}; + } + + // Holder balance + auto const sle = le(keylet::mptoken(id, account)); + if (!sle) + return {STAmount(mptIssue, 0), account.name()}; + + STAmount const amount{mptIssue, sle->getFieldU64(sfMPTAmount)}; + return {amount, lookup(issuer).name()}; + }); } PrettyAmount @@ -300,6 +293,8 @@ Env::fund(bool setDefaultRipple, STAmount const& amount, Account const& account) void Env::trust(STAmount const& amount, Account const& account) { + if (!amount.holds()) + Throw("Env::trust: amount doesn't hold Issue"); auto const start = balance(account); apply( jtx::trust(account, amount), diff --git a/src/test/jtx/impl/TestHelpers.cpp b/src/test/jtx/impl/TestHelpers.cpp index e10a0c46d0..8010f171f7 100644 --- a/src/test/jtx/impl/TestHelpers.cpp +++ b/src/test/jtx/impl/TestHelpers.cpp @@ -1,9 +1,16 @@ #include +#include #include #include +#include +#include + +#include #include +#include #include +#include namespace xrpl { namespace test { @@ -55,7 +62,7 @@ stpath_append_one(STPath& st, STPathElement const& pe) bool equal(STAmount const& sa1, STAmount const& sa2) { - return sa1 == sa2 && sa1.issue().account == sa2.issue().account; + return sa1 == sa2 && sa1.getIssuer() == sa2.getIssuer(); } // Issue path element @@ -65,9 +72,211 @@ IPE(Issue const& iss) return STPathElement( STPathElement::typeCurrency | STPathElement::typeIssuer, xrpAccount(), - iss.currency, + PathAsset{iss.currency}, iss.account); } +STPathElement +IPE(MPTIssue const& iss) +{ + return STPathElement( + STPathElement::typeMPT | STPathElement::typeIssuer, + xrpAccount(), + PathAsset{iss.getMptID()}, + iss.getIssuer()); +} + +static void +addSourceAsset( + Json::Value& jv, + PathAsset const& srcAsset, + std::optional const& srcIssuer) +{ + std::visit( + [&](TAsset const& asset) { + if constexpr (std::is_same_v) + { + jv[jss::currency] = to_string(asset); + if (srcIssuer) + jv[jss::issuer] = to_string(*srcIssuer); + } + else + { + if (srcIssuer) + Throw("MPT source_currencies can't have issuer"); + jv[jss::mpt_issuance_id] = to_string(asset); + } + }, + srcAsset.value()); +} + +Json::Value +rpf(jtx::Account const& src, + jtx::Account const& dst, + STAmount const& dstAmount, + std::optional const& sendMax, + std::optional const& srcAsset, + std::optional const& srcIssuer) +{ + Json::Value jv = Json::objectValue; + jv[jss::command] = "ripple_path_find"; + jv[jss::source_account] = toBase58(src); + jv[jss::destination_account] = toBase58(dst); + jv[jss::destination_amount] = dstAmount.getJson(JsonOptions::none); + if (sendMax) + jv[jss::send_max] = sendMax->getJson(JsonOptions::none); + if (srcAsset) + { + auto& sc = jv[jss::source_currencies] = Json::arrayValue; + Json::Value j = Json::objectValue; + addSourceAsset(j, *srcAsset, srcIssuer); + sc.append(j); + } + + return jv; +} + +jtx::Env +pathTestEnv(beast::unit_test::suite& suite) +{ + // These tests were originally written with search parameters that are + // different from the current defaults. This function creates an env + // with the search parameters that the tests were written for. + using namespace jtx; + return Env(suite, envconfig([](std::unique_ptr cfg) { + cfg->PATH_SEARCH_OLD = 7; + cfg->PATH_SEARCH = 7; + cfg->PATH_SEARCH_MAX = 10; + return cfg; + })); +} + +Json::Value +find_paths_request( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax, + std::optional const& srcAsset, + std::optional const& srcIssuer, + std::optional const& domain) +{ + using namespace jtx; + + auto& app = env.app(); + Resource::Charge loadType = Resource::feeReferenceRPC; + Resource::Consumer c; + + RPC::JsonContext context{ + {env.journal, + app, + loadType, + app.getOPs(), + app.getLedgerMaster(), + c, + Role::USER, + {}, + {}, + RPC::apiVersionIfUnspecified}, + {}, + {}}; + + Json::Value params = Json::objectValue; + params[jss::command] = "ripple_path_find"; + params[jss::source_account] = toBase58(src); + params[jss::destination_account] = toBase58(dst); + params[jss::destination_amount] = saDstAmount.getJson(JsonOptions::none); + if (saSendMax) + params[jss::send_max] = saSendMax->getJson(JsonOptions::none); + + if (srcAsset) + { + auto& sc = params[jss::source_currencies] = Json::arrayValue; + Json::Value j = Json::objectValue; + addSourceAsset(j, *srcAsset, srcIssuer); + sc.append(j); + } + + if (domain) + params[jss::domain] = to_string(*domain); + + Json::Value result; + gate g; + app.getJobQueue().postCoro(jtCLIENT, "RPC-Client", [&](auto const& coro) { + context.params = std::move(params); + context.coro = coro; + RPC::doCommand(context, result); + g.signal(); + }); + + using namespace std::chrono_literals; + using namespace beast::unit_test; + g.wait_for(5s); + return result; +} + +std::tuple +find_paths( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax, + std::optional const& srcAsset, + std::optional const& srcIssuer, + std::optional const& domain) +{ + Json::Value result = + find_paths_request(env, src, dst, saDstAmount, saSendMax, srcAsset, srcIssuer, domain); + if (result.isMember(jss::error)) + return std::make_tuple(STPathSet{}, STAmount{}, STAmount{}); + + STAmount da; + if (result.isMember(jss::destination_amount)) + da = amountFromJson(sfGeneric, result[jss::destination_amount]); + + STAmount sa; + STPathSet paths; + if (result.isMember(jss::alternatives)) + { + auto const& alts = result[jss::alternatives]; + if (alts.size() > 0) + { + auto const& path = alts[0u]; + + if (path.isMember(jss::source_amount)) + sa = amountFromJson(sfGeneric, path[jss::source_amount]); + + if (path.isMember(jss::destination_amount)) + da = amountFromJson(sfGeneric, path[jss::destination_amount]); + + if (path.isMember(jss::paths_computed)) + { + Json::Value p; + p["Paths"] = path[jss::paths_computed]; + STParsedJSONObject po("generic", p); + paths = po.object->getFieldPathSet(sfPaths); + } + } + } + + return std::make_tuple(std::move(paths), std::move(sa), std::move(da)); +} + +std::tuple +find_paths_by_element( + jtx::Env& env, + jtx::Account const& src, + jtx::Account const& dst, + STAmount const& saDstAmount, + std::optional const& saSendMax, + std::optional const& srcElement, + std::optional const& srcIssuer, + std::optional const& domain) +{ + return find_paths( + env, src, dst, saDstAmount, saSendMax, srcElement->getPathAsset(), srcIssuer, domain); +} /******************************************************************************/ @@ -87,9 +296,9 @@ xrpMinusFee(Env const& env, std::int64_t xrpAmount) [[nodiscard]] bool expectHolding(Env& env, AccountID const& account, STAmount const& value, bool defaultLimits) { - if (auto const sle = env.le(keylet::line(account, value.issue()))) + if (auto const sle = env.le(keylet::line(account, value.get()))) { - Issue const issue = value.issue(); + Issue const issue = value.get(); bool const accountLow = account < issue.account; bool expectDefaultTrustLine = true; @@ -98,15 +307,15 @@ expectHolding(Env& env, AccountID const& account, STAmount const& value, bool de STAmount low{issue}; STAmount high{issue}; - low.setIssuer(accountLow ? account : issue.account); - high.setIssuer(accountLow ? issue.account : account); + low.get().account = accountLow ? account : issue.account; + high.get().account = accountLow ? issue.account : account; expectDefaultTrustLine = sle->getFieldAmount(sfLowLimit) == low && sle->getFieldAmount(sfHighLimit) == high; } auto amount = sle->getFieldAmount(sfBalance); - amount.setIssuer(value.issue().account); + amount.get().account = value.getIssuer(); if (!accountLow) amount.negate(); return amount == value && expectDefaultTrustLine; @@ -134,6 +343,14 @@ expectHolding(Env& env, AccountID const& account, None const& value) value.asset.value()); } +[[nodiscard]] bool +expectMPT(Env& env, AccountID const& account, STAmount const& value) +{ + auto const mptIssuanceID = keylet::mptIssuance(value.asset().get()); + auto const mptToken = env.le(keylet::mptoken(mptIssuanceID.key, account)); + return mptToken && (*mptToken)[sfMPTAmount] == value.mpt().value(); +} + [[nodiscard]] bool expectOffers( Env& env, @@ -157,7 +374,7 @@ expectOffers( } return true; }); - return size == cnt && matched == toMatch.size(); + return size == cnt && ((toMatch.empty() && size != 0) || (matched == toMatch.size())); } Json::Value @@ -185,6 +402,34 @@ ledgerEntryState( return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; } +Json::Value +ledgerEntryOffer(jtx::Env& env, jtx::Account const& acct, std::uint32_t offer_seq) +{ + Json::Value jvParams; + jvParams[jss::offer][jss::account] = acct.human(); + jvParams[jss::offer][jss::seq] = offer_seq; + return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; +} + +Json::Value +ledgerEntryMPT(jtx::Env& env, jtx::Account const& acct, MPTID const& mptID) +{ + Json::Value jvParams; + jvParams[jss::mptoken][jss::account] = acct.human(); + jvParams[jss::mptoken][jss::mpt_issuance_id] = to_string(mptID); + return env.rpc("json", "ledger_entry", to_string(jvParams))[jss::result]; +} + +Json::Value +getBookOffers(jtx::Env& env, Asset const& taker_pays, Asset const& taker_gets) +{ + Json::Value jvbp; + jvbp[jss::ledger_index] = "current"; + taker_pays.setJson(jvbp[jss::taker_pays]); + taker_gets.setJson(jvbp[jss::taker_gets]); + return env.rpc("json", "book_offers", to_string(jvbp))[jss::result]; +} + Json::Value accountBalance(Env& env, Account const& acct) { @@ -312,22 +557,133 @@ n_offers(Env& env, std::size_t n, Account const& account, STAmount const& in, ST // Currency path element STPathElement -cpe(Currency const& c) +cpe(PathAsset const& pa) { - return STPathElement(STPathElement::typeCurrency, xrpAccount(), c, xrpAccount()); + return pa.visit( + [](Currency const& currency) { + return STPathElement(STPathElement::typeCurrency, xrpAccount(), currency, xrpAccount()); + }, + [](MPTID const& mpt) { + return STPathElement(STPathElement::typeMPT, xrpAccount(), mpt, xrpAccount()); + }); }; // All path element STPathElement -allPathElements(AccountID const& a, Issue const& iss) +allPathElements(AccountID const& a, Asset const& asset) { - return STPathElement( - STPathElement::typeAccount | STPathElement::typeCurrency | STPathElement::typeIssuer, - a, - iss.currency, - iss.account); + return STPathElement(a, asset, asset.getIssuer()); }; +STPathElement +ipe(Asset const& asset) +{ + return asset.visit( + [](Issue const& issue) { + return STPathElement( + STPathElement::typeCurrency | STPathElement::typeIssuer, + xrpAccount(), + issue.currency, + issue.account); + }, + [](MPTIssue const& issue) { + return STPathElement( + STPathElement::typeMPT | STPathElement::typeIssuer, + xrpAccount(), + issue.getMptID(), + issue.getIssuer()); + }); +}; + +// Issuer path element +STPathElement +iape(AccountID const& account) +{ + return STPathElement(STPathElement::typeIssuer, xrpAccount(), xrpCurrency(), account); +}; + +// Account path element +STPathElement +ape(AccountID const& a) +{ + return STPathElement(STPathElement::typeAccount, a, xrpCurrency(), xrpAccount()); +}; + +bool +equal(std::unique_ptr const& s1, DirectStepInfo const& dsi) +{ + if (!s1) + return false; + return test::directStepEqual(*s1, dsi.src, dsi.dst, dsi.currency); +} + +bool +equal(std::unique_ptr const& s1, MPTEndpointStepInfo const& dsi) +{ + if (!s1) + return false; + return test::mptEndpointStepEqual(*s1, dsi.src, dsi.dst, dsi.mptid); +} + +bool +equal(std::unique_ptr const& s1, XRPEndpointStepInfo const& xrpStepInfo) +{ + if (!s1) + return false; + return test::xrpEndpointStepEqual(*s1, xrpStepInfo.acc); +} + +bool +equal(std::unique_ptr const& s1, xrpl::Book const& bsi) +{ + if (!s1) + return false; + return bookStepEqual(*s1, bsi); +} + +namespace detail { + +IOU +issueHelperIOU(IssuerArgs const& args) +{ + auto const iou = args.issuer[args.token]; + if (args.transferFee != 0) + { + auto const tfee = 1. + (static_cast(args.transferFee) / 100'000); + args.env(rate(args.issuer, tfee)); + } + for (auto const& account : args.holders) + { + args.env(trust(account, iou(args.limit.value_or(1'000)))); + } + return iou; +} + +MPT +issueHelperMPT(IssuerArgs const& args) +{ + using namespace jtx; + if (args.limit) + { + MPT const mpt = MPTTester( + {.env = args.env, + .issuer = args.issuer, + .holders = args.holders, + .transferFee = args.transferFee, + .maxAmt = args.limit}); + return mpt; + } + + MPT const mpt = MPTTester( + {.env = args.env, + .issuer = args.issuer, + .holders = args.holders, + .transferFee = args.transferFee}); + return mpt; +} + +} // namespace detail + /* LoanBroker */ /******************************************************************************/ diff --git a/src/test/jtx/impl/amount.cpp b/src/test/jtx/impl/amount.cpp index 25fcb5c8f0..c3ae76967a 100644 --- a/src/test/jtx/impl/amount.cpp +++ b/src/test/jtx/impl/amount.cpp @@ -9,25 +9,6 @@ namespace xrpl { namespace test { namespace jtx { -#if 0 -std::ostream& -operator<<(std::ostream&& os, - AnyAmount const& amount) -{ - if (amount.is_any) - { - os << amount.value.getText() << "/" << - to_string(amount.value.issue().currency) << - "*"; - return os; - } - os << amount.value.getText() << "/" << - to_string(amount.value.issue().currency) << - "(" << amount.name() << ")"; - return os; -} -#endif - PrettyAmount:: operator AnyAmount() const { @@ -54,39 +35,45 @@ to_places(T const d, std::uint8_t places) std::ostream& operator<<(std::ostream& os, PrettyAmount const& amount) { - if (amount.value().native()) - { - // measure in hundredths - auto const c = dropsPerXRP.drops() / 100; - auto const n = amount.value().mantissa(); - if (n < c) - { - if (amount.value().negative()) + amount.value().asset().visit( + [&](Issue const& issue) { + if (issue.native()) { - os << "-" << n << " drops"; + // measure in hundredths + auto const c = dropsPerXRP.drops() / 100; + auto const n = amount.value().mantissa(); + if (n < c) + { + if (amount.value().negative()) + { + os << "-" << n << " drops"; + } + else + { + os << n << " drops"; + } + } + else + { + auto const d = double(n) / dropsPerXRP.drops(); + if (amount.value().negative()) + { + os << "-"; + } + + os << to_places(d, 6) << " XRP"; + } } else { - os << n << " drops"; + os << amount.value().getText() << "/" << to_string(issue.currency) << "(" + << amount.name() << ")"; } - return os; - } - auto const d = double(n) / dropsPerXRP.drops(); - if (amount.value().negative()) - os << "-"; - - os << to_places(d, 6) << " XRP"; - } - else if (amount.value().holds()) - { - os << amount.value().getText() << "/" << to_string(amount.value().issue().currency) << "(" - << amount.name() << ")"; - } - else - { - auto const& mptIssue = amount.value().asset().get(); - os << amount.value().getText() << "/" << to_string(mptIssue) << "(" << amount.name() << ")"; - } + }, + [&](MPTIssue const& issue) { + os << amount.value().getText() << "/" << to_string(issue) << "(" << amount.name() + << ")"; + }); return os; } @@ -101,7 +88,7 @@ IOU::operator()(epsilon_t) const } PrettyAmount -IOU::operator()(detail::epsilon_multiple m) const +IOU::operator()(xrpl::detail::epsilon_multiple m) const { return {STAmount(issue(), safe_cast(m.n), -81), account.name()}; } @@ -109,7 +96,14 @@ IOU::operator()(detail::epsilon_multiple m) const std::ostream& operator<<(std::ostream& os, IOU const& iou) { - os << to_string(iou.issue().currency) << "(" << iou.account.name() << ")"; + os << to_string(iou.currency) << "(" << iou.account.name() << ")"; + return os; +} + +std::ostream& +operator<<(std::ostream& os, MPT const& mpt) +{ + os << to_string(mpt.issuanceID); return os; } diff --git a/src/test/jtx/impl/balance.cpp b/src/test/jtx/impl/balance.cpp index 1c3cc0b3c3..157c6c4d8e 100644 --- a/src/test/jtx/impl/balance.cpp +++ b/src/test/jtx/impl/balance.cpp @@ -35,8 +35,8 @@ doBalance(Env& env, AccountID const& account, bool none, STAmount const& value, else if (TEST_EXPECT(sle)) { auto amount = sle->getFieldAmount(sfBalance); - amount.setIssuer(issue.account); - if (account > issue.account) + amount.get().account = value.getIssuer(); + if (account > value.getIssuer()) amount.negate(); TEST_EXPECTS(amount == value, amount.getText()); } diff --git a/src/test/jtx/impl/mpt.cpp b/src/test/jtx/impl/mpt.cpp index 0a6af63450..c26f051797 100644 --- a/src/test/jtx/impl/mpt.cpp +++ b/src/test/jtx/impl/mpt.cpp @@ -84,6 +84,7 @@ makeMPTCreate(MPTInitDef const& arg) .transferFee = arg.transferFee, .pay = {{arg.holders, *arg.pay}}, .flags = arg.flags, + .mutableFlags = arg.mutableFlags, .authHolder = arg.authHolder}; } return { @@ -91,6 +92,7 @@ makeMPTCreate(MPTInitDef const& arg) .transferFee = arg.transferFee, .authorize = arg.holders, .flags = arg.flags, + .mutableFlags = arg.mutableFlags, .authHolder = arg.authHolder}; } diff --git a/src/test/jtx/impl/paths.cpp b/src/test/jtx/impl/paths.cpp index af72b8bd5a..718aca6979 100644 --- a/src/test/jtx/impl/paths.cpp +++ b/src/test/jtx/impl/paths.cpp @@ -30,11 +30,11 @@ paths::operator()(Env& env, JTx& jt) const } Pathfinder pf( - std::make_shared(env.current(), env.app().getJournal("RippleLineCache")), + std::make_shared(env.current(), env.app().getJournal("AssetCache")), from, to, - in_.currency, - in_.account, + in_, + in_.getIssuer(), amount, std::nullopt, domain, @@ -44,7 +44,7 @@ paths::operator()(Env& env, JTx& jt) const STPath fp; pf.computePathRanks(limit_); - auto const found = pf.getBestPaths(limit_, fp, {}, in_.account); + auto const found = pf.getBestPaths(limit_, fp, {}, in_.getIssuer()); // VFALCO TODO API to allow caller to examine the STPathSet // VFALCO isDefault should be renamed to empty() @@ -54,6 +54,11 @@ paths::operator()(Env& env, JTx& jt) const //------------------------------------------------------------------------------ +path::path(STPath const& p) +{ + jv_ = p.getJson(JsonOptions::none); +} + Json::Value& path::create() { @@ -77,16 +82,20 @@ void path::append_one(IOU const& iou) { auto& jv = create(); - jv["currency"] = to_string(iou.issue().currency); - jv["account"] = toBase58(iou.issue().account); + jv["currency"] = to_string(iou.currency); + jv["account"] = toBase58(iou.account); } void path::append_one(BookSpec const& book) { auto& jv = create(); - jv["currency"] = to_string(book.currency); - jv["issuer"] = toBase58(book.account); + book.asset.visit( + [&](Issue const& issue) { + jv["currency"] = to_string(issue.currency); + jv["issuer"] = toBase58(issue.account); + }, + [&](MPTIssue const& issue) { jv["mpt_issuance_id"] = to_string(issue.getMptID()); }); } void diff --git a/src/test/jtx/impl/xchain_bridge.cpp b/src/test/jtx/impl/xchain_bridge.cpp index 72d932463f..0e5a2c56d0 100644 --- a/src/test/jtx/impl/xchain_bridge.cpp +++ b/src/test/jtx/impl/xchain_bridge.cpp @@ -414,16 +414,17 @@ XChainBridgeObjects::XChainBridgeObjects() return r; }()) , reward(XRP(1)) - , split_reward_quorum(divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.issue())) - , split_reward_everyone(divide(reward, STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.issue())) + , split_reward_quorum(divide(reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), reward.get())) + , split_reward_everyone( + divide(reward, STAmount(UT_XCHAIN_DEFAULT_NUM_SIGNERS), reward.get())) , tiny_reward(drops(37)) , tiny_reward_split( - (divide(tiny_reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue()))) + (divide(tiny_reward, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.get()))) , tiny_reward_remainder( tiny_reward - - multiply(tiny_reward_split, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.issue())) + multiply(tiny_reward_split, STAmount(UT_XCHAIN_DEFAULT_QUORUM), tiny_reward.get())) , one_xrp(XRP(1)) - , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.issue())) + , xrp_dust(divide(one_xrp, STAmount(10000), one_xrp.get())) { } diff --git a/src/test/jtx/mpt.h b/src/test/jtx/mpt.h index 3990dd3087..96fbf30d90 100644 --- a/src/test/jtx/mpt.h +++ b/src/test/jtx/mpt.h @@ -5,6 +5,7 @@ #include #include +#include #include namespace xrpl { @@ -113,6 +114,7 @@ struct MPTInitDef std::uint16_t transferFee = 0; std::optional pay = std::nullopt; std::uint32_t flags = MPTDEXFlags; + std::optional mutableFlags = std::nullopt; bool authHolder = false; bool fund = false; bool close = true; @@ -272,6 +274,12 @@ public: operator Asset() const; + friend BookSpec + operator~(MPTTester const& mpt) + { + return ~static_cast(mpt); + } + private: using SLEP = SLE::const_pointer; bool diff --git a/src/test/jtx/owners.h b/src/test/jtx/owners.h index 3f54e0c55f..b24f0a686f 100644 --- a/src/test/jtx/owners.h +++ b/src/test/jtx/owners.h @@ -43,7 +43,7 @@ public: void operator()(Env& env) const { - detail::owned_count_helper(env, account_.id(), Type, value_); + xrpl::detail::owned_count_helper(env, account_.id(), Type, value_); } }; @@ -69,6 +69,9 @@ using lines = owner_count; /** Match the number of offers in the account's owner directory */ using offers = owner_count; +/** Match the number of MPToken in the account's owner directory */ +using mptokens = owner_count; + } // namespace jtx } // namespace test } // namespace xrpl diff --git a/src/test/jtx/paths.h b/src/test/jtx/paths.h index 6522364e14..8558b6232b 100644 --- a/src/test/jtx/paths.h +++ b/src/test/jtx/paths.h @@ -7,6 +7,7 @@ #include namespace xrpl { +class STPath; namespace test { namespace jtx { @@ -14,12 +15,12 @@ namespace jtx { class paths { private: - Issue in_; + Asset in_; int depth_; unsigned int limit_; public: - paths(Issue const& in, int depth = 7, unsigned int limit = 4) + paths(Asset const& in, int depth = 7, unsigned int limit = 4) : in_(in), depth_(depth), limit_(limit) { } @@ -45,6 +46,8 @@ public: template explicit path(T const& t, Args const&... args); + path(STPath const& p); + void operator()(Env&, JTx& jt) const; diff --git a/src/test/ledger/BookDirs_test.cpp b/src/test/ledger/BookDirs_test.cpp index e8733d159d..951a53185b 100644 --- a/src/test/ledger/BookDirs_test.cpp +++ b/src/test/ledger/BookDirs_test.cpp @@ -19,7 +19,7 @@ struct BookDirs_test : public beast::unit_test::suite env.close(); { - Book const book(xrpIssue(), USD.issue(), std::nullopt); + Book const book(xrpIssue(), USD, std::nullopt); { auto d = BookDirs(*env.current(), book); BEAST_EXPECT(std::begin(d) == std::end(d)); @@ -33,14 +33,14 @@ struct BookDirs_test : public beast::unit_test::suite { env(offer("alice", Account("alice")["USD"](50), XRP(10))); - auto d = BookDirs( - *env.current(), Book(Account("alice")["USD"].issue(), xrpIssue(), std::nullopt)); + auto d = + BookDirs(*env.current(), Book(Account("alice")["USD"], xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } { env(offer("alice", gw["CNY"](50), XRP(10))); - auto d = BookDirs(*env.current(), Book(gw["CNY"].issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(gw["CNY"], xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } @@ -48,8 +48,7 @@ struct BookDirs_test : public beast::unit_test::suite env.trust(Account("bob")["CNY"](10), "alice"); env(pay("bob", "alice", Account("bob")["CNY"](10))); env(offer("alice", USD(50), Account("bob")["CNY"](10))); - auto d = BookDirs( - *env.current(), Book(USD.issue(), Account("bob")["CNY"].issue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(USD, Account("bob")["CNY"], std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 1); } @@ -61,7 +60,7 @@ struct BookDirs_test : public beast::unit_test::suite env(offer("alice", AUD(i), XRP(j))); } - auto d = BookDirs(*env.current(), Book(AUD.issue(), xrpIssue(), std::nullopt)); + auto d = BookDirs(*env.current(), Book(AUD, xrpIssue(), std::nullopt)); BEAST_EXPECT(std::distance(d.begin(), d.end()) == 240); auto i = 1, j = 3, k = 0; for (auto const& e : d) diff --git a/src/test/ledger/Directory_test.cpp b/src/test/ledger/Directory_test.cpp index 4115d03c19..518ec2511c 100644 --- a/src/test/ledger/Directory_test.cpp +++ b/src/test/ledger/Directory_test.cpp @@ -123,7 +123,7 @@ struct Directory_test : public beast::unit_test::suite // Now check the orderbook: it should be in the order we placed // the offers. - auto book = BookDirs(*env.current(), Book({xrpIssue(), USD.issue(), std::nullopt})); + auto book = BookDirs(*env.current(), Book({xrpIssue(), USD, std::nullopt})); int count = 1; for (auto const& offer : book) @@ -283,7 +283,7 @@ struct Directory_test : public beast::unit_test::suite // should have no entries and be empty: { Sandbox const sb(env.closed().get(), tapNONE); - uint256 const bookBase = getBookBase({xrpIssue(), USD.issue(), std::nullopt}); + uint256 const bookBase = getBookBase({xrpIssue(), USD, std::nullopt}); BEAST_EXPECT(dirIsEmpty(sb, keylet::page(bookBase))); BEAST_EXPECT(!sb.succ(bookBase, getQualityNext(bookBase))); @@ -475,7 +475,7 @@ struct Directory_test : public beast::unit_test::suite testDirectoryFull() { using namespace test::jtx; - Account alice("alice"); + Account const alice("alice"); auto const testCase = [&, this](FeatureBitset features, auto setup) { using namespace test::jtx; diff --git a/src/test/ledger/PaymentSandbox_test.cpp b/src/test/ledger/PaymentSandbox_test.cpp index 69e2657d0c..f1d648153c 100644 --- a/src/test/ledger/PaymentSandbox_test.cpp +++ b/src/test/ledger/PaymentSandbox_test.cpp @@ -105,7 +105,7 @@ class PaymentSandbox_test : public beast::unit_test::suite // accountSend, no deferredCredits ApplyViewImpl av(&*env.current(), tapNONE); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); { @@ -128,7 +128,7 @@ class PaymentSandbox_test : public beast::unit_test::suite // directSendNoFee, no deferredCredits ApplyViewImpl av(&*env.current(), tapNONE); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(av, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -148,7 +148,7 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -174,7 +174,7 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -189,7 +189,7 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -204,7 +204,7 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -219,7 +219,7 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - auto const iss = USD_gw1.issue(); + auto const iss = USD_gw1; auto const startingAmount = accountHolds(pv, alice, iss.currency, iss.account, fhIGNORE_FREEZE, j); @@ -272,7 +272,7 @@ class PaymentSandbox_test : public beast::unit_test::suite Account const alice("alice"); auto const USD = gw["USD"]; - auto const issue = USD.issue(); + auto const issue = USD; STAmount const tinyAmt( issue, STAmount::cMinValue, STAmount::cMinOffset + 1, false, STAmount::unchecked{}); STAmount const hugeAmt( @@ -280,8 +280,8 @@ class PaymentSandbox_test : public beast::unit_test::suite ApplyViewImpl av(&*env.current(), tapNONE); PaymentSandbox pv(&av); - pv.creditHook(gw, alice, hugeAmt, -tinyAmt); - BEAST_EXPECT(pv.balanceHook(alice, gw, hugeAmt) == tinyAmt); + pv.creditHookIOU(gw, alice, hugeAmt, -tinyAmt); + BEAST_EXPECT(pv.balanceHookIOU(alice, gw, hugeAmt) == tinyAmt); } void @@ -328,8 +328,8 @@ class PaymentSandbox_test : public beast::unit_test::suite void testBalanceHook(FeatureBitset features) { - // Make sure the Issue::Account returned by PAymentSandbox::balanceHook - // is correct. + // Make sure the Issue::Account returned by + // PaymentSandbox::balanceHookIOU is correct. testcase("balanceHook"); using namespace jtx; @@ -343,16 +343,18 @@ class PaymentSandbox_test : public beast::unit_test::suite PaymentSandbox sb(&av); // The currency we pass for the last argument mimics the currency that - // is typically passed to creditHook, since it comes from a trust line. + // is typically passed to creditHookIOU, since it comes from a trust + // line. Issue tlIssue = noIssue(); - tlIssue.currency = USD.issue().currency; + tlIssue.currency = USD.currency; - sb.creditHook(gw.id(), alice.id(), {USD, 400}, {tlIssue, 600}); - sb.creditHook(gw.id(), alice.id(), {USD, 100}, {tlIssue, 600}); + sb.creditHookIOU(gw.id(), alice.id(), {USD, 400}, {tlIssue, 600}); + sb.creditHookIOU(gw.id(), alice.id(), {USD, 100}, {tlIssue, 600}); - // Expect that the STAmount issuer returned by balanceHook() is correct. - STAmount const balance = sb.balanceHook(gw.id(), alice.id(), {USD, 600}); - BEAST_EXPECT(balance.getIssuer() == USD.issue().account); + // Expect that the STAmount issuer returned by balanceHookIOU() is + // correct. + STAmount const balance = sb.balanceHookIOU(gw.id(), alice.id(), {USD, 600}); + BEAST_EXPECT(balance.getIssuer() == USD.account.id()); } public: diff --git a/src/test/protocol/Memo_test.cpp b/src/test/protocol/Memo_test.cpp index 9a0fd7d94c..a39fdfd194 100644 --- a/src/test/protocol/Memo_test.cpp +++ b/src/test/protocol/Memo_test.cpp @@ -13,7 +13,7 @@ public: testcase("Test memos"); using namespace test::jtx; - Account alice{"alice"}; + Account const alice{"alice"}; Env env(*this); env.fund(XRP(10000), alice); diff --git a/src/test/protocol/STAmount_test.cpp b/src/test/protocol/STAmount_test.cpp index 2c2e005146..92f30bbaa1 100644 --- a/src/test/protocol/STAmount_test.cpp +++ b/src/test/protocol/STAmount_test.cpp @@ -35,10 +35,10 @@ public: mantissa--; if (mantissa < STAmount::cMinValue) - return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; + return {amount.asset(), mantissa, amount.exponent(), amount.negative()}; return { - amount.issue(), + amount.asset(), mantissa, amount.exponent(), amount.negative(), @@ -50,10 +50,10 @@ public: mantissa++; if (mantissa > STAmount::cMaxValue) - return {amount.issue(), mantissa, amount.exponent(), amount.negative()}; + return {amount.asset(), mantissa, amount.exponent(), amount.negative()}; return { - amount.issue(), + amount.asset(), mantissa, amount.exponent(), amount.negative(), @@ -79,7 +79,7 @@ public: BEAST_EXPECT(!cmp.native()); - BEAST_EXPECT(cmp.issue().currency == res.issue().currency); + BEAST_EXPECT(cmp.get().currency == res.get().currency); if (res != cmp) { diff --git a/src/test/protocol/STNumber_test.cpp b/src/test/protocol/STNumber_test.cpp index 3b794b23b5..d4e82eeef2 100644 --- a/src/test/protocol/STNumber_test.cpp +++ b/src/test/protocol/STNumber_test.cpp @@ -58,7 +58,7 @@ struct STNumber_test : public beast::unit_test::suite STNumber const factor{sfNumber, 100}; auto const iouValue = strikePrice.iou(); IOUAmount const totalValue{iouValue * factor}; - STAmount const totalAmount{totalValue, strikePrice.issue()}; + STAmount const totalAmount{totalValue, strikePrice.get()}; BEAST_EXPECT(totalAmount == Number{10'000}); } diff --git a/src/test/rpc/AMMInfo_test.cpp b/src/test/rpc/AMMInfo_test.cpp index 3f20e0378d..ccad7032e4 100644 --- a/src/test/rpc/AMMInfo_test.cpp +++ b/src/test/rpc/AMMInfo_test.cpp @@ -38,7 +38,7 @@ public: testAMM([&](AMM& ammAlice, Env&) { Account const gw("gw"); auto const USD = gw["USD"]; - auto const jv = ammAlice.ammRpcInfo({}, {}, USD.issue(), USD.issue()); + auto const jv = ammAlice.ammRpcInfo({}, {}, USD, USD); BEAST_EXPECT(jv[jss::error_message] == "Account not found."); }); @@ -51,10 +51,10 @@ public: std::vector, std::optional, TestAccount, bool>> const invalidParams = { {xrpIssue(), std::nullopt, None, false}, - {std::nullopt, USD.issue(), None, false}, + {std::nullopt, USD, None, false}, {xrpIssue(), std::nullopt, Alice, false}, - {std::nullopt, USD.issue(), Alice, false}, - {xrpIssue(), USD.issue(), Alice, false}, + {std::nullopt, USD, Alice, false}, + {xrpIssue(), USD, Alice, false}, {std::nullopt, std::nullopt, None, true}}; // Invalid parameters @@ -113,10 +113,10 @@ public: std::vector, std::optional, TestAccount, bool>> const invalidParamsBadAccount = { {xrpIssue(), std::nullopt, None, false}, - {std::nullopt, USD.issue(), None, false}, + {std::nullopt, USD, None, false}, {xrpIssue(), std::nullopt, Bogie, false}, - {std::nullopt, USD.issue(), Bogie, false}, - {xrpIssue(), USD.issue(), Bogie, false}, + {std::nullopt, USD, Bogie, false}, + {xrpIssue(), USD, Bogie, false}, {std::nullopt, std::nullopt, None, true}}; // Invalid parameters *and* invalid AMM account, default API version @@ -161,7 +161,6 @@ public: using namespace jtx; testAMM([&](AMM& ammAlice, Env&) { - BEAST_EXPECT(ammAlice.expectAmmRpcInfo(XRP(10000), USD(10000), IOUAmount{10000000, 0})); BEAST_EXPECT(ammAlice.expectAmmRpcInfo( XRP(10000), USD(10000), @@ -170,6 +169,32 @@ public: std::nullopt, ammAlice.ammAccount())); }); + + { + Env env{*this}; + env.fund(XRP(1'000), gw); + MPTTester mpt(env, gw, {.fund = false}); + mpt.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + MPTTester mpt1(env, gw, {.fund = false}); + mpt1.create({.flags = tfMPTCanTransfer | tfMPTCanTrade}); + auto const MPT = mpt["MPT"]; + auto const MPT1 = mpt1["MPT"]; + std::vector> pools = { + {XRP(100), MPT(100), IOUAmount{100'000}}, + {USD(100), MPT(100), IOUAmount{100}}, + {MPT(100), MPT1(100), IOUAmount{100}}}; + for (auto& pool : pools) + { + AMM const amm(env, gw, std::get<0>(pool), std::get<1>(pool)); + BEAST_EXPECT(amm.expectAmmRpcInfo( + std::get<0>(pool), + std::get<1>(pool), + std::get<2>(pool), + std::nullopt, + std::nullopt, + amm.ammAccount())); + } + } } void diff --git a/src/test/rpc/Book_test.cpp b/src/test/rpc/Book_test.cpp index 5e149ebc0e..ed5ecce388 100644 --- a/src/test/rpc/Book_test.cpp +++ b/src/test/rpc/Book_test.cpp @@ -940,7 +940,7 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 1); auto const jrOffer = jrr[jss::offers][0u]; BEAST_EXPECT(jrOffer[sfAccount.fieldName] == alice.human()); - BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue())); + BEAST_EXPECT(jrOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD)); BEAST_EXPECT(jrOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrOffer[jss::Flags] == 0); BEAST_EXPECT(jrOffer[sfLedgerEntryType.fieldName] == jss::Offer); @@ -984,7 +984,7 @@ public: BEAST_EXPECT(jrr[jss::offers].size() == 2); auto const jrNextOffer = jrr[jss::offers][1u]; BEAST_EXPECT(jrNextOffer[sfAccount.fieldName] == bob.human()); - BEAST_EXPECT(jrNextOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD.issue())); + BEAST_EXPECT(jrNextOffer[sfBookDirectory.fieldName] == getBookDir(env, XRP, USD)); BEAST_EXPECT(jrNextOffer[sfBookNode.fieldName] == "0"); BEAST_EXPECT(jrNextOffer[jss::Flags] == 0); BEAST_EXPECT(jrNextOffer[sfLedgerEntryType.fieldName] == jss::Offer); diff --git a/src/test/rpc/DeliveredAmount_test.cpp b/src/test/rpc/DeliveredAmount_test.cpp index 358657a6c3..167027006a 100644 --- a/src/test/rpc/DeliveredAmount_test.cpp +++ b/src/test/rpc/DeliveredAmount_test.cpp @@ -396,7 +396,7 @@ public: testTxDeliveredAmountRPC(); testAccountDeliveredAmountSubscribe(); - testMPTDeliveredAmountRPC(all - fixMPTDeliveredAmount); + testMPTDeliveredAmountRPC(all - fixMPTDeliveredAmount - featureMPTokensV2); testMPTDeliveredAmountRPC(all); } }; diff --git a/src/test/rpc/Feature_test.cpp b/src/test/rpc/Feature_test.cpp index 657eda2c1c..db9b25cfd4 100644 --- a/src/test/rpc/Feature_test.cpp +++ b/src/test/rpc/Feature_test.cpp @@ -505,7 +505,7 @@ class Feature_test : public beast::unit_test::suite using namespace test::jtx; Env env{*this}; - auto const& supportedAmendments = detail::supportedAmendments(); + auto const& supportedAmendments = xrpl::detail::supportedAmendments(); auto obsoleteFeature = std::find_if( std::begin(supportedAmendments), std::end(supportedAmendments), [](auto const& pair) { return pair.second == VoteBehavior::Obsolete; diff --git a/src/test/rpc/GatewayBalances_test.cpp b/src/test/rpc/GatewayBalances_test.cpp index b6efea17fc..35514ec093 100644 --- a/src/test/rpc/GatewayBalances_test.cpp +++ b/src/test/rpc/GatewayBalances_test.cpp @@ -181,7 +181,7 @@ public: auto USD = alice["USD"]; // The largest valid STAmount of USD: - STAmount const maxUSD(USD.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); + STAmount const maxUSD(USD, STAmount::cMaxValue, STAmount::cMaxOffset); // Create a hotwallet Account const hw{"hw"}; diff --git a/src/test/rpc/LedgerEntry_test.cpp b/src/test/rpc/LedgerEntry_test.cpp index bd053d71c9..7688c09fa7 100644 --- a/src/test/rpc/LedgerEntry_test.cpp +++ b/src/test/rpc/LedgerEntry_test.cpp @@ -26,7 +26,7 @@ enum class FieldType { HashField, HashOrObjectField, FixedHashField, - IssueField, + AssetField, ObjectField, StringField, TwoAccountArrayField, @@ -37,8 +37,8 @@ enum class FieldType { std::vector> mappings{ {jss::account, FieldType::AccountField}, {jss::accounts, FieldType::TwoAccountArrayField}, - {jss::asset, FieldType::IssueField}, - {jss::asset2, FieldType::IssueField}, + {jss::asset, FieldType::AssetField}, + {jss::asset2, FieldType::AssetField}, {jss::authorize, FieldType::AccountField}, {jss::authorized, FieldType::AccountField}, {jss::credential_type, FieldType::BlobField}, @@ -82,8 +82,8 @@ getTypeName(FieldType typeID) return "hex string"; case FieldType::HashOrObjectField: return "hex string or object"; - case FieldType::IssueField: - return "Issue"; + case FieldType::AssetField: + return "Asset"; case FieldType::TwoAccountArrayField: return "length-2 array of Accounts"; case FieldType::UInt32Field: @@ -194,7 +194,7 @@ class LedgerEntry_test : public beast::unit_test::suite static auto const& badIndexValues = remove({12, 16, 18, 19}); static auto const& badUInt32Values = remove({2, 3}); static auto const& badUInt64Values = remove({2, 3}); - static auto const& badIssueValues = remove({}); + static auto const& badAssetValues = remove({}); switch (fieldType) { @@ -213,8 +213,8 @@ class LedgerEntry_test : public beast::unit_test::suite return badIndexValues; case FieldType::FixedHashField: return badFixedHashValues; - case FieldType::IssueField: - return badIssueValues; + case FieldType::AssetField: + return badAssetValues; case FieldType::UInt32Field: return badUInt32Values; case FieldType::UInt64Field: @@ -254,7 +254,7 @@ class LedgerEntry_test : public beast::unit_test::suite case FieldType::HashField: return "5233D68B4D44388F98559DE42903767803EFA7C1F8D01413FC16EE6" "B01403D6D"; - case FieldType::IssueField: + case FieldType::AssetField: return issueObject; case FieldType::HashOrObjectField: return "5233D68B4D44388F98559DE42903767803EFA7C1F8D01413FC16EE6" @@ -693,59 +693,67 @@ class LedgerEntry_test : public beast::unit_test::suite { testcase("AMM"); using namespace test::jtx; - Env env{*this}; - - // positive test Account const alice{"alice"}; - env.fund(XRP(10000), alice); - env.close(); - AMM const amm(env, alice, XRP(10), alice["USD"](1000)); - env.close(); - { - Json::Value jvParams; - jvParams[jss::amm] = to_string(amm.ammID()); - auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && - !result[jss::result].isMember(jss::error) && - result[jss::result].isMember(jss::node) && - result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && - result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); - } + auto test = [&](auto&& getAsset) { + Env env{*this}; + + // positive test + env.fund(XRP(10000), alice); + env.close(); + PrettyAsset const USD = getAsset(env); + AMM const amm(env, alice, XRP(10), USD(1000)); + env.close(); - { - Json::Value jvParams; - Json::Value ammParams(Json::objectValue); { - Json::Value obj(Json::objectValue); - obj[jss::currency] = "XRP"; - ammParams[jss::asset] = obj; + Json::Value jvParams; + jvParams[jss::amm] = to_string(amm.ammID()); + auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); + BEAST_EXPECT( + result.isObject() && result.isMember(jss::result) && + !result[jss::result].isMember(jss::error) && + result[jss::result].isMember(jss::node) && + result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); } - { - Json::Value obj(Json::objectValue); - obj[jss::currency] = "USD"; - obj[jss::issuer] = alice.human(); - ammParams[jss::asset2] = obj; - } - jvParams[jss::amm] = ammParams; - auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); - BEAST_EXPECT( - result.isObject() && result.isMember(jss::result) && - !result[jss::result].isMember(jss::error) && - result[jss::result].isMember(jss::node) && - result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && - result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); - } - // negative tests - runLedgerEntryTest( - env, - jss::amm, { - {jss::asset, "malformedRequest"}, - {jss::asset2, "malformedRequest"}, - }); + Json::Value jvParams; + Json::Value ammParams(Json::objectValue); + { + Json::Value obj(Json::objectValue); + obj[jss::currency] = "XRP"; + ammParams[jss::asset] = obj; + } + { + Json::Value const obj(Json::objectValue); + ammParams[jss::asset2] = to_json(USD.raw()); + } + jvParams[jss::amm] = ammParams; + auto const result = env.rpc("json", "ledger_entry", to_string(jvParams)); + BEAST_EXPECT( + result.isObject() && result.isMember(jss::result) && + !result[jss::result].isMember(jss::error) && + result[jss::result].isMember(jss::node) && + result[jss::result][jss::node].isMember(sfLedgerEntryType.jsonName) && + result[jss::result][jss::node][sfLedgerEntryType.jsonName] == jss::AMM); + } + + // negative tests + runLedgerEntryTest( + env, + jss::amm, + { + {jss::asset, "malformedRequest"}, + {jss::asset2, "malformedRequest"}, + }); + }; + auto getIOU = [&](Env& env) -> PrettyAsset { return alice["USD"]; }; + auto getMPT = [&](Env& env) -> PrettyAsset { + return MPTTester({.env = env, .issuer = alice}); + }; + test(getIOU); + test(getMPT); } void diff --git a/src/test/rpc/Subscribe_test.cpp b/src/test/rpc/Subscribe_test.cpp index bf52bde7aa..080c9232de 100644 --- a/src/test/rpc/Subscribe_test.cpp +++ b/src/test/rpc/Subscribe_test.cpp @@ -783,9 +783,9 @@ public: using namespace jtx; using IdxHashVec = std::vector>; - Account alice("alice"); + Account const alice("alice"); Account const bob("bob"); - Account carol("carol"); + Account const carol("carol"); Account const david("david"); /////////////////////////////////////////////////////////////////// diff --git a/src/tests/libxrpl/protocol_autogen/ledger_entries/DirectoryNodeTests.cpp b/src/tests/libxrpl/protocol_autogen/ledger_entries/DirectoryNodeTests.cpp index d1b6edc704..af617c2634 100644 --- a/src/tests/libxrpl/protocol_autogen/ledger_entries/DirectoryNodeTests.cpp +++ b/src/tests/libxrpl/protocol_autogen/ledger_entries/DirectoryNodeTests.cpp @@ -23,8 +23,10 @@ TEST(DirectoryNodeTests, BuilderSettersRoundTrip) auto const ownerValue = canonical_ACCOUNT(); auto const takerPaysCurrencyValue = canonical_UINT160(); auto const takerPaysIssuerValue = canonical_UINT160(); + auto const takerPaysMPTValue = canonical_UINT192(); auto const takerGetsCurrencyValue = canonical_UINT160(); auto const takerGetsIssuerValue = canonical_UINT160(); + auto const takerGetsMPTValue = canonical_UINT192(); auto const exchangeRateValue = canonical_UINT64(); auto const indexesValue = canonical_VECTOR256(); auto const rootIndexValue = canonical_UINT256(); @@ -43,8 +45,10 @@ TEST(DirectoryNodeTests, BuilderSettersRoundTrip) builder.setOwner(ownerValue); builder.setTakerPaysCurrency(takerPaysCurrencyValue); builder.setTakerPaysIssuer(takerPaysIssuerValue); + builder.setTakerPaysMPT(takerPaysMPTValue); builder.setTakerGetsCurrency(takerGetsCurrencyValue); builder.setTakerGetsIssuer(takerGetsIssuerValue); + builder.setTakerGetsMPT(takerGetsMPTValue); builder.setExchangeRate(exchangeRateValue); builder.setIndexNext(indexNextValue); builder.setIndexPrevious(indexPreviousValue); @@ -98,6 +102,14 @@ TEST(DirectoryNodeTests, BuilderSettersRoundTrip) EXPECT_TRUE(entry.hasTakerPaysIssuer()); } + { + auto const& expected = takerPaysMPTValue; + auto const actualOpt = entry.getTakerPaysMPT(); + ASSERT_TRUE(actualOpt.has_value()); + expectEqualField(expected, *actualOpt, "sfTakerPaysMPT"); + EXPECT_TRUE(entry.hasTakerPaysMPT()); + } + { auto const& expected = takerGetsCurrencyValue; auto const actualOpt = entry.getTakerGetsCurrency(); @@ -114,6 +126,14 @@ TEST(DirectoryNodeTests, BuilderSettersRoundTrip) EXPECT_TRUE(entry.hasTakerGetsIssuer()); } + { + auto const& expected = takerGetsMPTValue; + auto const actualOpt = entry.getTakerGetsMPT(); + ASSERT_TRUE(actualOpt.has_value()); + expectEqualField(expected, *actualOpt, "sfTakerGetsMPT"); + EXPECT_TRUE(entry.hasTakerGetsMPT()); + } + { auto const& expected = exchangeRateValue; auto const actualOpt = entry.getExchangeRate(); @@ -186,8 +206,10 @@ TEST(DirectoryNodeTests, BuilderFromSleRoundTrip) auto const ownerValue = canonical_ACCOUNT(); auto const takerPaysCurrencyValue = canonical_UINT160(); auto const takerPaysIssuerValue = canonical_UINT160(); + auto const takerPaysMPTValue = canonical_UINT192(); auto const takerGetsCurrencyValue = canonical_UINT160(); auto const takerGetsIssuerValue = canonical_UINT160(); + auto const takerGetsMPTValue = canonical_UINT192(); auto const exchangeRateValue = canonical_UINT64(); auto const indexesValue = canonical_VECTOR256(); auto const rootIndexValue = canonical_UINT256(); @@ -203,8 +225,10 @@ TEST(DirectoryNodeTests, BuilderFromSleRoundTrip) sle->at(sfOwner) = ownerValue; sle->at(sfTakerPaysCurrency) = takerPaysCurrencyValue; sle->at(sfTakerPaysIssuer) = takerPaysIssuerValue; + sle->at(sfTakerPaysMPT) = takerPaysMPTValue; sle->at(sfTakerGetsCurrency) = takerGetsCurrencyValue; sle->at(sfTakerGetsIssuer) = takerGetsIssuerValue; + sle->at(sfTakerGetsMPT) = takerGetsMPTValue; sle->at(sfExchangeRate) = exchangeRateValue; sle->at(sfIndexes) = indexesValue; sle->at(sfRootIndex) = rootIndexValue; @@ -283,6 +307,19 @@ TEST(DirectoryNodeTests, BuilderFromSleRoundTrip) expectEqualField(expected, *fromBuilderOpt, "sfTakerPaysIssuer"); } + { + auto const& expected = takerPaysMPTValue; + + auto const fromSleOpt = entryFromSle.getTakerPaysMPT(); + auto const fromBuilderOpt = entryFromBuilder.getTakerPaysMPT(); + + ASSERT_TRUE(fromSleOpt.has_value()); + ASSERT_TRUE(fromBuilderOpt.has_value()); + + expectEqualField(expected, *fromSleOpt, "sfTakerPaysMPT"); + expectEqualField(expected, *fromBuilderOpt, "sfTakerPaysMPT"); + } + { auto const& expected = takerGetsCurrencyValue; @@ -309,6 +346,19 @@ TEST(DirectoryNodeTests, BuilderFromSleRoundTrip) expectEqualField(expected, *fromBuilderOpt, "sfTakerGetsIssuer"); } + { + auto const& expected = takerGetsMPTValue; + + auto const fromSleOpt = entryFromSle.getTakerGetsMPT(); + auto const fromBuilderOpt = entryFromBuilder.getTakerGetsMPT(); + + ASSERT_TRUE(fromSleOpt.has_value()); + ASSERT_TRUE(fromBuilderOpt.has_value()); + + expectEqualField(expected, *fromSleOpt, "sfTakerGetsMPT"); + expectEqualField(expected, *fromBuilderOpt, "sfTakerGetsMPT"); + } + { auto const& expected = exchangeRateValue; @@ -462,10 +512,14 @@ TEST(DirectoryNodeTests, OptionalFieldsReturnNullopt) EXPECT_FALSE(entry.getTakerPaysCurrency().has_value()); EXPECT_FALSE(entry.hasTakerPaysIssuer()); EXPECT_FALSE(entry.getTakerPaysIssuer().has_value()); + EXPECT_FALSE(entry.hasTakerPaysMPT()); + EXPECT_FALSE(entry.getTakerPaysMPT().has_value()); EXPECT_FALSE(entry.hasTakerGetsCurrency()); EXPECT_FALSE(entry.getTakerGetsCurrency().has_value()); EXPECT_FALSE(entry.hasTakerGetsIssuer()); EXPECT_FALSE(entry.getTakerGetsIssuer().has_value()); + EXPECT_FALSE(entry.hasTakerGetsMPT()); + EXPECT_FALSE(entry.getTakerGetsMPT().has_value()); EXPECT_FALSE(entry.hasExchangeRate()); EXPECT_FALSE(entry.getExchangeRate().has_value()); EXPECT_FALSE(entry.hasIndexNext()); diff --git a/src/xrpld/app/ledger/OrderBookDB.h b/src/xrpld/app/ledger/OrderBookDB.h new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.cpp b/src/xrpld/app/ledger/OrderBookDBImpl.cpp index add9c7eea9..67597531ab 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.cpp +++ b/src/xrpld/app/ledger/OrderBookDBImpl.cpp @@ -109,10 +109,34 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) { Book book; - book.in.currency = sle->getFieldH160(sfTakerPaysCurrency); - book.in.account = sle->getFieldH160(sfTakerPaysIssuer); - book.out.currency = sle->getFieldH160(sfTakerGetsCurrency); - book.out.account = sle->getFieldH160(sfTakerGetsIssuer); + if (sle->isFieldPresent(sfTakerPaysCurrency)) + { + Issue issue; + issue.currency = sle->getFieldH160(sfTakerPaysCurrency); + issue.account = sle->getFieldH160(sfTakerPaysIssuer); + book.in = issue; + } + else + { + XRPL_ASSERT( + sle->isFieldPresent(sfTakerPaysMPT), + "OrderBookDB::update, must be TakerPaysMPT"); + book.in = sle->getFieldH192(sfTakerPaysMPT); + } + if (sle->isFieldPresent(sfTakerGetsCurrency)) + { + Issue issue; + issue.currency = sle->getFieldH160(sfTakerGetsCurrency); + issue.account = sle->getFieldH160(sfTakerGetsIssuer); + book.out = issue; + } + else + { + XRPL_ASSERT( + sle->isFieldPresent(sfTakerGetsMPT), + "OrderBookDB::update, must be TakerGetsMPT"); + book.out = sle->getFieldH192(sfTakerGetsMPT); + } book.domain = (*sle)[~sfDomainID]; if (book.domain) @@ -137,9 +161,9 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) } else if (sle->getType() == ltAMM) { - auto const issue1 = (*sle)[sfAsset].get(); - auto const issue2 = (*sle)[sfAsset2].get(); - auto addBook = [&](Issue const& in, Issue const& out) { + auto const asset1 = (*sle)[sfAsset]; + auto const asset2 = (*sle)[sfAsset2]; + auto addBook = [&](Asset const& in, Asset const& out) { allBooks[in].insert(out); if (isXRP(out)) @@ -147,8 +171,8 @@ OrderBookDBImpl::update(std::shared_ptr const& ledger) ++cnt; }; - addBook(issue1, issue2); - addBook(issue2, issue1); + addBook(asset1, asset2); + addBook(asset2, asset1); } } } @@ -200,7 +224,7 @@ OrderBookDBImpl::addOrderBook(Book const& book) // return list of all orderbooks that want this issuerID and currencyID std::vector -OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional const& domain) +OrderBookDBImpl::getBooksByTakerPays(Asset const& asset, std::optional const& domain) { std::vector ret; @@ -214,17 +238,17 @@ OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional ret.reserve(books.size()); for (auto const& gets : books) - ret.emplace_back(issue, gets, domain); + ret.emplace_back(asset, gets, domain); } }; if (!domain) { - getBooks(allBooks_, issue); + getBooks(allBooks_, asset); } else { - getBooks(domainBooks_, std::make_pair(issue, *domain)); + getBooks(domainBooks_, std::make_pair(asset, *domain)); } } @@ -232,18 +256,18 @@ OrderBookDBImpl::getBooksByTakerPays(Issue const& issue, std::optional } int -OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& domain) +OrderBookDBImpl::getBookSize(Asset const& asset, std::optional const& domain) { std::lock_guard const sl(mLock); if (!domain) { - if (auto it = allBooks_.find(issue); it != allBooks_.end()) + if (auto it = allBooks_.find(asset); it != allBooks_.end()) return static_cast(it->second.size()); } else { - if (auto it = domainBooks_.find({issue, *domain}); it != domainBooks_.end()) + if (auto it = domainBooks_.find({asset, *domain}); it != domainBooks_.end()) return static_cast(it->second.size()); } @@ -251,12 +275,12 @@ OrderBookDBImpl::getBookSize(Issue const& issue, std::optional const& d } bool -OrderBookDBImpl::isBookToXRP(Issue const& issue, std::optional const& domain) +OrderBookDBImpl::isBookToXRP(Asset const& asset, std::optional const& domain) { std::lock_guard const sl(mLock); if (domain) - return xrpDomainBooks_.contains({issue, *domain}); - return xrpBooks_.contains(issue); + return xrpDomainBooks_.contains({asset, *domain}); + return xrpBooks_.contains(asset); } BookListeners::pointer @@ -320,8 +344,8 @@ OrderBookDBImpl::processTxn( data->isFieldPresent(sfTakerPays) && data->isFieldPresent(sfTakerGets)) { auto listeners = getBookListeners( - {data->getFieldAmount(sfTakerGets).issue(), - data->getFieldAmount(sfTakerPays).issue(), + {data->getFieldAmount(sfTakerGets).asset(), + data->getFieldAmount(sfTakerPays).asset(), (*data)[~sfDomainID]}); if (listeners) listeners->publish(jvObj, havePublished); diff --git a/src/xrpld/app/ledger/OrderBookDBImpl.h b/src/xrpld/app/ledger/OrderBookDBImpl.h index 4dd413438e..a72669bef2 100644 --- a/src/xrpld/app/ledger/OrderBookDBImpl.h +++ b/src/xrpld/app/ledger/OrderBookDBImpl.h @@ -41,14 +41,14 @@ public: addOrderBook(Book const& book) override; std::vector - getBooksByTakerPays(Issue const& issue, std::optional const& domain = std::nullopt) + getBooksByTakerPays(Asset const& asset, std::optional const& domain = std::nullopt) override; int - getBookSize(Issue const& issue, std::optional const& domain = std::nullopt) override; + getBookSize(Asset const& asset, std::optional const& domain = std::nullopt) override; bool - isBookToXRP(Issue const& issue, std::optional const& domain = std::nullopt) override; + isBookToXRP(Asset const& asset, std::optional const& domain = std::nullopt) override; // OrderBookDBImpl-specific methods void @@ -71,16 +71,16 @@ private: int const pathSearchMax_; bool const standalone_; - // Maps order books by "issue in" to "issue out": - hardened_hash_map> allBooks_; + // Maps order books by "asset in" to "asset out": + hardened_hash_map> allBooks_; - hardened_hash_map, hardened_hash_set> domainBooks_; + hardened_hash_map, hardened_hash_set> domainBooks_; // does an order book to XRP exist - hash_set xrpBooks_; + hash_set xrpBooks_; // does an order book to XRP exist - hash_set> xrpDomainBooks_; + hash_set> xrpDomainBooks_; std::recursive_mutex mLock; diff --git a/src/xrpld/app/misc/NetworkOPs.cpp b/src/xrpld/app/misc/NetworkOPs.cpp index 361eada455..e39230efdb 100644 --- a/src/xrpld/app/misc/NetworkOPs.cpp +++ b/src/xrpld/app/misc/NetworkOPs.cpp @@ -3177,10 +3177,15 @@ NetworkOPsImp::transJson( auto const amount = transaction->getFieldAmount(sfTakerGets); // If the offer create is not self funded then add the owner balance - if (account != amount.issue().account) + if (account != amount.getIssuer()) { auto const ownerFunds = accountFunds( - *ledger, account, amount, fhIGNORE_FREEZE, registry_.get().getJournal("View")); + *ledger, + account, + amount, + fhIGNORE_FREEZE, + ahIGNORE_AUTH, + registry_.get().getJournal("View")); jvObj[jss::transaction][jss::owner_funds] = ownerFunds.getText(); } } @@ -4271,7 +4276,7 @@ NetworkOPsImp::getBookPage( ReadView const& view = *lpLedger; bool const bGlobalFreeze = - isGlobalFrozen(view, book.out.account) || isGlobalFrozen(view, book.in.account); + isGlobalFrozen(view, book.out.getIssuer()) || isGlobalFrozen(view, book.in.getIssuer()); bool bDone = false; bool bDirectAdvance = true; @@ -4281,7 +4286,7 @@ NetworkOPsImp::getBookPage( unsigned int uBookEntry = 0; STAmount saDirRate; - auto const rate = transferRate(view, book.out.account); + auto const rate = transferRate(view, book.out.getIssuer()); auto viewJ = registry_.get().getJournal("View"); while (!bDone && iLimit-- > 0) @@ -4331,7 +4336,7 @@ NetworkOPsImp::getBookPage( STAmount saOwnerFunds; bool firstOwnerOffer(true); - if (book.out.account == uOfferOwnerID) + if (book.out.getIssuer() == uOfferOwnerID) { // If an offer is selling issuer's own IOUs, it is fully // funded. @@ -4360,9 +4365,9 @@ NetworkOPsImp::getBookPage( saOwnerFunds = accountHolds( view, uOfferOwnerID, - book.out.currency, - book.out.account, + book.out, fhZERO_IF_FROZEN, + ahZERO_IF_UNAUTHORIZED, viewJ); if (saOwnerFunds < beast::zero) @@ -4382,9 +4387,9 @@ NetworkOPsImp::getBookPage( if (rate != parityRate // Have a transfer fee. - && uTakerID != book.out.account + && uTakerID != book.out.getIssuer() // Not taking offers of own IOUs. - && book.out.account != uOfferOwnerID) + && book.out.getIssuer() != uOfferOwnerID) // Offer owner not issuing ownfunds { // Need to charge a transfer fee to offer owner. @@ -4405,7 +4410,7 @@ NetworkOPsImp::getBookPage( saTakerGetsFunded.setJson(jvOffer[jss::taker_gets_funded]); std::min( - saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) + saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.asset())) .setJson(jvOffer[jss::taker_pays_funded]); } @@ -4549,7 +4554,7 @@ NetworkOPsImp::getBookPage( // TODO(tom): The result of this expression is not used - what's // going on here? - std::min(saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.issue())) + std::min(saTakerPays, multiply(saTakerGetsFunded, saDirRate, saTakerPays.asset())) .setJson(jvOffer[jss::taker_pays_funded]); } diff --git a/src/xrpld/rpc/BookChanges.h b/src/xrpld/rpc/BookChanges.h index a318c80221..41853ee890 100644 --- a/src/xrpld/rpc/BookChanges.h +++ b/src/xrpld/rpc/BookChanges.h @@ -99,8 +99,8 @@ computeBookChanges(std::shared_ptr const& lpAccepted) STAmount const deltaPays = finalFields.getFieldAmount(sfTakerPays) - previousFields.getFieldAmount(sfTakerPays); - std::string const g{to_string(deltaGets.issue())}; - std::string const p{to_string(deltaPays.issue())}; + std::string const g{to_string(deltaGets.asset())}; + std::string const p{to_string(deltaPays.asset())}; bool const noswap = isXRP(deltaGets) ? true : (isXRP(deltaPays) ? false : (g < p)); @@ -170,6 +170,16 @@ computeBookChanges(std::shared_ptr const& lpAccepted) jvObj[jss::changes] = Json::arrayValue; + auto volToStr = [](STAmount const& vol) { + return vol.asset().visit( + [&](Issue const& issue) { + if (isXRP(issue)) + return to_string(vol.xrp()); + return to_string(vol.iou()); + }, + [&](MPTIssue const&) { return to_string(vol.mpt()); }); + }; + for (auto const& entry : tally) { Json::Value& inner = jvObj[jss::changes].append(Json::objectValue); @@ -177,11 +187,20 @@ computeBookChanges(std::shared_ptr const& lpAccepted) STAmount const volA = std::get<0>(entry.second); STAmount const volB = std::get<1>(entry.second); - inner[jss::currency_a] = (isXRP(volA) ? "XRP_drops" : to_string(volA.issue())); - inner[jss::currency_b] = (isXRP(volB) ? "XRP_drops" : to_string(volB.issue())); + volA.asset().visit( + [&](Issue const&) { + inner[jss::currency_a] = (isXRP(volA) ? "XRP_drops" : to_string(volA.asset())); + }, + [&](MPTIssue const&) { inner[jss::mpt_issuance_id_a] = to_string(volA.asset()); }); - inner[jss::volume_a] = (isXRP(volA) ? to_string(volA.xrp()) : to_string(volA.iou())); - inner[jss::volume_b] = (isXRP(volB) ? to_string(volB.xrp()) : to_string(volB.iou())); + volB.asset().visit( + [&](Issue const&) { + inner[jss::currency_b] = (isXRP(volB) ? "XRP_drops" : to_string(volB.asset())); + }, + [&](MPTIssue const&) { inner[jss::mpt_issuance_id_b] = to_string(volB.asset()); }); + + inner[jss::volume_a] = volToStr(volA); + inner[jss::volume_b] = volToStr(volB); inner[jss::high] = to_string(std::get<2>(entry.second).iou()); inner[jss::low] = to_string(std::get<3>(entry.second).iou()); diff --git a/src/xrpld/rpc/MPTokenIssuanceID.h b/src/xrpld/rpc/MPTokenIssuanceID.h index 34aa0474d6..9e60c44ee0 100644 --- a/src/xrpld/rpc/MPTokenIssuanceID.h +++ b/src/xrpld/rpc/MPTokenIssuanceID.h @@ -25,7 +25,7 @@ canHaveMPTokenIssuanceID( std::shared_ptr const& serializedTx, TxMeta const& transactionMeta); -std::optional +std::optional getIDFromCreatedIssuance(TxMeta const& transactionMeta); void diff --git a/src/xrpld/rpc/detail/AccountAssets.cpp b/src/xrpld/rpc/detail/AccountAssets.cpp new file mode 100644 index 0000000000..fbe3169bf7 --- /dev/null +++ b/src/xrpld/rpc/detail/AccountAssets.cpp @@ -0,0 +1,86 @@ +#include + +namespace xrpl { + +hash_set +accountSourceAssets( + AccountID const& account, + std::shared_ptr const& lrCache, + bool includeXRP) +{ + hash_set assets; + + // YYY Only bother if they are above reserve + if (includeXRP) + assets.insert(xrpCurrency()); + + if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) + { + for (auto const& rspEntry : *lines) + { + auto& saBalance = rspEntry.getBalance(); + + // Filter out non + if (saBalance > beast::zero + // Have IOUs to send. + || (rspEntry.getLimitPeer() + // Peer extends credit. + && ((-saBalance) < rspEntry.getLimitPeer()))) // Credit left. + { + assets.insert(saBalance.get().currency); + } + } + } + + assets.erase(badCurrency()); + + if (auto const mpts = lrCache->getMPTs(account)) + { + for (auto const& rspEntry : *mpts) + { + if (!rspEntry.isZeroBalance() && !rspEntry.isMaxedOut()) + assets.insert(rspEntry.getMptID()); + } + } + + return assets; +} + +hash_set +accountDestAssets( + AccountID const& account, + std::shared_ptr const& lrCache, + bool includeXRP) +{ + hash_set assets; + + if (includeXRP) + assets.insert(xrpCurrency()); + // Even if account doesn't exist + + if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) + { + for (auto const& rspEntry : *lines) + { + auto& saBalance = rspEntry.getBalance(); + + if (saBalance < rspEntry.getLimit()) // Can take more + assets.insert(saBalance.get().currency); + } + } + + assets.erase(badCurrency()); + + if (auto const mpts = lrCache->getMPTs(account)) + { + for (auto const& rspEntry : *mpts) + { + if (rspEntry.isZeroBalance() && !rspEntry.isMaxedOut()) + assets.insert(rspEntry.getMptID()); + } + } + + return assets; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/detail/AccountAssets.h b/src/xrpld/rpc/detail/AccountAssets.h new file mode 100644 index 0000000000..55fce62fa6 --- /dev/null +++ b/src/xrpld/rpc/detail/AccountAssets.h @@ -0,0 +1,21 @@ +#pragma once + +#include + +#include + +namespace xrpl { + +hash_set +accountDestAssets( + AccountID const& account, + std::shared_ptr const& cache, + bool includeXRP); + +hash_set +accountSourceAssets( + AccountID const& account, + std::shared_ptr const& lrLedger, + bool includeXRP); + +} // namespace xrpl diff --git a/src/xrpld/rpc/detail/AccountCurrencies.cpp b/src/xrpld/rpc/detail/AccountCurrencies.cpp deleted file mode 100644 index c839b1475c..0000000000 --- a/src/xrpld/rpc/detail/AccountCurrencies.cpp +++ /dev/null @@ -1,66 +0,0 @@ -#include - -namespace xrpl { - -hash_set -accountSourceCurrencies( - AccountID const& account, - std::shared_ptr const& lrCache, - bool includeXRP) -{ - hash_set currencies; - - // YYY Only bother if they are above reserve - if (includeXRP) - currencies.insert(xrpCurrency()); - - if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) - { - for (auto const& rspEntry : *lines) - { - auto& saBalance = rspEntry.getBalance(); - - // Filter out non - if (saBalance > beast::zero - // Have IOUs to send. - || (rspEntry.getLimitPeer() - // Peer extends credit. - && ((-saBalance) < rspEntry.getLimitPeer()))) // Credit left. - { - currencies.insert(saBalance.getCurrency()); - } - } - } - - currencies.erase(badCurrency()); - return currencies; -} - -hash_set -accountDestCurrencies( - AccountID const& account, - std::shared_ptr const& lrCache, - bool includeXRP) -{ - hash_set currencies; - - if (includeXRP) - currencies.insert(xrpCurrency()); - // Even if account doesn't exist - - if (auto const lines = lrCache->getRippleLines(account, LineDirection::outgoing)) - { - for (auto const& rspEntry : *lines) - { - auto& saBalance = rspEntry.getBalance(); - - if (saBalance < rspEntry.getLimit()) // Can take more - currencies.insert(saBalance.getCurrency()); - } - } - - currencies.erase(badCurrency()); - return currencies; -} - -} // namespace xrpl diff --git a/src/xrpld/rpc/detail/AccountCurrencies.h b/src/xrpld/rpc/detail/AccountCurrencies.h deleted file mode 100644 index 76c531cb9b..0000000000 --- a/src/xrpld/rpc/detail/AccountCurrencies.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once - -#include - -#include - -namespace xrpl { - -hash_set -accountDestCurrencies( - AccountID const& account, - std::shared_ptr const& cache, - bool includeXRP); - -hash_set -accountSourceCurrencies( - AccountID const& account, - std::shared_ptr const& lrLedger, - bool includeXRP); - -} // namespace xrpl diff --git a/src/xrpld/rpc/detail/AssetCache.cpp b/src/xrpld/rpc/detail/AssetCache.cpp new file mode 100644 index 0000000000..0eb9434e91 --- /dev/null +++ b/src/xrpld/rpc/detail/AssetCache.cpp @@ -0,0 +1,147 @@ +#include +#include + +#include +#include + +namespace xrpl { + +AssetCache::AssetCache(std::shared_ptr const& ledger, beast::Journal j) + : ledger_(ledger), journal_(j) +{ + JLOG(journal_.debug()) << "created for ledger " << ledger_->header().seq; +} + +AssetCache::~AssetCache() +{ + JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq << " with " + << lines_.size() << " accounts and " << totalLineCount_ + << " distinct trust lines."; +} + +std::shared_ptr> +AssetCache::getRippleLines(AccountID const& accountID, LineDirection direction) +{ + auto const hash = hasher_(accountID); + AccountKey key(accountID, direction, hash); + AccountKey otherkey( + accountID, + direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, + hash); + + std::lock_guard const sl(mLock); + + auto [it, inserted] = [&]() { + if (auto otheriter = lines_.find(otherkey); otheriter != lines_.end()) + { + // The whole point of using the direction flag is to reduce the + // number of trust line objects held in memory. Ensure that there is + // only a single set of trustlines in the cache per account. + auto const size = otheriter->second ? otheriter->second->size() : 0; + JLOG(journal_.info()) + << "Request for " + << (direction == LineDirection::outgoing ? "outgoing" : "incoming") + << " trust lines for account " << accountID << " found " << size + << (direction == LineDirection::outgoing ? " incoming" : " outgoing") + << " trust lines. " + << (direction == LineDirection::outgoing ? "Deleting the subset of incoming" + : "Returning the superset of outgoing") + << " trust lines. "; + if (direction == LineDirection::outgoing) + { + // This request is for the outgoing set, but there is already a + // subset of incoming lines in the cache. Erase that subset + // to be replaced by the full set. The full set will be built + // below, and will be returned, if needed, on subsequent calls + // for either value of outgoing. + XRPL_ASSERT( + size <= totalLineCount_, "xrpl::AssetCache::getRippleLines : maximum lines"); + totalLineCount_ -= size; + lines_.erase(otheriter); + } + else + { + // This request is for the incoming set, but there is + // already a superset of the outgoing trust lines in the cache. + // The path finding engine will disregard the non-rippling trust + // lines, so to prevent them from being stored twice, return the + // outgoing set. + key = otherkey; + return std::pair{otheriter, false}; + } + } + return lines_.emplace(key, nullptr); + }(); + + if (inserted) + { + XRPL_ASSERT(it->second == nullptr, "xrpl::Asset::getRippleLines : null lines"); + auto lines = PathFindTrustLine::getItems(accountID, *ledger_, direction); + if (!lines.empty()) + { + it->second = std::make_shared>(std::move(lines)); + totalLineCount_ += it->second->size(); + } + } + + XRPL_ASSERT( + !it->second || !it->second->empty(), + "xrpl::AssetCache::getRippleLines : null or nonempty lines"); + auto const size = it->second ? it->second->size() : 0; + JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " + << size + << (key.direction_ == LineDirection::outgoing ? " outgoing" + : " incoming") + << " lines for " << (inserted ? "new " : "existing ") << accountID + << " out of a total of " << lines_.size() << " accounts and " + << totalLineCount_ << " trust lines"; + + return it->second; +} + +std::shared_ptr> const& +AssetCache::getMPTs(xrpl::AccountID const& account) +{ + std::lock_guard const sl(mLock); + + if (auto it = mpts_.find(account); it != mpts_.end()) + return it->second; + + std::vector mpts; + // Get issued/authorized tokens + forEachItem(*ledger_, account, [&](std::shared_ptr const& sle) { + if (sle->getType() == ltMPTOKEN_ISSUANCE) + { + auto const mptID = makeMptID(sle->getFieldU32(sfSequence), account); + bool const maxedOut = sle->at(sfOutstandingAmount) == maxMPTAmount(*sle); + mpts.emplace_back(mptID, false, maxedOut); + } + else if (sle->getType() == ltMPTOKEN) + { + auto const mptID = sle->getFieldH192(sfMPTokenIssuanceID); + bool const zeroBalance = sle->at(sfMPTAmount) == 0; + bool const maxedOut = [&] { + if (auto const sleIssuance = ledger_->read(keylet::mptIssuance(mptID))) + { + return sleIssuance->at(sfOutstandingAmount) == maxMPTAmount(*sleIssuance); + } + return true; + }(); + + mpts.emplace_back(mptID, zeroBalance, maxedOut); + } + }); + + if (mpts.empty()) + { + mpts_.emplace(account, nullptr); + } + else + { + mpts_.emplace(account, std::make_shared>(std::move(mpts))); + } + + return mpts_[account]; +} + +} // namespace xrpl diff --git a/src/xrpld/rpc/detail/AssetCache.h b/src/xrpld/rpc/detail/AssetCache.h new file mode 100644 index 0000000000..0709df2c5f --- /dev/null +++ b/src/xrpld/rpc/detail/AssetCache.h @@ -0,0 +1,106 @@ +#pragma once + +#include +#include + +#include +#include +#include + +#include +#include +#include + +namespace xrpl { + +// Used by Pathfinder +class AssetCache final : public CountedObject +{ +public: + explicit AssetCache(std::shared_ptr const& l, beast::Journal j); + ~AssetCache(); + + std::shared_ptr const& + getLedger() const + { + return ledger_; + } + + /** Find the trust lines associated with an account. + + @param accountID The account + @param direction Whether the account is an "outgoing" link on the path. + "Outgoing" is defined as the source account, or an account found via a + trustline that has rippling enabled on the @accountID's side. If an + account is "outgoing", all trust lines will be returned. If an account is + not "outgoing", then any trust lines that don't have rippling enabled are + not usable, so only return trust lines that have rippling enabled on + @accountID's side. + @return Returns a vector of the usable trust lines. + */ + std::shared_ptr> + getRippleLines(AccountID const& accountID, LineDirection direction); + + std::shared_ptr> const& + getMPTs(AccountID const& account); + +private: + std::mutex mLock; + + xrpl::hardened_hash<> hasher_; + std::shared_ptr ledger_; + + beast::Journal journal_; + + struct AccountKey final : public CountedObject + { + AccountID account_; + LineDirection direction_; + std::size_t hash_value_; + + AccountKey(AccountID const& account, LineDirection direction, std::size_t hash) + : account_(account), direction_(direction), hash_value_(hash) + { + } + + AccountKey(AccountKey const& other) = default; + + AccountKey& + operator=(AccountKey const& other) = default; + + bool + operator==(AccountKey const& lhs) const + { + return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && + direction_ == lhs.direction_; + } + + std::size_t + get_hash() const + { + return hash_value_; + } + + struct Hash + { + Hash() = default; + + std::size_t + operator()(AccountKey const& key) const noexcept + { + return key.get_hash(); + } + }; + }; + + // Use a shared_ptr so entries can be removed from the map safely. + // Even though a shared_ptr to a vector will take more memory just a vector, + // most accounts are not going to have any entries (estimated over 90%), so + // vectors will not need to be created for them. This should lead to far + // less memory usage overall. + hash_map>, AccountKey::Hash> lines_; + std::size_t totalLineCount_ = 0; + hash_map>> mpts_; +}; + +} // namespace xrpl diff --git a/src/xrpld/rpc/detail/MPT.h b/src/xrpld/rpc/detail/MPT.h new file mode 100644 index 0000000000..61dcb8fa7d --- /dev/null +++ b/src/xrpld/rpc/detail/MPT.h @@ -0,0 +1,45 @@ +#pragma once + +#include + +namespace xrpl { + +class PathFindMPT final +{ +private: + MPTID const mptID_; + // If true then holder's balance is 0, always false for issuer + bool const zeroBalance_; + // OutstandingAmount is equal to MaximumAmount + bool const maxedOut_; + +public: + PathFindMPT(MPTID const& mptID) : mptID_(mptID), zeroBalance_(false), maxedOut_(false) + { + } + PathFindMPT(MPTID const& mptID, bool zeroBalance, bool maxedOut) + : mptID_(mptID), zeroBalance_(zeroBalance), maxedOut_(maxedOut) + { + } + operator MPTID const&() const + { + return mptID_; + } + MPTID const& + getMptID() const + { + return mptID_; + } + bool + isZeroBalance() const + { + return zeroBalance_; + } + bool + isMaxedOut() const + { + return maxedOut_; + } +}; + +} // namespace xrpl diff --git a/src/xrpld/rpc/detail/MPTokenIssuanceID.cpp b/src/xrpld/rpc/detail/MPTokenIssuanceID.cpp index ef8bc448ee..48e5579581 100644 --- a/src/xrpld/rpc/detail/MPTokenIssuanceID.cpp +++ b/src/xrpld/rpc/detail/MPTokenIssuanceID.cpp @@ -23,7 +23,7 @@ canHaveMPTokenIssuanceID( return true; } -std::optional +std::optional getIDFromCreatedIssuance(TxMeta const& transactionMeta) { for (STObject const& node : transactionMeta.getNodes()) @@ -48,7 +48,7 @@ insertMPTokenIssuanceID( if (!canHaveMPTokenIssuanceID(transaction, transactionMeta)) return; - std::optional result = getIDFromCreatedIssuance(transactionMeta); + std::optional result = getIDFromCreatedIssuance(transactionMeta); if (result) response[jss::mpt_issuance_id] = to_string(result.value()); } diff --git a/src/xrpld/rpc/detail/PathRequest.cpp b/src/xrpld/rpc/detail/PathRequest.cpp index fe85c519eb..e732ef646f 100644 --- a/src/xrpld/rpc/detail/PathRequest.cpp +++ b/src/xrpld/rpc/detail/PathRequest.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include #include #include #include @@ -146,7 +146,7 @@ PathRequest::updateComplete() } bool -PathRequest::isValid(std::shared_ptr const& crCache) +PathRequest::isValid(std::shared_ptr const& crCache) { if (!raSrcAccount || !raDstAccount) return false; @@ -192,10 +192,11 @@ PathRequest::isValid(std::shared_ptr const& crCache) { bool const disallowXRP((sleDest->getFlags() & lsfDisallowXRP) != 0u); - auto usDestCurrID = accountDestCurrencies(*raDstAccount, crCache, !disallowXRP); + auto const destAssets = accountDestAssets(*raDstAccount, crCache, !disallowXRP); + + for (auto const& asset : destAssets) + jvDestCur.append(to_string(asset)); - for (auto const& currency : usDestCurrID) - jvDestCur.append(to_string(currency)); jvStatus[jss::destination_tag] = (sleDest->getFlags() & lsfRequireDestTag); } @@ -214,7 +215,7 @@ PathRequest::isValid(std::shared_ptr const& crCache) in all cases. */ std::pair -PathRequest::doCreate(std::shared_ptr const& cache, Json::Value const& value) +PathRequest::doCreate(std::shared_ptr const& cache, Json::Value const& value) { bool valid = false; @@ -282,11 +283,9 @@ PathRequest::parseJson(Json::Value const& jvParams) return PFR_PJ_INVALID; } - convert_all_ = saDstAmount == STAmount(saDstAmount.issue(), 1u, 0, true); + convert_all_ = saDstAmount == STAmount(saDstAmount.asset(), 1u, 0, true); - if ((saDstAmount.getCurrency().isZero() && saDstAmount.getIssuer().isNonZero()) || - (saDstAmount.getCurrency() == badCurrency()) || - (!convert_all_ && saDstAmount <= beast::zero)) + if (!validAsset(saDstAmount.asset()) || (!convert_all_ && saDstAmount <= beast::zero)) { jvStatus = rpcError(rpcDST_AMT_MALFORMED); return PFR_PJ_INVALID; @@ -303,9 +302,8 @@ PathRequest::parseJson(Json::Value const& jvParams) saSendMax.emplace(); if (!amountFromJsonNoThrow(*saSendMax, jvParams[jss::send_max]) || - (saSendMax->getCurrency().isZero() && saSendMax->getIssuer().isNonZero()) || - (saSendMax->getCurrency() == badCurrency()) || - (*saSendMax <= beast::zero && *saSendMax != STAmount(saSendMax->issue(), 1u, 0, true))) + !validAsset(saSendMax->asset()) || + (*saSendMax <= beast::zero && *saSendMax != STAmount(saSendMax->asset(), 1u, 0, true))) { jvStatus = rpcError(rpcSENDMAX_MALFORMED); return PFR_PJ_INVALID; @@ -322,45 +320,71 @@ PathRequest::parseJson(Json::Value const& jvParams) return PFR_PJ_INVALID; } - sciSourceCurrencies.clear(); + sciSourceAssets.clear(); for (auto const& c : jvSrcCurrencies) { - // Mandatory currency - Currency srcCurrencyID; - if (!c.isObject() || !c.isMember(jss::currency) || !c[jss::currency].isString() || - !to_currency(srcCurrencyID, c[jss::currency].asString())) + // Mandatory currency or MPT + if (!validJSONAsset(c) || !c.isObject()) { jvStatus = rpcError(rpcSRC_CUR_MALFORMED); return PFR_PJ_INVALID; } + PathAsset srcPathAsset; + if (c.isMember(jss::currency)) + { + Currency currency; + if (!c[jss::currency].isString() || + !to_currency(currency, c[jss::currency].asString())) + { + jvStatus = rpcError(rpcSRC_CUR_MALFORMED); + return PFR_PJ_INVALID; + } + srcPathAsset = currency; + } + else + { + uint192 u; + if (!c[jss::mpt_issuance_id].isString() || + !u.parseHex(c[jss::mpt_issuance_id].asString())) + { + jvStatus = rpcError(rpcSRC_CUR_MALFORMED); + return PFR_PJ_INVALID; + } + srcPathAsset = u; + } + // Optional issuer AccountID srcIssuerID; if (c.isMember(jss::issuer) && - (!c[jss::issuer].isString() || !to_issuer(srcIssuerID, c[jss::issuer].asString()))) + (c.isMember(jss::mpt_issuance_id) || !c[jss::issuer].isString() || + !to_issuer(srcIssuerID, c[jss::issuer].asString()))) { jvStatus = rpcError(rpcSRC_ISR_MALFORMED); return PFR_PJ_INVALID; } - if (srcCurrencyID.isZero()) + if (srcPathAsset.holds()) { - if (srcIssuerID.isNonZero()) + if (srcPathAsset.get().isZero()) { - jvStatus = rpcError(rpcSRC_CUR_MALFORMED); - return PFR_PJ_INVALID; + if (srcIssuerID.isNonZero()) + { + jvStatus = rpcError(rpcSRC_CUR_MALFORMED); + return PFR_PJ_INVALID; + } + } + else if (srcIssuerID.isZero()) + { + srcIssuerID = *raSrcAccount; } - } - else if (srcIssuerID.isZero()) - { - srcIssuerID = *raSrcAccount; } if (saSendMax) { - // If the currencies don't match, ignore the source currency. - if (srcCurrencyID == saSendMax->getCurrency()) + // If the assets don't match, ignore the source asset. + if (srcPathAsset == saSendMax->asset()) { // If neither is the source and they are not equal, then the // source issuer is illegal. @@ -373,23 +397,30 @@ PathRequest::parseJson(Json::Value const& jvParams) // If both are the source, use the source. // Otherwise, use the one that's not the source. - if (srcIssuerID != *raSrcAccount) - { - sciSourceCurrencies.insert({srcCurrencyID, srcIssuerID}); - } - else if (saSendMax->getIssuer() != *raSrcAccount) - { - sciSourceCurrencies.insert({srcCurrencyID, saSendMax->getIssuer()}); - } - else - { - sciSourceCurrencies.insert({srcCurrencyID, *raSrcAccount}); - } + srcPathAsset.visit( + [&](Currency const& currency) { + if (srcIssuerID != *raSrcAccount) + { + sciSourceAssets.insert(Issue{currency, srcIssuerID}); + } + else if (saSendMax->getIssuer() != *raSrcAccount) + { + sciSourceAssets.insert(Issue{currency, saSendMax->getIssuer()}); + } + { + sciSourceAssets.insert(Issue{currency, *raSrcAccount}); + } + }, + [&](MPTID const& mpt) { sciSourceAssets.insert(mpt); }); } } else { - sciSourceCurrencies.insert({srcCurrencyID, srcIssuerID}); + srcPathAsset.visit( + [&](Currency const& currency) { + sciSourceAssets.insert(Issue{currency, srcIssuerID}); + }, + [&](MPTID const& mpt) { sciSourceAssets.insert(MPTIssue{mpt}); }); } } } @@ -437,21 +468,21 @@ PathRequest::doAborting() const std::unique_ptr const& PathRequest::getPathFinder( - std::shared_ptr const& cache, - hash_map>& currency_map, - Currency const& currency, + std::shared_ptr const& cache, + hash_map>& pathasset_map, + PathAsset const& asset, STAmount const& dst_amount, int const level, std::function const& continueCallback) { - auto i = currency_map.find(currency); - if (i != currency_map.end()) + auto i = pathasset_map.find(asset); + if (i != pathasset_map.end()) return i->second; auto pathfinder = std::make_unique( cache, *raSrcAccount, *raDstAccount, - currency, + asset, std::nullopt, dst_amount, saSendMax, @@ -465,47 +496,63 @@ PathRequest::getPathFinder( { pathfinder.reset(); // It's a bad request - clear it. } - return currency_map[currency] = std::move(pathfinder); + return pathasset_map[asset] = std::move(pathfinder); } bool PathRequest::findPaths( - std::shared_ptr const& cache, + std::shared_ptr const& cache, int const level, Json::Value& jvArray, std::function const& continueCallback) { - auto sourceCurrencies = sciSourceCurrencies; - if (sourceCurrencies.empty() && saSendMax) + auto sourceAssets = sciSourceAssets; + if (sourceAssets.empty() && saSendMax) { - sourceCurrencies.insert(saSendMax->issue()); + sourceAssets.insert(saSendMax->asset()); } - if (sourceCurrencies.empty()) + if (sourceAssets.empty()) { - auto currencies = accountSourceCurrencies(*raSrcAccount, cache, true); + auto assets = accountSourceAssets(*raSrcAccount, cache, true); bool const sameAccount = *raSrcAccount == *raDstAccount; - for (auto const& c : currencies) + for (auto const& asset : assets) { - if (!sameAccount || c != saDstAmount.getCurrency()) + if (!std::visit( + [&](TAsset const& a) { + if (!sameAccount || a != saDstAmount.asset()) + { + if (sourceAssets.size() >= RPC::Tuning::max_auto_src_cur) + return false; + if constexpr (std::is_same_v) + { + sourceAssets.insert( + Issue{a, a.isZero() ? xrpAccount() : *raSrcAccount}); + } + else + { + sourceAssets.insert(MPTIssue{a}); + } + } + return true; + }, + asset.value())) { - if (sourceCurrencies.size() >= RPC::Tuning::max_auto_src_cur) - return false; - sourceCurrencies.insert({c, c.isZero() ? xrpAccount() : *raSrcAccount}); + return false; } } } auto const dst_amount = convertAmount(saDstAmount, convert_all_); - hash_map> currency_map; - for (auto const& issue : sourceCurrencies) + hash_map> pathasset_map; + for (auto const& asset : sourceAssets) { if (continueCallback && !continueCallback()) break; JLOG(m_journal.debug()) << iIdentifier - << " Trying to find paths: " << STAmount(issue, 1).getFullText(); + << " Trying to find paths: " << STAmount(asset, 1).getFullText(); auto& pathfinder = - getPathFinder(cache, currency_map, issue.currency, dst_amount, level, continueCallback); + getPathFinder(cache, pathasset_map, asset, dst_amount, level, continueCallback); if (!pathfinder) { JLOG(m_journal.debug()) << iIdentifier << " No paths found"; @@ -514,21 +561,28 @@ PathRequest::findPaths( STPath fullLiquidityPath; auto ps = pathfinder->getBestPaths( - max_paths_, fullLiquidityPath, mContext[issue], issue.account, continueCallback); - mContext[issue] = ps; + max_paths_, fullLiquidityPath, mContext[asset], asset.getIssuer(), continueCallback); + mContext[asset] = ps; auto const& sourceAccount = [&] { - if (!isXRP(issue.account)) - return issue.account; + if (!isXRP(asset.getIssuer())) + return asset.getIssuer(); - if (isXRP(issue.currency)) + if (isXRP(asset)) return xrpAccount(); return *raSrcAccount; }(); - STAmount const saMaxAmount = - saSendMax.value_or(STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true)); + STAmount const saMaxAmount = [&]() { + if (saSendMax) + return *saSendMax; + return asset.visit( + [&](Issue const& issue) { + return STAmount(Issue{issue.currency, sourceAccount}, 1u, 0, true); + }, + [](MPTIssue const& issue) { return STAmount(issue, 1u, 0, true); }); + }(); JLOG(m_journal.debug()) << iIdentifier << " Paths found, calling rippleCalc"; @@ -581,7 +635,8 @@ PathRequest::findPaths( if (rc.result() == tesSUCCESS) { Json::Value jvEntry(Json::objectValue); - rc.actualAmountIn.setIssuer(sourceAccount); + if (rc.actualAmountIn.holds()) + rc.actualAmountIn.get().account = sourceAccount; jvEntry[jss::source_amount] = rc.actualAmountIn.getJson(JsonOptions::none); jvEntry[jss::paths_computed] = ps.getJson(JsonOptions::none); @@ -607,14 +662,14 @@ PathRequest::findPaths( The minimum cost is 50 and the maximum is 400. The cost increases after four source currencies, 50 - (4 * 4) = 34. */ - int const size = sourceCurrencies.size(); + int const size = sourceAssets.size(); consumer_.charge({std::clamp((size * size) + 34, 50, 400), "path update"}); return true; } Json::Value PathRequest::doUpdate( - std::shared_ptr const& cache, + std::shared_ptr const& cache, bool fast, std::function const& continueCallback) { @@ -633,10 +688,10 @@ PathRequest::doUpdate( if (hasCompletion()) { // Old ripple_path_find API gives destination_currencies - auto& destCurrencies = (newStatus[jss::destination_currencies] = Json::arrayValue); - auto usCurrencies = accountDestCurrencies(*raDstAccount, cache, true); - for (auto const& c : usCurrencies) - destCurrencies.append(to_string(c)); + auto& destAssets = (newStatus[jss::destination_currencies] = Json::arrayValue); + auto const assets = accountDestAssets(*raDstAccount, cache, true); + for (auto const& asset : assets) + destAssets.append(to_string(asset)); } newStatus[jss::source_account] = toBase58(*raSrcAccount); diff --git a/src/xrpld/rpc/detail/PathRequest.h b/src/xrpld/rpc/detail/PathRequest.h index db173e307b..f699ccb6f8 100644 --- a/src/xrpld/rpc/detail/PathRequest.h +++ b/src/xrpld/rpc/detail/PathRequest.h @@ -1,11 +1,12 @@ #pragma once +#include #include -#include #include #include #include +#include #include #include @@ -19,7 +20,7 @@ namespace xrpl { // A pathfinding request submitted by a client // The request issuer must maintain a strong pointer -class RippleLineCache; +class AssetCache; class PathRequestManager; // Return values from parseJson <0 = invalid, >0 = valid @@ -68,7 +69,7 @@ public: updateComplete(); std::pair - doCreate(std::shared_ptr const&, Json::Value const&); + doCreate(std::shared_ptr const&, Json::Value const&); Json::Value doClose() override; @@ -80,7 +81,7 @@ public: // update jvStatus Json::Value doUpdate( - std::shared_ptr const&, + std::shared_ptr const&, bool fast, std::function const& continueCallback = {}); InfoSub::pointer @@ -90,13 +91,13 @@ public: private: bool - isValid(std::shared_ptr const& crCache); + isValid(std::shared_ptr const& crCache); std::unique_ptr const& getPathFinder( - std::shared_ptr const&, - hash_map>&, - Currency const&, + std::shared_ptr const&, + hash_map>&, + PathAsset const&, STAmount const&, int const, std::function const&); @@ -106,7 +107,7 @@ private: */ bool findPaths( - std::shared_ptr const&, + std::shared_ptr const&, int const, Json::Value&, std::function const&); @@ -134,8 +135,8 @@ private: STAmount saDstAmount; std::optional saSendMax; - std::set sciSourceCurrencies; - std::map mContext; + std::set sciSourceAssets; + std::map mContext; std::optional domain; diff --git a/src/xrpld/rpc/detail/PathRequestManager.cpp b/src/xrpld/rpc/detail/PathRequestManager.cpp index 4455e304e5..73d57a771c 100644 --- a/src/xrpld/rpc/detail/PathRequestManager.cpp +++ b/src/xrpld/rpc/detail/PathRequestManager.cpp @@ -11,19 +11,19 @@ namespace xrpl { -/** Get the current RippleLineCache, updating it if necessary. +/** Get the current AssetCache, updating it if necessary. Get the correct ledger to use. */ -std::shared_ptr -PathRequestManager::getLineCache(std::shared_ptr const& ledger, bool authoritative) +std::shared_ptr +PathRequestManager::getAssetCache(std::shared_ptr const& ledger, bool authoritative) { std::lock_guard const sl(mLock); - auto lineCache = lineCache_.lock(); + auto assetCache = assetCache_.lock(); - std::uint32_t const lineSeq = lineCache ? lineCache->getLedger()->seq() : 0; + std::uint32_t const lineSeq = assetCache ? assetCache->getLedger()->seq() : 0; std::uint32_t const lgrSeq = ledger->seq(); - JLOG(mJournal.debug()) << "getLineCache has cache for " << lineSeq << ", considering " + JLOG(mJournal.debug()) << "getAssetCache has cache for " << lineSeq << ", considering " << lgrSeq; if ((lineSeq == 0) || // no ledger @@ -31,14 +31,14 @@ PathRequestManager::getLineCache(std::shared_ptr const& ledger, (authoritative && ((lgrSeq + 8) < lineSeq)) || // we jumped way back for some reason (lgrSeq > (lineSeq + 8))) // we jumped way forward for some reason { - JLOG(mJournal.debug()) << "getLineCache creating new cache for " << lgrSeq; + JLOG(mJournal.debug()) << "getAssetCache creating new cache for " << lgrSeq; // Assign to the local before the member, because the member is a // weak_ptr, and will immediately discard it if there are no other // references. - lineCache_ = lineCache = - std::make_shared(ledger, app_.getJournal("RippleLineCache")); + assetCache_ = assetCache = + std::make_shared(ledger, app_.getJournal("AssetCache")); } - return lineCache; + return assetCache; } void @@ -47,13 +47,13 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) auto event = app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "PathRequest::updateAll"); std::vector requests; - std::shared_ptr cache; + std::shared_ptr cache; // Get the ledger and cache we should be using { std::lock_guard const sl(mLock); requests = requests_; - cache = getLineCache(inLedger, true); + cache = getAssetCache(inLedger, true); } bool newRequests = app_.getLedgerMaster().isNewPathRequest(); @@ -172,7 +172,7 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) // Hold on to the line cache until after the lock is released, so it can // be destroyed outside of the lock - std::shared_ptr lastCache; + std::shared_ptr lastCache; { // Get the latest requests, cache, and ledger for next pass std::lock_guard const sl(mLock); @@ -181,7 +181,7 @@ PathRequestManager::updateAll(std::shared_ptr const& inLedger) break; requests = requests_; lastCache = cache; - cache = getLineCache(cache->getLedger(), false); + cache = getAssetCache(cache->getLedger(), false); } } while (!app_.getJobQueue().isStopping()); @@ -222,7 +222,7 @@ PathRequestManager::makePathRequest( { auto req = std::make_shared(app_, subscriber, ++mLastIdentifier, *this, mJournal); - auto [valid, jvRes] = req->doCreate(getLineCache(inLedger, false), requestJson); + auto [valid, jvRes] = req->doCreate(getAssetCache(inLedger, false), requestJson); if (valid) { @@ -247,7 +247,7 @@ PathRequestManager::makeLegacyPathRequest( req = std::make_shared( app_, completion, consumer, ++mLastIdentifier, *this, mJournal); - auto [valid, jvRes] = req->doCreate(getLineCache(inLedger, false), request); + auto [valid, jvRes] = req->doCreate(getAssetCache(inLedger, false), request); if (!valid) { @@ -273,7 +273,7 @@ PathRequestManager::doLegacyPathRequest( std::shared_ptr const& inLedger, Json::Value const& request) { - auto cache = std::make_shared(inLedger, app_.getJournal("RippleLineCache")); + auto cache = std::make_shared(inLedger, app_.getJournal("AssetCache")); auto req = std::make_shared(app_, [] {}, consumer, ++mLastIdentifier, *this, mJournal); diff --git a/src/xrpld/rpc/detail/PathRequestManager.h b/src/xrpld/rpc/detail/PathRequestManager.h index 0f884de5f3..f76a52bc1c 100644 --- a/src/xrpld/rpc/detail/PathRequestManager.h +++ b/src/xrpld/rpc/detail/PathRequestManager.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include @@ -34,8 +35,8 @@ public: bool requestsPending() const; - std::shared_ptr - getLineCache(std::shared_ptr const& ledger, bool authoritative); + std::shared_ptr + getAssetCache(std::shared_ptr const& ledger, bool authoritative); // Create a new-style path request that pushes // updates to a subscriber @@ -89,8 +90,8 @@ private: // Track all requests std::vector requests_; - // Use a RippleLineCache - std::weak_ptr lineCache_; + // Use a AssetCache + std::weak_ptr assetCache_; std::atomic mLastIdentifier; diff --git a/src/xrpld/rpc/detail/Pathfinder.cpp b/src/xrpld/rpc/detail/Pathfinder.cpp index 4749caaccb..6bb085042b 100644 --- a/src/xrpld/rpc/detail/Pathfinder.cpp +++ b/src/xrpld/rpc/detail/Pathfinder.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -66,12 +67,16 @@ compareAccountCandidate( AccountCandidate const& first, AccountCandidate const& second) { - if (first.priority < second.priority) - return false; + // Primary sort key: priority descending + if (first.priority != second.priority) + return first.priority > second.priority; - if (first.account > second.account) - return true; + // Secondary sort key: account descending + if (first.account != second.account) + return first.account > second.account; + // Tertiary sort key (tie-breaker): (priority ^ seq) ascending + // Note: The primary and secondary keys are equal here. return (first.priority ^ seq) < (second.priority ^ seq); } @@ -134,15 +139,38 @@ pathTypeToString(Pathfinder::PathType const& type) STAmount smallestUsefulAmount(STAmount const& amount, int maxPaths) { - return divide(amount, STAmount(maxPaths + 2), amount.issue()); + return divide(amount, STAmount(maxPaths + 2), amount.asset()); } + +STAmount +amountFromPathAsset( + PathAsset const& pathAsset, + std::optional const& srcIssuer, + AccountID const& srcAccount) +{ + return pathAsset.visit( + [&](Currency const& currency) { + auto const& account = srcIssuer.value_or(isXRP(currency) ? xrpAccount() : srcAccount); + return STAmount(Issue{currency, account}, 1u, 0, true); + }, + [](MPTID const& mpt) { return STAmount(mpt, 1u, 0, true); }); +} + +Asset +assetFromPathAsset(PathAsset const& pathAsset, AccountID const& account) +{ + return pathAsset.visit( + [&](Currency const& currency) { return Asset{Issue{currency, account}}; }, + [](MPTID const& mpt) { return Asset{mpt}; }); +} + } // namespace Pathfinder::Pathfinder( - std::shared_ptr const& cache, + std::shared_ptr const& cache, AccountID const& uSrcAccount, AccountID const& uDstAccount, - Currency const& uSrcCurrency, + PathAsset const& uSrcPathAsset, std::optional const& uSrcIssuer, STAmount const& saDstAmount, std::optional const& srcAmount, @@ -152,24 +180,18 @@ Pathfinder::Pathfinder( , mDstAccount(uDstAccount) , mEffectiveDst(isXRP(saDstAmount.getIssuer()) ? uDstAccount : saDstAmount.getIssuer()) , mDstAmount(saDstAmount) - , mSrcCurrency(uSrcCurrency) + , mSrcPathAsset(uSrcPathAsset) , mSrcIssuer(uSrcIssuer) - , mSrcAmount(srcAmount.value_or(STAmount( - Issue{ - uSrcCurrency, - uSrcIssuer.value_or(isXRP(uSrcCurrency) ? xrpAccount() : uSrcAccount)}, - 1u, - 0, - true))) + , mSrcAmount(amountFromPathAsset(uSrcPathAsset, uSrcIssuer, uSrcAccount)) , convert_all_(convertAllCheck(mDstAmount)) , mDomain(domain) , mLedger(cache->getLedger()) - , mRLCache(cache) + , mAssetCache(cache) , app_(app) , j_(app.getJournal("Pathfinder")) { XRPL_ASSERT( - !uSrcIssuer || isXRP(uSrcCurrency) == isXRP(uSrcIssuer.value()), + !uSrcIssuer || uSrcPathAsset.isXRP() == isXRP(uSrcIssuer.value()), "xrpl::Pathfinder::Pathfinder : valid inputs"); } @@ -189,7 +211,7 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue } if (mSrcAccount == mDstAccount && mDstAccount == mEffectiveDst && - mSrcCurrency == mDstAmount.getCurrency()) + mSrcPathAsset == mDstAmount.asset()) { // No need to send to same account with same currency. JLOG(j_.debug()) << "Tried to send to same issuer"; @@ -197,24 +219,24 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue return false; } - if (mSrcAccount == mEffectiveDst && mSrcCurrency == mDstAmount.getCurrency()) + if (mSrcAccount == mEffectiveDst && mSrcPathAsset == mDstAmount.asset()) { // Default path might work, but any path would loop return true; } m_loadEvent = app_.getJobQueue().makeLoadEvent(jtPATH_FIND, "FindPath"); - auto currencyIsXRP = isXRP(mSrcCurrency); + auto currencyIsXRP = isXRP(mSrcPathAsset); bool const useIssuerAccount = mSrcIssuer && !currencyIsXRP && !isXRP(*mSrcIssuer); auto& account = useIssuerAccount ? *mSrcIssuer : mSrcAccount; auto issuer = currencyIsXRP ? AccountID() : account; - mSource = STPathElement(account, mSrcCurrency, issuer); + mSource = STPathElement(account, mSrcPathAsset, issuer); auto issuerString = mSrcIssuer ? to_string(*mSrcIssuer) : std::string("none"); JLOG(j_.trace()) << "findPaths>" << " mSrcAccount=" << mSrcAccount << " mDstAccount=" << mDstAccount << " mDstAmount=" << mDstAmount.getFullText() - << " mSrcCurrency=" << mSrcCurrency << " mSrcIssuer=" << issuerString; + << " mSrcPathAsset=" << mSrcPathAsset << " mSrcIssuer=" << issuerString; if (!mLedger) { @@ -222,8 +244,8 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue return false; } - bool const bSrcXrp = isXRP(mSrcCurrency); - bool const bDstXrp = isXRP(mDstAmount.getCurrency()); + bool const bSrcXrp = isXRP(mSrcPathAsset); + bool const bDstXrp = isXRP(mDstAmount.asset()); if (!mLedger->exists(keylet::account(mSrcAccount))) { @@ -278,7 +300,7 @@ Pathfinder::findPaths(int searchLevel, std::function const& continue JLOG(j_.debug()) << "non-XRP to XRP payment"; paymentType = pt_nonXRP_to_XRP; } - else if (mSrcCurrency == mDstAmount.getCurrency()) + else if (mSrcPathAsset == mDstAmount.asset()) { // non-XRP -> non-XRP - Same currency JLOG(j_.debug()) << "non-XRP to non-XRP - same currency"; @@ -550,7 +572,7 @@ Pathfinder::getBestPaths( XRPL_ASSERT( fullLiquidityPath.empty(), "xrpl::Pathfinder::getBestPaths : first empty path result"); - bool const issuerIsSender = isXRP(mSrcCurrency) || (srcIssuer == mSrcAccount); + bool const issuerIsSender = isXRP(mSrcPathAsset) || (srcIssuer == mSrcAccount); std::vector extraPathRanks; rankPaths(maxPaths, extraPaths, extraPathRanks, continueCallback); @@ -672,27 +694,27 @@ Pathfinder::getBestPaths( } bool -Pathfinder::issueMatchesOrigin(Issue const& issue) +Pathfinder::issueMatchesOrigin(Asset const& asset) { - bool const matchingCurrency = (issue.currency == mSrcCurrency); - bool const matchingAccount = isXRP(issue.currency) || - (mSrcIssuer && issue.account == mSrcIssuer) || issue.account == mSrcAccount; + bool const matchingAsset = (asset == mSrcPathAsset); + bool const matchingAccount = isXRP(asset) || (mSrcIssuer && asset.getIssuer() == mSrcIssuer) || + asset.getIssuer() == mSrcAccount; - return matchingCurrency && matchingAccount; + return matchingAsset && matchingAccount; } int Pathfinder::getPathsOut( - Currency const& currency, + PathAsset const& pathAsset, AccountID const& account, LineDirection direction, - bool isDstCurrency, + bool isDstAsset, AccountID const& dstAccount, std::function const& continueCallback) { - Issue const issue(currency, account); + Asset const asset = assetFromPathAsset(pathAsset, account); - auto [it, inserted] = mPathsOutCountMap.emplace(issue, 0); + auto [it, inserted] = mPathsOutCountMap.emplace(asset, 0); // If it was already present, return the stored number of paths if (!inserted) @@ -703,48 +725,87 @@ Pathfinder::getPathsOut( if (!sleAccount) return 0; - int const aFlags = sleAccount->getFieldU32(sfFlags); - bool const bAuthRequired = (aFlags & lsfRequireAuth) != 0; - bool const bFrozen = ((aFlags & lsfGlobalFreeze) != 0); + auto const aFlags = sleAccount->getFieldU32(sfFlags); + bool const bAuthRequired = [&]() { + if (pathAsset.holds()) + return (aFlags & lsfRequireAuth) != 0; + return !isTesSuccess(requireAuth(*mLedger, asset.get(), account)); + }(); + bool const bFrozen = [&]() { + if (pathAsset.holds()) + return (aFlags & lsfGlobalFreeze) != 0; + return isGlobalFrozen(*mLedger, asset.get()); + }(); int count = 0; if (!bFrozen) { - count = app_.getOrderBookDB().getBookSize(issue, mDomain); + count = app_.getOrderBookDB().getBookSize(asset, mDomain); - if (auto const lines = mRLCache->getRippleLines(account, direction)) - { - for (auto const& rspEntry : *lines) - { - if (currency != rspEntry.getLimit().getCurrency()) + asset.visit( + [&](Issue const&) { + if (auto const lines = mAssetCache->getRippleLines(account, direction)) { + for (auto const& rspEntry : *lines) + { + if (pathAsset.get() != rspEntry.getLimit().get().currency) + { + } + else if ( + rspEntry.getBalance() <= beast::zero && + (!rspEntry.getLimitPeer() || + -rspEntry.getBalance() >= rspEntry.getLimitPeer() || + (bAuthRequired && !rspEntry.getAuth()))) + { + } + else if (isDstAsset && dstAccount == rspEntry.getAccountIDPeer()) + { + count += 10000; // count a path to the destination extra + } + else if (rspEntry.getNoRipplePeer()) + { + // This probably isn't a useful path out + } + else if (rspEntry.getFreezePeer()) + { + // Not a useful path out + } + else + { + ++count; + } + } } - else if ( - rspEntry.getBalance() <= beast::zero && - (!rspEntry.getLimitPeer() || - -rspEntry.getBalance() >= rspEntry.getLimitPeer() || - (bAuthRequired && !rspEntry.getAuth()))) + }, + [&](MPTIssue const&) { + if (auto const mpts = mAssetCache->getMPTs(account)) { + for (auto const& mpt : *mpts) + { + if (pathAsset.get() != mpt.getMptID()) + { + } + else if (mpt.isZeroBalance() || mpt.isMaxedOut()) + { + } + else if (bAuthRequired) + { + } + else if (isDstAsset && dstAccount == getMPTIssuer(mpt)) + { + count += 10000; + } + else if (isIndividualFrozen(*mLedger, account, MPTIssue{mpt.getMptID()})) + { + } + else + { + ++count; + } + } } - else if (isDstCurrency && dstAccount == rspEntry.getAccountIDPeer()) - { - count += 10000; // count a path to the destination extra - } - else if (rspEntry.getNoRipplePeer()) - { - // This probably isn't a useful path out - } - else if (rspEntry.getFreezePeer()) - { - // Not a useful path out - } - else - { - ++count; - } - } - } + }); } it->second = count; return count; @@ -872,7 +933,7 @@ Pathfinder::isNoRippleOut(STPath const& currentPath) auto const& fromAccount = (currentPath.size() == 1) ? mSrcAccount : (currentPath.end() - 2)->getAccountID(); auto const& toAccount = endElement.getAccountID(); - return isNoRipple(fromAccount, toAccount, endElement.getCurrency()); + return endElement.hasCurrency() && isNoRipple(fromAccount, toAccount, endElement.getCurrency()); } void @@ -896,10 +957,10 @@ Pathfinder::addLink( std::function const& continueCallback) { auto const& pathEnd = currentPath.empty() ? mSource : currentPath.back(); - auto const& uEndCurrency = pathEnd.getCurrency(); + auto const& uEndPathAsset = pathEnd.getPathAsset(); auto const& uEndIssuer = pathEnd.getIssuerID(); auto const& uEndAccount = pathEnd.getAccountID(); - bool const bOnXRP = uEndCurrency.isZero(); + bool const bOnXRP = isXRP(uEndPathAsset); // Does pathfinding really need to get this to // a gateway (the issuer of the destination amount) @@ -930,25 +991,38 @@ Pathfinder::addLink( if (sleEnd) { bool const bRequireAuth((sleEnd->getFieldU32(sfFlags) & lsfRequireAuth) != 0u); - bool const bIsEndCurrency(uEndCurrency == mDstAmount.getCurrency()); + bool const bIsEndAsset(uEndPathAsset == mDstAmount.asset()); bool const bIsNoRippleOut(isNoRippleOut(currentPath)); bool const bDestOnly((addFlags & afAC_LAST) != 0u); - if (auto const lines = mRLCache->getRippleLines( - uEndAccount, - bIsNoRippleOut ? LineDirection::incoming : LineDirection::outgoing)) - { - auto& rippleLines = *lines; + AccountCandidates candidates; - AccountCandidates candidates; - candidates.reserve(rippleLines.size()); + auto forAssets = [&](AssetType const& assets) { + candidates.reserve(assets.size()); - for (auto const& rs : rippleLines) + static bool constexpr isLine = + std::is_same_v>; + static bool constexpr isMPT = + std::is_same_v>; + + for (auto const& asset : assets) { if (continueCallback && !continueCallback()) return; - auto const& acct = rs.getAccountIDPeer(); - LineDirection const direction = rs.getDirectionPeer(); + auto const& acct = [&]() constexpr { + if constexpr (isLine) + return asset.getAccountIDPeer(); + // Unlike trustline, MPT is not bidirectional + if constexpr (isMPT) + return getMPTIssuer(asset); + }(); + auto const direction = [&]() constexpr -> LineDirection { + if constexpr (isLine) + return asset.getDirectionPeer(); + // incoming for MPT since MPT doesn't support + // rippling (see LineDirection comments) + return LineDirection::incoming; + }(); if (hasEffectiveDestination && (acct == mDstAccount)) { @@ -963,25 +1037,46 @@ Pathfinder::addLink( continue; } - if ((uEndCurrency == rs.getLimit().getCurrency()) && - !currentPath.hasSeen(acct, uEndCurrency, acct)) + auto const correctAsset = [&]() { + if constexpr (isLine) + { + return uEndPathAsset.get() == + asset.getLimit().template get().currency; + } + if constexpr (isMPT) + { + return uEndPathAsset.get() == asset.getMptID(); + } + }(); + auto checkAsset = [&]() { + if constexpr (isLine) + { + return ( + (asset.getBalance() <= beast::zero && + (!asset.getLimitPeer() || + -asset.getBalance() >= asset.getLimitPeer() || + (bRequireAuth && !asset.getAuth()))) || + (bIsNoRippleOut && asset.getNoRipple())); + } + if constexpr (isMPT) + { + return asset.isZeroBalance() || asset.isMaxedOut() || + requireAuth(*mLedger, MPTIssue{asset}, acct); + } + }; + + if (correctAsset && !currentPath.hasSeen(acct, uEndPathAsset, acct)) { // path is for correct currency and has not been // seen - if (rs.getBalance() <= beast::zero && - (!rs.getLimitPeer() || -rs.getBalance() >= rs.getLimitPeer() || - (bRequireAuth && !rs.getAuth()))) - { - // path has no credit - } - else if (bIsNoRippleOut && rs.getNoRipple()) + if (checkAsset()) { // Can't leave on this path } else if (bToDestination) { // destination is always worth trying - if (uEndCurrency == mDstAmount.getCurrency()) + if (uEndPathAsset == mDstAmount.asset()) { // this is a complete path if (!currentPath.empty()) @@ -1005,10 +1100,10 @@ Pathfinder::addLink( { // save this candidate int const out = getPathsOut( - uEndCurrency, + uEndPathAsset, acct, direction, - bIsEndCurrency, + bIsEndAsset, mEffectiveDst, continueCallback); if (out != 0) @@ -1016,40 +1111,56 @@ Pathfinder::addLink( } } } + }; - if (!candidates.empty()) + uEndPathAsset.visit( + [&](Currency const&) { + if (auto const lines = mAssetCache->getRippleLines( + uEndAccount, + bIsNoRippleOut ? LineDirection::incoming : LineDirection::outgoing)) + { + forAssets(*lines); + } + }, + [&](MPTID const&) { + if (auto const mpts = mAssetCache->getMPTs(uEndAccount)) + { + forAssets(*mpts); + } + }); + + if (!candidates.empty()) + { + std::sort( + candidates.begin(), + candidates.end(), + std::bind( + compareAccountCandidate, + mLedger->seq(), + std::placeholders::_1, + std::placeholders::_2)); + + int count = candidates.size(); + // allow more paths from source + if ((count > 10) && (uEndAccount != mSrcAccount)) { - std::sort( - candidates.begin(), - candidates.end(), - std::bind( - compareAccountCandidate, - mLedger->seq(), - std::placeholders::_1, - std::placeholders::_2)); + count = 10; + } + else if (count > 50) + { + count = 50; + } - int count = candidates.size(); - // allow more paths from source - if ((count > 10) && (uEndAccount != mSrcAccount)) - { - count = 10; - } - else if (count > 50) - { - count = 50; - } - - auto it = candidates.begin(); - while (count-- != 0) - { - if (continueCallback && !continueCallback()) - return; - // Add accounts to incompletePaths - STPathElement const pathElement( - STPathElement::typeAccount, it->account, uEndCurrency, it->account); - incompletePaths.assembleAdd(currentPath, pathElement); - ++it; - } + auto it = candidates.begin(); + while (count-- != 0) + { + if (continueCallback && !continueCallback()) + return; + // Add accounts to incompletePaths + STPathElement const pathElement( + STPathElement::typeAccount, it->account, uEndPathAsset, it->account); + incompletePaths.assembleAdd(currentPath, pathElement); + ++it; } } } @@ -1065,7 +1176,9 @@ Pathfinder::addLink( if ((addFlags & afOB_XRP) != 0u) { // to XRP only - if (!bOnXRP && app_.getOrderBookDB().isBookToXRP({uEndCurrency, uEndIssuer}, mDomain)) + if (!bOnXRP && + app_.getOrderBookDB().isBookToXRP( + assetFromPathAsset(uEndPathAsset, uEndIssuer), mDomain)) { STPathElement const pathElement( STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); @@ -1075,28 +1188,28 @@ Pathfinder::addLink( else { bool const bDestOnly = (addFlags & afOB_LAST) != 0; - auto books = - app_.getOrderBookDB().getBooksByTakerPays({uEndCurrency, uEndIssuer}, mDomain); + auto books = app_.getOrderBookDB().getBooksByTakerPays( + assetFromPathAsset(uEndPathAsset, uEndIssuer), mDomain); JLOG(j_.trace()) << books.size() << " books found from this currency/issuer"; for (auto const& book : books) { if (continueCallback && !continueCallback()) return; - if (!currentPath.hasSeen(xrpAccount(), book.out.currency, book.out.account) && + if (!currentPath.hasSeen(xrpAccount(), book.out, book.out.getIssuer()) && !issueMatchesOrigin(book.out) && - (!bDestOnly || (book.out.currency == mDstAmount.getCurrency()))) + (!bDestOnly || equalTokens(book.out, mDstAmount.asset()))) { STPath newPath(currentPath); - if (book.out.currency.isZero()) + if (isXRP(book.out)) { // to XRP // add the order book itself newPath.emplace_back( STPathElement::typeCurrency, xrpAccount(), xrpCurrency(), xrpAccount()); - if (mDstAmount.getCurrency().isZero()) + if (isXRP(mDstAmount.asset())) { // destination is XRP, add account and path is // complete @@ -1110,8 +1223,10 @@ Pathfinder::addLink( } } else if (!currentPath.hasSeen( - book.out.account, book.out.currency, book.out.account)) + book.out.getIssuer(), book.out, book.out.getIssuer())) { + auto const assetType = book.out.holds() ? STPathElement::typeCurrency + : STPathElement::typeMPT; // Don't want the book if we've already seen the issuer // book -> account -> book if ((newPath.size() >= 2) && (newPath.back().isAccount()) && @@ -1119,29 +1234,29 @@ Pathfinder::addLink( { // replace the redundant account with the order book newPath[newPath.size() - 1] = STPathElement( - STPathElement::typeCurrency | STPathElement::typeIssuer, + assetType | STPathElement::typeIssuer, xrpAccount(), - book.out.currency, - book.out.account); + book.out, + book.out.getIssuer()); } else { // add the order book newPath.emplace_back( - STPathElement::typeCurrency | STPathElement::typeIssuer, + assetType | STPathElement::typeIssuer, xrpAccount(), - book.out.currency, - book.out.account); + book.out, + book.out.getIssuer()); } - if (hasEffectiveDestination && book.out.account == mDstAccount && - book.out.currency == mDstAmount.getCurrency()) + if (hasEffectiveDestination && book.out.getIssuer() == mDstAccount && + equalTokens(book.out, mDstAmount.asset())) { // We skipped a required issuer } else if ( - book.out.account == mEffectiveDst && - book.out.currency == mDstAmount.getCurrency()) + book.out.getIssuer() == mEffectiveDst && + equalTokens(book.out, mDstAmount.asset())) { // with the destination account, this path is // complete JLOG(j_.trace()) << "complete path found ba: " @@ -1155,9 +1270,9 @@ Pathfinder::addLink( newPath, STPathElement( STPathElement::typeAccount, - book.out.account, - book.out.currency, - book.out.account)); + book.out.getIssuer(), + book.out, + book.out.getIssuer())); } } } diff --git a/src/xrpld/rpc/detail/Pathfinder.h b/src/xrpld/rpc/detail/Pathfinder.h index 662d59ac9a..48f02bb8f9 100644 --- a/src/xrpld/rpc/detail/Pathfinder.h +++ b/src/xrpld/rpc/detail/Pathfinder.h @@ -1,10 +1,11 @@ #pragma once -#include +#include #include #include #include +#include #include #include @@ -21,10 +22,10 @@ class Pathfinder : public CountedObject public: /** Construct a pathfinder without an issuer.*/ Pathfinder( - std::shared_ptr const& cache, + std::shared_ptr const& cache, AccountID const& srcAccount, AccountID const& dstAccount, - Currency const& uSrcCurrency, + PathAsset const& uSrcPathAsset, std::optional const& uSrcIssuer, STAmount const& dstAmount, std::optional const& srcAmount, @@ -114,14 +115,14 @@ private: addPathsForType(PathType const& type, std::function const& continueCallback); bool - issueMatchesOrigin(Issue const&); + issueMatchesOrigin(Asset const&); int getPathsOut( - Currency const& currency, + PathAsset const& pathAsset, AccountID const& account, LineDirection direction, - bool isDestCurrency, + bool isDestPathAsset, AccountID const& dest, std::function const& continueCallback); @@ -170,7 +171,7 @@ private: AccountID mDstAccount; AccountID mEffectiveDst; // The account the paths need to end at STAmount mDstAmount; - Currency mSrcCurrency; + PathAsset mSrcPathAsset; std::optional mSrcIssuer; STAmount mSrcAmount; /** The amount remaining from mSrcAccount after the default liquidity has @@ -181,14 +182,14 @@ private: std::shared_ptr mLedger; std::unique_ptr m_loadEvent; - std::shared_ptr mRLCache; + std::shared_ptr mAssetCache; STPathElement mSource; STPathSet mCompletePaths; std::vector mPathRanks; std::map mPaths; - hash_map mPathsOutCountMap; + hash_map mPathsOutCountMap; Application& app_; beast::Journal const j_; diff --git a/src/xrpld/rpc/detail/PathfinderUtils.h b/src/xrpld/rpc/detail/PathfinderUtils.h index 560deca2d6..4f5566bdec 100644 --- a/src/xrpld/rpc/detail/PathfinderUtils.h +++ b/src/xrpld/rpc/detail/PathfinderUtils.h @@ -7,10 +7,13 @@ namespace xrpl { inline STAmount largestAmount(STAmount const& amt) { - if (amt.native()) - return INITIAL_XRP; - - return STAmount(amt.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); + return amt.asset().visit( + [&](Issue const& issue) -> STAmount { + if (issue.native()) + return INITIAL_XRP; + return STAmount(amt.asset(), STAmount::cMaxValue, STAmount::cMaxOffset); + }, + [&](MPTIssue const&) { return STAmount(amt.asset(), maxMPTokenAmount, 0); }); } inline STAmount diff --git a/src/xrpld/rpc/detail/RPCHelpers.cpp b/src/xrpld/rpc/detail/RPCHelpers.cpp index 190254fc37..e7b56feac4 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.cpp +++ b/src/xrpld/rpc/detail/RPCHelpers.cpp @@ -14,6 +14,7 @@ #include #include +#include namespace xrpl { namespace RPC { @@ -384,5 +385,64 @@ isAccountObjectsValidType(LedgerEntryType const& type) } } +error_code_i +parseSubUnsubJson( + Asset& asset, + Json::Value const& params, + Json::StaticString const& name, + beast::Journal j) +{ + auto const& jv = params[name]; + auto const [issuerError, assetError] = [&]() { + if (name == jss::taker_pays) + return std::make_pair(rpcSRC_ISR_MALFORMED, rpcSRC_CUR_MALFORMED); + return std::make_pair(rpcDST_ISR_MALFORMED, rpcDST_AMT_MALFORMED); + }(); + + if (jv.isMember(jss::mpt_issuance_id) && + (jv.isMember(jss::currency) || jv.isMember(jss::issuer))) + { + JLOG(j.info()) << boost::format("Bad %s currency or MPT.") % name.c_str(); + return rpcINVALID_PARAMS; + } + + if (jv.isMember(jss::currency)) + { + Issue issue = xrpIssue(); + // Parse mandatory currency. + if (!jv.isMember(jss::currency) || + !to_currency(issue.currency, jv[jss::currency].asString())) + { + JLOG(j.info()) << boost::format("Bad %s currency.") % name.c_str(); + return assetError; + } + + // Parse optional issuer. + if (((jv.isMember(jss::issuer)) && + (!jv[jss::issuer].isString() || !to_issuer(issue.account, jv[jss::issuer].asString()))) + // Don't allow illegal issuers. + || (!issue.currency != !issue.account) || noAccount() == issue.account) + { + JLOG(j.info()) << boost::format("Bad %s issuer.") % name.c_str(); + return issuerError; + } + asset = issue; + } + else if (jv.isMember(jss::mpt_issuance_id)) + { + MPTID mptid; + if (!mptid.parseHex(jv[jss::mpt_issuance_id].asString())) + return assetError; + asset = mptid; + } + else + { + JLOG(j.info()) << boost::format("Neither %s currency or MPT is present.") % name.c_str(); + return assetError; + } + + return rpcSUCCESS; +} + } // namespace RPC } // namespace xrpl diff --git a/src/xrpld/rpc/detail/RPCHelpers.h b/src/xrpld/rpc/detail/RPCHelpers.h index 00a0018870..64f7d223a6 100644 --- a/src/xrpld/rpc/detail/RPCHelpers.h +++ b/src/xrpld/rpc/detail/RPCHelpers.h @@ -154,6 +154,15 @@ keypairForSignature( Json::Value& error, unsigned int apiVersion = apiVersionIfUnspecified); +/** Parse subscribe/unsubscribe parameters + */ +error_code_i +parseSubUnsubJson( + Asset& asset, + Json::Value const& jv, + Json::StaticString const& name, + beast::Journal j); + } // namespace RPC } // namespace xrpl diff --git a/src/xrpld/rpc/detail/RippleLineCache.cpp b/src/xrpld/rpc/detail/RippleLineCache.cpp index 7cc77f9b8b..e69de29bb2 100644 --- a/src/xrpld/rpc/detail/RippleLineCache.cpp +++ b/src/xrpld/rpc/detail/RippleLineCache.cpp @@ -1,101 +0,0 @@ -#include -#include - -namespace xrpl { - -RippleLineCache::RippleLineCache(std::shared_ptr const& ledger, beast::Journal j) - : ledger_(ledger), journal_(j) -{ - JLOG(journal_.debug()) << "created for ledger " << ledger_->header().seq; -} - -RippleLineCache::~RippleLineCache() -{ - JLOG(journal_.debug()) << "destroyed for ledger " << ledger_->header().seq << " with " - << lines_.size() << " accounts and " << totalLineCount_ - << " distinct trust lines."; -} - -std::shared_ptr> -RippleLineCache::getRippleLines(AccountID const& accountID, LineDirection direction) -{ - auto const hash = hasher_(accountID); - AccountKey key(accountID, direction, hash); - AccountKey otherkey( - accountID, - direction == LineDirection::outgoing ? LineDirection::incoming : LineDirection::outgoing, - hash); - - std::lock_guard const sl(mLock); - - auto [it, inserted] = - [&]() { - if (auto otheriter = lines_.find(otherkey); otheriter != lines_.end()) - { - // The whole point of using the direction flag is to reduce the - // number of trust line objects held in memory. Ensure that there is - // only a single set of trustlines in the cache per account. - auto const size = otheriter->second ? otheriter->second->size() : 0; - JLOG(journal_.info()) - << "Request for " - << (direction == LineDirection::outgoing ? "outgoing" : "incoming") - << " trust lines for account " << accountID << " found " << size - << (direction == LineDirection::outgoing ? " incoming" : " outgoing") - << " trust lines. " - << (direction == LineDirection::outgoing ? "Deleting the subset of incoming" - : "Returning the superset of outgoing") - << " trust lines. "; - if (direction == LineDirection::outgoing) - { - // This request is for the outgoing set, but there is already a - // subset of incoming lines in the cache. Erase that subset - // to be replaced by the full set. The full set will be built - // below, and will be returned, if needed, on subsequent calls - // for either value of outgoing. - XRPL_ASSERT( - size <= totalLineCount_, - "xrpl::RippleLineCache::getRippleLines : maximum lines"); - totalLineCount_ -= size; - lines_.erase(otheriter); - } - else - { - // This request is for the incoming set, but there is - // already a superset of the outgoing trust lines in the cache. - // The path finding engine will disregard the non-rippling trust - // lines, so to prevent them from being stored twice, return the - // outgoing set. - key = otherkey; - return std::pair{otheriter, false}; - } - } - return lines_.emplace(key, nullptr); - }(); - - if (inserted) - { - XRPL_ASSERT(it->second == nullptr, "xrpl::RippleLineCache::getRippleLines : null lines"); - auto lines = PathFindTrustLine::getItems(accountID, *ledger_, direction); - if (!lines.empty()) - { - it->second = std::make_shared>(std::move(lines)); - totalLineCount_ += it->second->size(); - } - } - - XRPL_ASSERT( - !it->second || (!it->second->empty()), - "xrpl::RippleLineCache::getRippleLines : null or nonempty lines"); - auto const size = it->second ? it->second->size() : 0; - JLOG(journal_.trace()) << "getRippleLines for ledger " << ledger_->header().seq << " found " - << size - << (key.direction_ == LineDirection::outgoing ? " outgoing" - : " incoming") - << " lines for " << (inserted ? "new " : "existing ") << accountID - << " out of a total of " << lines_.size() << " accounts and " - << totalLineCount_ << " trust lines"; - - return it->second; -} - -} // namespace xrpl diff --git a/src/xrpld/rpc/detail/RippleLineCache.h b/src/xrpld/rpc/detail/RippleLineCache.h index 65607f2d25..e69de29bb2 100644 --- a/src/xrpld/rpc/detail/RippleLineCache.h +++ b/src/xrpld/rpc/detail/RippleLineCache.h @@ -1,101 +0,0 @@ -#pragma once - -#include - -#include -#include -#include - -#include -#include -#include - -namespace xrpl { - -// Used by Pathfinder -class RippleLineCache final : public CountedObject -{ -public: - explicit RippleLineCache(std::shared_ptr const& l, beast::Journal j); - ~RippleLineCache(); - - std::shared_ptr const& - getLedger() const - { - return ledger_; - } - - /** Find the trust lines associated with an account. - - @param accountID The account - @param direction Whether the account is an "outgoing" link on the path. - "Outgoing" is defined as the source account, or an account found via a - trustline that has rippling enabled on the @accountID's side. If an - account is "outgoing", all trust lines will be returned. If an account is - not "outgoing", then any trust lines that don't have rippling enabled are - not usable, so only return trust lines that have rippling enabled on - @accountID's side. - @return Returns a vector of the usable trust lines. - */ - std::shared_ptr> - getRippleLines(AccountID const& accountID, LineDirection direction); - -private: - std::mutex mLock; - - xrpl::hardened_hash<> hasher_; - std::shared_ptr ledger_; - - beast::Journal journal_; - - struct AccountKey final : public CountedObject - { - AccountID account_; - LineDirection direction_; - std::size_t hash_value_; - - AccountKey(AccountID const& account, LineDirection direction, std::size_t hash) - : account_(account), direction_(direction), hash_value_(hash) - { - } - - AccountKey(AccountKey const& other) = default; - - AccountKey& - operator=(AccountKey const& other) = default; - - bool - operator==(AccountKey const& lhs) const - { - return hash_value_ == lhs.hash_value_ && account_ == lhs.account_ && - direction_ == lhs.direction_; - } - - std::size_t - get_hash() const - { - return hash_value_; - } - - struct Hash - { - Hash() = default; - - std::size_t - operator()(AccountKey const& key) const noexcept - { - return key.get_hash(); - } - }; - }; - - // Use a shared_ptr so entries can be removed from the map safely. - // Even though a shared_ptr to a vector will take more memory just a vector, - // most accounts are not going to have any entries (estimated over 90%), so - // vectors will not need to be created for them. This should lead to far - // less memory usage overall. - hash_map>, AccountKey::Hash> lines_; - std::size_t totalLineCount_ = 0; -}; - -} // namespace xrpl diff --git a/src/xrpld/rpc/detail/TransactionSign.cpp b/src/xrpld/rpc/detail/TransactionSign.cpp index 23c70b9def..d6909d555b 100644 --- a/src/xrpld/rpc/detail/TransactionSign.cpp +++ b/src/xrpld/rpc/detail/TransactionSign.cpp @@ -206,7 +206,10 @@ checkPayment( if (!dstAccountID) return RPC::invalid_field_error("tx_json.Destination"); - if (params.isMember(jss::build_path) && ((!doPath) || amount.holds())) + if (params.isMember(jss::build_path) && + (!doPath || + (!app.getOpenLedger().current()->rules().enabled(featureMPTokensV2) && + amount.holds()))) { return RPC::make_error( rpcINVALID_PARAMS, "Field 'build_path' not allowed in this context."); @@ -242,9 +245,11 @@ checkPayment( } else { - // If no SendMax, default to Amount with sender as issuer. + // If no SendMax, default to Amount with sender as issuer if Issue. sendMax = amount; - sendMax.setIssuer(srcAddressID); + sendMax.asset().visit( + [&](Issue const&) { sendMax.get().account = srcAddressID; }, + [](MPTIssue const&) {}); } if (sendMax.native() && amount.native()) @@ -260,11 +265,11 @@ checkPayment( if (auto ledger = app.getOpenLedger().current()) { Pathfinder pf( - std::make_shared(ledger, app.getJournal("RippleLineCache")), + std::make_shared(ledger, app.getJournal("AssetCache")), srcAddressID, *dstAccountID, - sendMax.issue().currency, - sendMax.issue().account, + sendMax.asset(), + sendMax.getIssuer(), amount, std::nullopt, domain, @@ -275,7 +280,7 @@ checkPayment( pf.computePathRanks(4); STPath fullLiquidityPath; STPathSet const paths; - result = pf.getBestPaths(4, fullLiquidityPath, paths, sendMax.issue().account); + result = pf.getBestPaths(4, fullLiquidityPath, paths, sendMax.getIssuer()); } } diff --git a/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp b/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp index e509a72862..3713823934 100644 --- a/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp +++ b/src/xrpld/rpc/handlers/account/AccountCurrencies.cpp @@ -55,9 +55,9 @@ doAccountCurrencies(RPC::JsonContext& context) STAmount const& saBalance = rspEntry.getBalance(); if (saBalance < rspEntry.getLimit()) - receive.insert(saBalance.getCurrency()); + receive.insert(saBalance.get().currency); if ((-saBalance) < rspEntry.getLimitPeer()) - send.insert(saBalance.getCurrency()); + send.insert(saBalance.get().currency); } send.erase(badCurrency()); diff --git a/src/xrpld/rpc/handlers/account/AccountLines.cpp b/src/xrpld/rpc/handlers/account/AccountLines.cpp index 24ebfaa446..7985417b50 100644 --- a/src/xrpld/rpc/handlers/account/AccountLines.cpp +++ b/src/xrpld/rpc/handlers/account/AccountLines.cpp @@ -28,7 +28,7 @@ addLine(Json::Value& jsonLines, RPCTrustLine const& line) // Amount reported is negative if other account holds current // account's IOUs. jPeer[jss::balance] = saBalance.getText(); - jPeer[jss::currency] = to_string(saBalance.issue().currency); + jPeer[jss::currency] = to_string(saBalance.get().currency); jPeer[jss::limit] = saLimit.getText(); jPeer[jss::limit_peer] = saLimitPeer.getText(); jPeer[jss::quality_in] = line.getQualityIn().value; diff --git a/src/xrpld/rpc/handlers/account/GatewayBalances.cpp b/src/xrpld/rpc/handlers/account/GatewayBalances.cpp index 20679e5f42..4dd169d5b5 100644 --- a/src/xrpld/rpc/handlers/account/GatewayBalances.cpp +++ b/src/xrpld/rpc/handlers/account/GatewayBalances.cpp @@ -136,7 +136,7 @@ doGatewayBalances(RPC::JsonContext& context) if (escrow.holds()) return; - auto& bal = locked[escrow.getCurrency()]; + auto& bal = locked[escrow.get().currency]; if (bal == beast::zero) { // This is needed to set the currency code correctly @@ -154,7 +154,7 @@ doGatewayBalances(RPC::JsonContext& context) // On overflow return the largest valid STAmount. // Very large sums of STAmount are approximations // anyway. - bal = STAmount(bal.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); + bal = STAmount(bal.get(), STAmount::cMaxValue, STAmount::cMaxOffset); } } } @@ -192,7 +192,7 @@ doGatewayBalances(RPC::JsonContext& context) else { // normal negative balance, obligation to customer - auto& bal = sums[rs->getBalance().getCurrency()]; + auto& bal = sums[rs->getBalance().get().currency]; if (bal == beast::zero) { // This is needed to set the currency code correctly @@ -210,7 +210,7 @@ doGatewayBalances(RPC::JsonContext& context) // On overflow return the largest valid STAmount. // Very large sums of STAmount are approximations // anyway. - bal = STAmount(bal.issue(), STAmount::cMaxValue, STAmount::cMaxOffset); + bal = STAmount(bal.asset(), STAmount::cMaxValue, STAmount::cMaxOffset); } } } @@ -239,7 +239,7 @@ doGatewayBalances(RPC::JsonContext& context) for (auto const& balance : accBalances) { Json::Value entry; - entry[jss::currency] = to_string(balance.issue().currency); + entry[jss::currency] = to_string(balance.get().currency); entry[jss::value] = balance.getText(); balanceArray.append(std::move(entry)); } diff --git a/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp b/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp index d00a3e279b..31662b63a5 100644 --- a/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp +++ b/src/xrpld/rpc/handlers/account/NoRippleCheck.cpp @@ -155,14 +155,14 @@ doNoRippleCheck(RPC::JsonContext& context) ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit).getIssuer(); STAmount const peerLimit = ownedItem->getFieldAmount(bLow ? sfHighLimit : sfLowLimit); - problem += to_string(peerLimit.getCurrency()); + problem += to_string(peerLimit.get().currency); problem += " line to "; problem += to_string(peerLimit.getIssuer()); problems.append(problem); STAmount limitAmount( ownedItem->getFieldAmount(bLow ? sfLowLimit : sfHighLimit)); - limitAmount.setIssuer(peer); + limitAmount.get().account = peer; Json::Value& tx = jvTransactions.append(Json::objectValue); tx["TransactionType"] = jss::TrustSet; diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp index 377983718e..1fa88ac34d 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntry.cpp @@ -112,11 +112,11 @@ parseAMM( return Unexpected(value.error()); } - auto const asset = LedgerEntryHelpers::requiredIssue(params, jss::asset, "malformedRequest"); + auto const asset = LedgerEntryHelpers::requiredAsset(params, jss::asset, "malformedRequest"); if (!asset) return Unexpected(asset.error()); - auto const asset2 = LedgerEntryHelpers::requiredIssue(params, jss::asset2, "malformedRequest"); + auto const asset2 = LedgerEntryHelpers::requiredAsset(params, jss::asset2, "malformedRequest"); if (!asset2) return Unexpected(asset2.error()); diff --git a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h index 9c5f0b2fcb..4a4366556d 100644 --- a/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h +++ b/src/xrpld/rpc/handlers/ledger/LedgerEntryHelpers.h @@ -212,12 +212,12 @@ requiredUInt192( } template <> -inline std::optional +inline std::optional parse(Json::Value const& param) { try { - return issueFromJson(param); + return assetFromJson(param); } catch (std::runtime_error const&) { @@ -225,10 +225,10 @@ parse(Json::Value const& param) } } -inline Expected -requiredIssue(Json::Value const& params, Json::StaticString const fieldName, std::string const& err) +inline Expected +requiredAsset(Json::Value const& params, Json::StaticString const fieldName, std::string const& err) { - return required(params, fieldName, err, "Issue"); + return required(params, fieldName, err, "Asset"); } inline Expected diff --git a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp index cdd70a5cd8..425642b471 100644 --- a/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp +++ b/src/xrpld/rpc/handlers/orderbook/AMMInfo.cpp @@ -13,16 +13,16 @@ namespace xrpl { -Expected -getIssue(Json::Value const& v, beast::Journal j) +Expected +getAsset(Json::Value const& v, beast::Journal j) { try { - return issueFromJson(v); + return assetFromJson(v); } catch (std::runtime_error const& ex) { - JLOG(j.debug()) << "getIssue " << ex.what(); + JLOG(j.debug()) << "getAsset " << ex.what(); } return Unexpected(rpcISSUE_MALFORMED); } @@ -52,15 +52,15 @@ doAMMInfo(RPC::JsonContext& context) struct ValuesFromContextParams { std::optional accountID; - Issue issue1; - Issue issue2; + Asset asset1; + Asset asset2; std::shared_ptr amm; }; auto getValuesFromContextParams = [&]() -> Expected { std::optional accountID; - std::optional issue1; - std::optional issue2; + std::optional asset1; + std::optional asset2; std::optional ammID; constexpr auto invalid = [](Json::Value const& params) -> bool { @@ -74,9 +74,9 @@ doAMMInfo(RPC::JsonContext& context) if (params.isMember(jss::asset)) { - if (auto const i = getIssue(params[jss::asset], context.j)) + if (auto const i = getAsset(params[jss::asset], context.j)) { - issue1 = *i; + asset1 = *i; } else { @@ -86,9 +86,9 @@ doAMMInfo(RPC::JsonContext& context) if (params.isMember(jss::asset2)) { - if (auto const i = getIssue(params[jss::asset2], context.j)) + if (auto const i = getAsset(params[jss::asset2], context.j)) { - issue2 = *i; + asset2 = *i; } else { @@ -121,25 +121,25 @@ doAMMInfo(RPC::JsonContext& context) return Unexpected(rpcINVALID_PARAMS); XRPL_ASSERT( - (issue1.has_value() == issue2.has_value()) && (issue1.has_value() != ammID.has_value()), - "xrpl::doAMMInfo : issue1 and issue2 do match"); + (asset1.has_value() == asset2.has_value()) && (asset1.has_value() != ammID.has_value()), + "xrpl::doAMMInfo : asset1 and asset2 do match"); auto const ammKeylet = [&]() { - if (issue1 && issue2) - return keylet::amm(*issue1, *issue2); + if (asset1 && asset2) + return keylet::amm(*asset1, *asset2); XRPL_ASSERT(ammID, "xrpl::doAMMInfo::ammKeylet : ammID is set"); return keylet::amm(*ammID); }(); auto const amm = ledger->read(ammKeylet); if (!amm) return Unexpected(rpcACT_NOT_FOUND); - if (!issue1 && !issue2) + if (!asset1 && !asset2) { - issue1 = (*amm)[sfAsset].get(); - issue2 = (*amm)[sfAsset2].get(); + asset1 = (*amm)[sfAsset]; + asset2 = (*amm)[sfAsset2]; } - return ValuesFromContextParams{accountID, *issue1, *issue2, amm}; + return ValuesFromContextParams{accountID, *asset1, *asset2, amm}; }; auto const r = getValuesFromContextParams(); @@ -149,13 +149,19 @@ doAMMInfo(RPC::JsonContext& context) return result; } - auto const& [accountID, issue1, issue2, amm] = *r; + auto const& [accountID, asset1, asset2, amm] = *r; auto const ammAccountID = amm->getAccountID(sfAccount); // provide funds if frozen, specify asset_frozen flag auto const [asset1Balance, asset2Balance] = ammPoolHolds( - *ledger, ammAccountID, issue1, issue2, FreezeHandling::fhIGNORE_FREEZE, context.j); + *ledger, + ammAccountID, + asset1, + asset2, + FreezeHandling::fhIGNORE_FREEZE, + AuthHandling::ahIGNORE_AUTH, + context.j); auto const lptAMMBalance = accountID ? ammLPHolds(*ledger, *amm, *accountID, context.j) : (*amm)[sfLPTokenBalance]; @@ -213,13 +219,11 @@ doAMMInfo(RPC::JsonContext& context) if (!isXRP(asset1Balance)) { - ammResult[jss::asset_frozen] = - isFrozen(*ledger, ammAccountID, issue1.currency, issue1.account); + ammResult[jss::asset_frozen] = isFrozen(*ledger, ammAccountID, asset1); } if (!isXRP(asset2Balance)) { - ammResult[jss::asset2_frozen] = - isFrozen(*ledger, ammAccountID, issue2.currency, issue2.account); + ammResult[jss::asset2_frozen] = isFrozen(*ledger, ammAccountID, asset2); } result[jss::amm] = std::move(ammResult); diff --git a/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp index 33d1e938ad..3b4f76dc96 100644 --- a/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp +++ b/src/xrpld/rpc/handlers/orderbook/BookOffers.cpp @@ -12,8 +12,145 @@ #include #include +#include + namespace xrpl { +std::optional +validateTakerJSON(Json::Value const& taker, Json::StaticString const& name) +{ + if (!taker.isMember(jss::currency) && !taker.isMember(jss::mpt_issuance_id)) + { + return RPC::missing_field_error((boost::format("%s.currency") % name.c_str()).str()); + } + + if (taker.isMember(jss::mpt_issuance_id) && + (taker.isMember(jss::currency) || taker.isMember(jss::issuer))) + { + return RPC::invalid_field_error(name.c_str()); + } + + if ((taker.isMember(jss::currency) && !taker[jss::currency].isString()) || + (taker.isMember(jss::mpt_issuance_id) && !taker[jss::mpt_issuance_id].isString())) + { + return RPC::expected_field_error( + (boost::format("%s.currency") % name.c_str()).str(), "string"); + } + + return std::nullopt; +} + +std::optional +parseTakerAssetJSON( + Asset& asset, + Json::Value const& taker, + Json::StaticString const& name, + beast::Journal j) +{ + auto const assetError = [&]() { + if (name == jss::taker_pays) + return rpcSRC_CUR_MALFORMED; + return rpcDST_AMT_MALFORMED; + }(); + + if (taker.isMember(jss::currency)) + { + Issue issue = xrpIssue(); + + if (!to_currency(issue.currency, taker[jss::currency].asString())) + { + JLOG(j.info()) << boost::format("Bad %s currency.") % name.c_str(); + return RPC::make_error( + assetError, + (boost::format("Invalid field '%s.currency', bad currency.") % name.c_str()).str()); + } + asset = issue; + } + else if (taker.isMember(jss::mpt_issuance_id)) + { + MPTID mptid; + if (!mptid.parseHex(taker[jss::mpt_issuance_id].asString())) + { + return RPC::make_error( + assetError, + (boost::format("Invalid field '%s.mpt_issuance_id'") % name.c_str()).str()); + } + asset = mptid; + } + + return std::nullopt; +} + +std::optional +parseTakerIssuerJSON( + Asset& asset, + Json::Value const& taker, + Json::StaticString const& name, + beast::Journal j) +{ + auto const issuerError = [&]() { + if (name == jss::taker_pays) + return rpcSRC_ISR_MALFORMED; + return rpcDST_ISR_MALFORMED; + }(); + + if (taker.isMember(jss::currency)) + { + Issue& issue = asset.get(); + + if (taker.isMember(jss::issuer)) + { + if (!taker[jss::issuer].isString()) + { + return RPC::expected_field_error( + (boost::format("%s.issuer") % name.c_str()).str(), "string"); + } + + if (!to_issuer(issue.account, taker[jss::issuer].asString())) + { + return RPC::make_error( + issuerError, + (boost::format("Invalid field '%s.issuer', bad issuer.") % name.c_str()).str()); + } + + if (issue.account == noAccount()) + { + return RPC::make_error( + issuerError, + (boost::format("Invalid field '%s.issuer', bad issuer account one.") % + name.c_str()) + .str()); + } + } + else + { + issue.account = xrpAccount(); + } + + if (isXRP(issue.currency) && !isXRP(issue.account)) + { + return RPC::make_error( + issuerError, + (boost::format( + "Unneeded field '%s.issuer' for XRP currency " + "specification.") % + name.c_str()) + .str()); + } + + if (!isXRP(issue.currency) && isXRP(issue.account)) + { + return RPC::make_error( + issuerError, + (boost::format("Invalid field '%s.issuer', expected non-XRP issuer.") % + name.c_str()) + .str()); + } + } + + return std::nullopt; +} + Json::Value doBookOffers(RPC::JsonContext& context) { @@ -44,111 +181,25 @@ doBookOffers(RPC::JsonContext& context) if (!taker_gets.isObjectOrNull()) return RPC::object_field_error(jss::taker_gets); - if (!taker_pays.isMember(jss::currency)) - return RPC::missing_field_error("taker_pays.currency"); + if (auto const err = validateTakerJSON(taker_pays, jss::taker_pays)) + return *err; - if (!taker_pays[jss::currency].isString()) - return RPC::expected_field_error("taker_pays.currency", "string"); + if (auto const err = validateTakerJSON(taker_gets, jss::taker_gets)) + return *err; - if (!taker_gets.isMember(jss::currency)) - return RPC::missing_field_error("taker_gets.currency"); + Book book; - if (!taker_gets[jss::currency].isString()) - return RPC::expected_field_error("taker_gets.currency", "string"); + if (auto const err = parseTakerAssetJSON(book.in, taker_pays, jss::taker_pays, context.j)) + return *err; - Currency pay_currency; + if (auto const err = parseTakerAssetJSON(book.out, taker_gets, jss::taker_gets, context.j)) + return *err; - if (!to_currency(pay_currency, taker_pays[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_pays currency."; - return RPC::make_error( - rpcSRC_CUR_MALFORMED, "Invalid field 'taker_pays.currency', bad currency."); - } + if (auto const err = parseTakerIssuerJSON(book.in, taker_pays, jss::taker_pays, context.j)) + return *err; - Currency get_currency; - - if (!to_currency(get_currency, taker_gets[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_gets currency."; - return RPC::make_error( - rpcDST_AMT_MALFORMED, "Invalid field 'taker_gets.currency', bad currency."); - } - - AccountID pay_issuer; - - if (taker_pays.isMember(jss::issuer)) - { - if (!taker_pays[jss::issuer].isString()) - return RPC::expected_field_error("taker_pays.issuer", "string"); - - if (!to_issuer(pay_issuer, taker_pays[jss::issuer].asString())) - { - return RPC::make_error( - rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer."); - } - - if (pay_issuer == noAccount()) - { - return RPC::make_error( - rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', bad issuer account one."); - } - } - else - { - pay_issuer = xrpAccount(); - } - - if (isXRP(pay_currency) && !isXRP(pay_issuer)) - { - return RPC::make_error( - rpcSRC_ISR_MALFORMED, - "Unneeded field 'taker_pays.issuer' for " - "XRP currency specification."); - } - - if (!isXRP(pay_currency) && isXRP(pay_issuer)) - { - return RPC::make_error( - rpcSRC_ISR_MALFORMED, "Invalid field 'taker_pays.issuer', expected non-XRP issuer."); - } - - AccountID get_issuer; - - if (taker_gets.isMember(jss::issuer)) - { - if (!taker_gets[jss::issuer].isString()) - return RPC::expected_field_error("taker_gets.issuer", "string"); - - if (!to_issuer(get_issuer, taker_gets[jss::issuer].asString())) - { - return RPC::make_error( - rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer."); - } - - if (get_issuer == noAccount()) - { - return RPC::make_error( - rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', bad issuer account one."); - } - } - else - { - get_issuer = xrpAccount(); - } - - if (isXRP(get_currency) && !isXRP(get_issuer)) - { - return RPC::make_error( - rpcDST_ISR_MALFORMED, - "Unneeded field 'taker_gets.issuer' for " - "XRP currency specification."); - } - - if (!isXRP(get_currency) && isXRP(get_issuer)) - { - return RPC::make_error( - rpcDST_ISR_MALFORMED, "Invalid field 'taker_gets.issuer', expected non-XRP issuer."); - } + if (auto const err = parseTakerIssuerJSON(book.out, taker_gets, jss::taker_gets, context.j)) + return *err; std::optional takerID; if (context.params.isMember(jss::taker)) @@ -174,7 +225,7 @@ doBookOffers(RPC::JsonContext& context) domain = num; } - if (pay_currency == get_currency && pay_issuer == get_issuer) + if (book.in == book.out) { JLOG(context.j.info()) << "taker_gets same as taker_pays."; return RPC::make_error(rpcBAD_MARKET); @@ -192,7 +243,7 @@ doBookOffers(RPC::JsonContext& context) context.netOps.getBookPage( lpLedger, - {{pay_currency, pay_issuer}, {get_currency, get_issuer}, domain}, + {book.in, book.out, domain}, takerID ? *takerID : beast::zero, bProof, limit, diff --git a/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp index af3e998a58..8b3e5a5e1f 100644 --- a/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp +++ b/src/xrpld/rpc/handlers/subscribe/Subscribe.cpp @@ -217,48 +217,16 @@ doSubscribe(RPC::JsonContext& context) return rpcError(rpcINVALID_PARAMS); Book book; - Json::Value taker_pays = j[jss::taker_pays]; - Json::Value taker_gets = j[jss::taker_gets]; - // Parse mandatory currency. - if (!taker_pays.isMember(jss::currency) || - !to_currency(book.in.currency, taker_pays[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_pays currency."; - return rpcError(rpcSRC_CUR_MALFORMED); - } + if (auto const err = RPC::parseSubUnsubJson(book.in, j, jss::taker_pays, context.j); + err != rpcSUCCESS) + return rpcError(err); - // Parse optional issuer. - if (((taker_pays.isMember(jss::issuer)) && - (!taker_pays[jss::issuer].isString() || - !to_issuer(book.in.account, taker_pays[jss::issuer].asString()))) - // Don't allow illegal issuers. - || (!book.in.currency != !book.in.account) || noAccount() == book.in.account) - { - JLOG(context.j.info()) << "Bad taker_pays issuer."; - return rpcError(rpcSRC_ISR_MALFORMED); - } + if (auto const err = RPC::parseSubUnsubJson(book.out, j, jss::taker_gets, context.j); + err != rpcSUCCESS) + return rpcError(err); - // Parse mandatory currency. - if (!taker_gets.isMember(jss::currency) || - !to_currency(book.out.currency, taker_gets[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_gets currency."; - return rpcError(rpcDST_AMT_MALFORMED); - } - - // Parse optional issuer. - if (((taker_gets.isMember(jss::issuer)) && - (!taker_gets[jss::issuer].isString() || - !to_issuer(book.out.account, taker_gets[jss::issuer].asString()))) - // Don't allow illegal issuers. - || (!book.out.currency != !book.out.account) || noAccount() == book.out.account) - { - JLOG(context.j.info()) << "Bad taker_gets issuer."; - return rpcError(rpcDST_ISR_MALFORMED); - } - - if (book.in.currency == book.out.currency && book.in.account == book.out.account) + if (book.in == book.out) { JLOG(context.j.info()) << "taker_gets same as taker_pays."; return rpcError(rpcBAD_MARKET); diff --git a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp index d3e36cc612..6846d9baf3 100644 --- a/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp +++ b/src/xrpld/rpc/handlers/subscribe/Unsubscribe.cpp @@ -152,49 +152,15 @@ doUnsubscribe(RPC::JsonContext& context) return rpcError(rpcINVALID_PARAMS); } - Json::Value taker_pays = jv[jss::taker_pays]; - Json::Value taker_gets = jv[jss::taker_gets]; - Book book; - // Parse mandatory currency. - if (!taker_pays.isMember(jss::currency) || - !to_currency(book.in.currency, taker_pays[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_pays currency."; - return rpcError(rpcSRC_CUR_MALFORMED); - } - // Parse optional issuer. - if (((taker_pays.isMember(jss::issuer)) && - (!taker_pays[jss::issuer].isString() || - !to_issuer(book.in.account, taker_pays[jss::issuer].asString()))) - // Don't allow illegal issuers. - || !isConsistent(book.in) || noAccount() == book.in.account) - { - JLOG(context.j.info()) << "Bad taker_pays issuer."; + if (auto const err = RPC::parseSubUnsubJson(book.in, jv, jss::taker_pays, context.j); + err != rpcSUCCESS) + return rpcError(err); - return rpcError(rpcSRC_ISR_MALFORMED); - } - - // Parse mandatory currency. - if (!taker_gets.isMember(jss::currency) || - !to_currency(book.out.currency, taker_gets[jss::currency].asString())) - { - JLOG(context.j.info()) << "Bad taker_gets currency."; - - return rpcError(rpcDST_AMT_MALFORMED); - } - // Parse optional issuer. - if (((taker_gets.isMember(jss::issuer)) && - (!taker_gets[jss::issuer].isString() || - !to_issuer(book.out.account, taker_gets[jss::issuer].asString()))) - // Don't allow illegal issuers. - || !isConsistent(book.out) || noAccount() == book.out.account) - { - JLOG(context.j.info()) << "Bad taker_gets issuer."; - - return rpcError(rpcDST_ISR_MALFORMED); - } + if (auto const err = RPC::parseSubUnsubJson(book.out, jv, jss::taker_gets, context.j); + err != rpcSUCCESS) + return rpcError(err); if (book.in == book.out) {