xrpld
Loading...
Searching...
No Matches
AMMLiquidity.cpp
1#include <xrpl/tx/paths/AMMLiquidity.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/basics/contract.h>
6#include <xrpl/beast/utility/Journal.h>
7#include <xrpl/beast/utility/Zero.h>
8#include <xrpl/beast/utility/instrumentation.h>
9#include <xrpl/ledger/ReadView.h>
10#include <xrpl/ledger/helpers/AMMHelpers.h>
11#include <xrpl/protocol/AccountID.h>
12#include <xrpl/protocol/Asset.h>
13#include <xrpl/protocol/Feature.h>
14#include <xrpl/protocol/IOUAmount.h>
15#include <xrpl/protocol/MPTAmount.h>
16#include <xrpl/protocol/Quality.h>
17#include <xrpl/protocol/Rules.h>
18#include <xrpl/protocol/STAmount.h>
19#include <xrpl/protocol/XRPAmount.h>
20#include <xrpl/tx/paths/AMMOffer.h>
21#include <xrpl/tx/transactors/dex/AMMContext.h>
22
23#include <cstdint>
24#include <exception>
25#include <optional>
26#include <stdexcept>
27
28namespace xrpl {
29
30template <typename TIn, typename TOut>
32 ReadView const& view,
33 AccountID const& ammAccountID,
35 Asset const& in,
36 Asset const& out,
37 AMMContext& ammContext,
39 : ammContext_(ammContext)
40 , ammAccountID_(ammAccountID)
42 , assetIn_(in)
43 , assetOut_(out)
45 , j_(j)
46{
47}
48
49template <typename TIn, typename TOut>
52{
53 auto const amountIn = ammAccountHolds(view, ammAccountID_, assetIn_);
54 auto const amountOut = ammAccountHolds(view, ammAccountID_, assetOut_);
55 // This should not happen.
56 if (amountIn < beast::kZero || amountOut < beast::kZero)
57 Throw<std::runtime_error>("AMMLiquidity: invalid balances");
58
59 return TAmounts{get<TIn>(amountIn), get<TOut>(amountOut)};
60}
61
62template <typename TIn, typename TOut>
65{
67
68 cur.in = toAmount<TIn>(
69 getAsset(balances.in),
73
74 if (ammContext_.curIters() == 0)
75 return cur;
76
77 // clang-format off
78 static constexpr std::uint32_t kFib[AMMContext::kMaxIterations] = {
79 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987,
80 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393,
81 196418, 317811, 514229, 832040, 1346269,};
82 // clang-format on
83
84 XRPL_ASSERT(
85 !ammContext_.maxItersReached(),
86 "xrpl::AMMLiquidity::generateFibSeqOffer : maximum iterations");
87
88 cur.out = toAmount<TOut>(
89 getAsset(balances.out),
90 cur.out * kFib[ammContext_.curIters() - 1],
92 // swapAssetOut() returns negative in this case
93 if (cur.out >= balances.out)
94 Throw<std::overflow_error>("AMMLiquidity: generateFibSeqOffer exceeds the balance");
95
96 cur.in = swapAssetOut(balances, cur.out, tradingFee_);
97
98 return cur;
99}
100
101namespace {
102template <typename T>
103T
104maxOut(T const& out, Asset const& asset)
105{
106 Number const res = out * Number{99, -2};
108}
109} // namespace
110
111template <typename TIn, typename TOut>
112std::optional<AMMOffer<TIn, TOut>>
114{
115 auto const out = maxOut<TOut>(balances.out, assetOut());
116 if (out <= TOut{0} || out >= balances.out)
117 return std::nullopt;
118 return AMMOffer<TIn, TOut>(
119 *this, {swapAssetOut(balances, out, tradingFee_), out}, balances, Quality{balances});
120}
121
122template <typename TIn, typename TOut>
125 const
126{
127 // Can't generate more offers if multi-path.
128 if (ammContext_.maxItersReached())
129 return std::nullopt;
130
131 auto const balances = fetchBalances(view);
132
133 // Frozen accounts
134 if (balances.in == beast::kZero || balances.out == beast::kZero)
135 {
136 JLOG(j_.debug()) << "AMMLiquidity::getOffer, frozen accounts";
137 return std::nullopt;
138 }
139
140 JLOG(j_.trace()) << "AMMLiquidity::getOffer balances " << to_string(initialBalances_.in) << " "
141 << to_string(initialBalances_.out) << " new balances "
142 << to_string(balances.in) << " " << to_string(balances.out);
143
144 // Can't generate AMM with a better quality than CLOB's
145 // quality if AMM's Spot Price quality is less than CLOB quality or is
146 // within a threshold.
147 // Spot price quality (SPQ) is calculated within some precision threshold.
148 // On the next iteration, after SPQ is changed, the new SPQ might be close
149 // to the requested clobQuality but not exactly and potentially SPQ may keep
150 // on approaching clobQuality for many iterations. Checking for the quality
151 // threshold prevents this scenario.
152 if (auto const spotPriceQ = Quality{balances}; clobQuality &&
153 (spotPriceQ <= clobQuality ||
154 withinRelativeDistance(spotPriceQ, *clobQuality, Number(1, -7))))
155 {
156 JLOG(j_.trace()) << "AMMLiquidity::getOffer, higher clob quality";
157 return std::nullopt;
158 }
159
160 auto offer = [&] -> std::optional<AMMOffer<TIn, TOut>> {
161 try
162 {
163 if (ammContext_.multiPath())
164 {
165 auto const amounts = generateFibSeqOffer(balances);
166 if (clobQuality && Quality{amounts} < clobQuality)
167 return std::nullopt;
168 return AMMOffer<TIn, TOut>(*this, amounts, balances, Quality{amounts});
169 }
170 if (!clobQuality)
171 {
172 // If there is no CLOB to compare against, return the largest
173 // amount, which doesn't overflow. The size is going to be
174 // changed in BookStep per either deliver amount limit, or
175 // sendmax, or available output or input funds. Might return
176 // nullopt if the pool is small.
177 return maxOffer(balances);
178 }
179 if (auto const amounts =
180 changeSpotPriceQuality(balances, *clobQuality, tradingFee_, j_))
181 {
182 return AMMOffer<TIn, TOut>(*this, *amounts, balances, Quality{*amounts});
183 }
184 if (view.rules().enabled(fixAMMv1_2))
185 {
186 if (auto const maxAMMOffer = maxOffer(balances);
187 maxAMMOffer && Quality{maxAMMOffer->amount()} > *clobQuality)
188 return maxAMMOffer;
189 }
190 }
191 catch (std::overflow_error const& e)
192 {
193 JLOG(j_.error()) << "AMMLiquidity::getOffer overflow " << e.what();
194
195 return std::nullopt;
196 }
197 catch (std::exception const& e)
198 {
199 JLOG(j_.error()) << "AMMLiquidity::getOffer exception " << e.what();
200 }
201 return std::nullopt;
202 }();
203
204 if (offer)
205 {
206 if (offer->amount().in > beast::kZero && offer->amount().out > beast::kZero)
207 {
208 JLOG(j_.trace()) << "AMMLiquidity::getOffer, created " << to_string(offer->amount().in)
209 << "/" << assetIn_ << " " << to_string(offer->amount().out) << "/"
210 << assetOut_;
211 return offer;
212 }
213
214 JLOG(j_.debug()) << "AMMLiquidity::getOffer, no valid offer " << ammContext_.multiPath()
215 << " " << ammContext_.curIters() << " "
216 << (clobQuality ? clobQuality->rate() : STAmount{}) << " "
217 << to_string(balances.in) << " " << to_string(balances.out);
218 }
219
220 return std::nullopt;
221}
222
231
232} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Maintains AMM info per overall payment engine execution and individual iteration.
Definition AMMContext.h:17
static constexpr std::uint8_t kMaxIterations
Definition AMMContext.h:22
AMMLiquidity class provides AMM offers to BookStep class.
beast::Journal const j_
TAmounts< TIn, TOut > generateFibSeqOffer(TAmounts< TIn, TOut > const &balances) const
Generate AMM offers with the offer size based on Fibonacci sequence.
Asset const & assetOut() const
TAmounts< TIn, TOut > const initialBalances_
Asset const assetIn_
AccountID const ammAccountID_
TAmounts< TIn, TOut > fetchBalances(ReadView const &view) const
Fetches current AMM balances.
std::optional< AMMOffer< TIn, TOut > > getOffer(ReadView const &view, std::optional< Quality > const &clobQuality) const
Generate AMM offer.
Asset const assetOut_
std::optional< AMMOffer< TIn, TOut > > maxOffer(TAmounts< TIn, TOut > const &balances) const
Generate max offer.
AMMLiquidity(ReadView const &view, AccountID const &ammAccountID, std::uint32_t tradingFee, Asset const &in, Asset const &out, AMMContext &ammContext, beast::Journal j)
static Number const kInitialFibSeqPct
std::uint32_t const tradingFee_
std::uint32_t tradingFee() const
AMMContext & ammContext_
Represents synthetic AMM offer in BookStep.
Definition AMMOffer.h:30
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
Represents the logical ratio of output currency to input currency.
Definition Quality.h:90
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
constexpr Zero kZero
Definition Zero.h:30
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
T get(Section const &section, std::string const &name, T const &defaultValue=T{})
Retrieve a key/value pair from a section.
TOut swapAssetIn(TAmounts< TIn, TOut > const &pool, TIn const &assetIn, std::uint16_t tfee)
AMM pool invariant - the product (A * B) after swap in/out has to remain at least the same: (A + in) ...
Definition AMMHelpers.h:397
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
T toAmount(STAmount const &amt)=delete
STAmount ammAccountHolds(ReadView const &view, AccountID const &ammAccountID, Asset const &asset)
Returns total amount held by AMM for the given token.
Asset getAsset(T const &amt)
std::optional< TAmounts< TIn, TOut > > changeSpotPriceQuality(TAmounts< TIn, TOut > const &pool, Quality const &quality, std::uint16_t tfee, beast::Journal j)
Generate AMM offer so that either updated Spot Price Quality (SPQ) is equal to LOB quality (in this c...
Definition AMMHelpers.h:328
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
TIn swapAssetOut(TAmounts< TIn, TOut > const &pool, TOut const &assetOut, std::uint16_t tfee)
Swap assetOut out of the pool and swap in a proportional amount of the other asset.
Definition AMMHelpers.h:456
bool withinRelativeDistance(Quality const &calcQuality, Quality const &reqQuality, Number const &dist)
Check if the relative distance between the qualities is within the requested distance.
Definition AMMHelpers.h:133
XRPL_NO_SANITIZE_ADDRESS void Throw(Args &&... args)
Definition contract.h:52
Represents a pair of input and output currencies.
Definition Quality.h:29
T what(T... args)