xrpld
Loading...
Searching...
No Matches
AMMVote.cpp
1#include <xrpl/tx/transactors/dex/AMMVote.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/basics/Number.h>
5#include <xrpl/beast/utility/Zero.h>
6#include <xrpl/beast/utility/instrumentation.h>
7#include <xrpl/ledger/Sandbox.h>
8#include <xrpl/ledger/helpers/AMMHelpers.h>
9#include <xrpl/protocol/AMMCore.h>
10#include <xrpl/protocol/AccountID.h>
11#include <xrpl/protocol/Feature.h>
12#include <xrpl/protocol/Indexes.h>
13#include <xrpl/protocol/MPTIssue.h>
14#include <xrpl/protocol/SField.h>
15#include <xrpl/protocol/STArray.h>
16#include <xrpl/protocol/STLedgerEntry.h>
17#include <xrpl/protocol/STTx.h>
18#include <xrpl/protocol/TER.h>
19#include <xrpl/protocol/XRPAmount.h>
20#include <xrpl/tx/ApplyContext.h>
21#include <xrpl/tx/Transactor.h>
22
23#include <cstddef>
24#include <cstdint>
25#include <optional>
26#include <utility>
27
28namespace xrpl {
29
30bool
32{
33 return ctx.rules.enabled(featureMPTokensV2) ||
34 (!ctx.tx[sfAsset].holds<MPTIssue>() && !ctx.tx[sfAsset2].holds<MPTIssue>());
35}
36
39{
40 if (auto const res = invalidAMMAssetPair(ctx.tx[sfAsset], ctx.tx[sfAsset2]))
41 {
42 JLOG(ctx.j.debug()) << "AMM Vote: invalid asset pair.";
43 return res;
44 }
45
46 if (ctx.tx[sfTradingFee] > kTradingFeeThreshold)
47 {
48 JLOG(ctx.j.debug()) << "AMM Vote: invalid trading fee.";
49 return temBAD_FEE;
50 }
51
52 return tesSUCCESS;
53}
54
55TER
57{
58 auto const ammSle = ctx.view.read(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2]));
59 if (!ammSle)
60 {
61 JLOG(ctx.j.debug()) << "AMM Vote: Invalid asset pair.";
62 return terNO_AMM;
63 }
64 if (ammSle->getFieldAmount(sfLPTokenBalance) == beast::kZero)
65 {
66 return tecAMM_EMPTY;
67 }
68 if (auto const lpTokensNew = ammLPHolds(ctx.view, *ammSle, ctx.tx[sfAccount], ctx.j);
69 lpTokensNew == beast::kZero)
70 {
71 JLOG(ctx.j.debug()) << "AMM Vote: account is not LP.";
73 }
74
75 return tesSUCCESS;
76}
77
79applyVote(ApplyContext const& ctx, Sandbox& sb, AccountID const& accountID, beast::Journal j)
80{
81 auto const feeNew = ctx.tx[sfTradingFee];
82 auto const ammSle = sb.peek(keylet::amm(ctx.tx[sfAsset], ctx.tx[sfAsset2]));
83 if (!ammSle)
84 return {tecINTERNAL, false};
85 STAmount const lptAMMBalance = (*ammSle)[sfLPTokenBalance];
86 auto const lpTokensNew = ammLPHolds(sb, *ammSle, accountID, ctx.journal);
88 std::size_t minPos{0};
89 AccountID minAccount{0};
90 std::uint32_t minFee{0};
91 STArray updatedVoteSlots;
92 Number num{0};
93 Number den{0};
94 // Account already has vote entry
95 bool foundAccount = false;
96
97 // Iterate over the current vote entries and update each entry
98 // per current total tokens balance and each LP tokens balance.
99 // Find the entry with the least tokens and whether the account
100 // has the vote entry.
101 for (auto const& entry : ammSle->getFieldArray(sfVoteSlots))
102 {
103 auto const entryAccount = entry[sfAccount];
104 auto lpTokens = ammLPHolds(sb, *ammSle, entryAccount, ctx.journal);
105 if (lpTokens == beast::kZero)
106 {
107 JLOG(j.debug()) << "AMMVote::applyVote, accountID " << entryAccount << " is not LP";
108 continue;
109 }
110 auto feeVal = entry[sfTradingFee];
111 STObject newEntry = STObject::makeInnerObject(sfVoteEntry);
112 // The account already has the vote entry.
113 if (entryAccount == accountID)
114 {
115 lpTokens = lpTokensNew;
116 feeVal = feeNew;
117 foundAccount = true;
118 }
119 // Keep running numerator/denominator to calculate the updated fee.
120 num += feeVal * lpTokens;
121 den += lpTokens;
122 newEntry.setAccountID(sfAccount, entryAccount);
123 if (feeVal != 0)
124 newEntry.setFieldU16(sfTradingFee, feeVal);
125 newEntry.setFieldU32(
126 sfVoteWeight,
127 static_cast<std::int64_t>(Number(lpTokens) * kVoteWeightScaleFactor / lptAMMBalance));
128
129 // Find an entry with the least tokens/fee. Make the order deterministic
130 // if the tokens/fees are equal.
131 if (!minTokens ||
132 (lpTokens < *minTokens ||
133 (lpTokens == *minTokens &&
134 (feeVal < minFee || (feeVal == minFee && entryAccount < minAccount)))))
135 {
136 minTokens = lpTokens;
137 minPos = updatedVoteSlots.size();
138 minAccount = entryAccount;
139 minFee = feeVal;
140 }
141 updatedVoteSlots.pushBack(std::move(newEntry));
142 }
143
144 // The account doesn't have the vote entry.
145 if (!foundAccount)
146 {
147 auto const update = [&](std::optional<std::uint8_t> const& minPos = std::nullopt) {
148 STObject newEntry = STObject::makeInnerObject(sfVoteEntry);
149 if (feeNew != 0)
150 newEntry.setFieldU16(sfTradingFee, feeNew);
151 newEntry.setFieldU32(
152 sfVoteWeight,
153 static_cast<std::int64_t>(
154 Number(lpTokensNew) * kVoteWeightScaleFactor / lptAMMBalance));
155 newEntry.setAccountID(sfAccount, accountID);
156 num += feeNew * lpTokensNew;
157 den += lpTokensNew;
158 if (minPos)
159 {
160 *(updatedVoteSlots.begin() + *minPos) = std::move(newEntry);
161 }
162 else
163 {
164 updatedVoteSlots.pushBack(std::move(newEntry));
165 }
166 };
167 // Add new entry if the number of the vote entries
168 // is less than Max.
169 if (updatedVoteSlots.size() < kVoteMaxSlots)
170 {
171 update();
172 // Add the entry if the account has more tokens than
173 // the least token holder or same tokens and higher fee.
174 }
175 // NOLINTBEGIN(bugprone-unchecked-optional-access) slots full means loop ran, minTokens is
176 // set
177 else if (lpTokensNew > *minTokens || (lpTokensNew == *minTokens && feeNew > minFee))
178 {
179 auto const entry = updatedVoteSlots.begin() + minPos;
180 // Remove the least token vote entry.
181 num -= Number((*entry)[~sfTradingFee].valueOr(0)) * *minTokens;
182 den -= *minTokens;
183 update(minPos);
184 }
185 // NOLINTEND(bugprone-unchecked-optional-access)
186 // All slots are full and the account does not hold more LPTokens.
187 // Update anyway to refresh the slots.
188 else
189 {
190 JLOG(j.debug()) << "AMMVote::applyVote, insufficient tokens to "
191 "override other votes";
192 }
193 }
194
195 XRPL_ASSERT(ammSle->isFieldPresent(sfAuctionSlot), "xrpl::applyVote : has auction slot");
196
197 // Update the vote entries and the trading/discounted fee.
198 ammSle->setFieldArray(sfVoteSlots, updatedVoteSlots);
199 if (auto const fee = static_cast<std::int64_t>(num / den))
200 {
201 ammSle->setFieldU16(sfTradingFee, fee);
202 if (ammSle->isFieldPresent(sfAuctionSlot))
203 {
204 auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot);
205 if (auto const discountedFee = fee / kAuctionSlotDiscountedFeeFraction)
206 {
207 auctionSlot.setFieldU16(sfDiscountedFee, discountedFee);
208 }
209 else if (auctionSlot.isFieldPresent(sfDiscountedFee))
210 {
211 auctionSlot.makeFieldAbsent(sfDiscountedFee);
212 }
213 }
214 }
215 else
216 {
217 if (ammSle->isFieldPresent(sfTradingFee))
218 ammSle->makeFieldAbsent(sfTradingFee);
219 if (ammSle->isFieldPresent(sfAuctionSlot))
220 {
221 auto& auctionSlot = ammSle->peekFieldObject(sfAuctionSlot);
222 if (auctionSlot.isFieldPresent(sfDiscountedFee))
223 auctionSlot.makeFieldAbsent(sfDiscountedFee);
224 }
225 }
226 sb.update(ammSle);
227
228 return {tesSUCCESS, true};
229}
230
231TER
233{
234 // This is the ledger view that we work against. Transactions are applied
235 // as we go on processing transactions.
236 Sandbox sb(&ctx_.view());
237
238 auto const result = applyVote(ctx_, sb, accountID_, j_);
239 if (result.second)
240 sb.apply(ctx_.rawView());
241
242 return result.first;
243}
244
245void
247{
248 // No transaction-specific invariants yet (future work).
249}
250
251bool
253{
254 // No transaction-specific invariants yet (future work).
255 return true;
256}
257
258} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
static NotTEC preflight(PreflightContext const &ctx)
Definition AMMVote.cpp:38
bool finalizeInvariants(STTx const &tx, TER result, XRPAmount fee, ReadView const &view, beast::Journal const &j) override
Check transaction-specific post-conditions after all entries have been visited.
Definition AMMVote.cpp:252
static TER preclaim(PreclaimContext const &ctx)
Definition AMMVote.cpp:56
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition AMMVote.cpp:31
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
Definition AMMVote.cpp:246
TER doApply() override
Definition AMMVote.cpp:232
State information when applying a tx.
STTx const & tx
beast::Journal const journal
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
A view into a ledger.
Definition ReadView.h:41
virtual SLE::const_pointer read(Keylet const &k) const =0
Return the state item associated with a key.
bool enabled(UInt256 const &feature) const
Returns true if a feature is enabled.
Definition Rules.cpp:182
size_type size() const
Definition STArray.h:248
iterator begin()
Definition STArray.h:224
void pushBack(STObject const &object)
Definition STArray.h:212
std::shared_ptr< STLedgerEntry const > const & ConstRef
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
void setFieldU16(SField const &field, std::uint16_t)
Definition STObject.cpp:737
static STObject makeInnerObject(SField const &name)
Definition STObject.cpp:79
void setAccountID(SField const &field, AccountID const &)
Definition STObject.cpp:785
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
beast::Journal const j_
Definition Transactor.h:164
AccountID const accountID_
Definition Transactor.h:166
ApplyContext & ctx_
Definition Transactor.h:162
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
constexpr Zero kZero
Definition Zero.h:30
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
constexpr std::uint16_t kVoteMaxSlots
Definition AMMCore.h:29
@ terNO_AMM
Definition TER.h:229
constexpr std::uint16_t kTradingFeeThreshold
Definition AMMCore.h:16
STAmount ammLPHolds(ReadView const &view, Asset const &asset1, Asset const &asset2, AccountID const &ammAccount, AccountID const &lpAccount, beast::Journal const j)
Get the balance of LP tokens.
constexpr std::uint32_t kAuctionSlotDiscountedFeeFraction
Definition AMMCore.h:23
NotTEC invalidAMMAssetPair(Asset const &asset1, Asset const &asset2, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt)
Definition AMMCore.cpp:81
static std::pair< TER, bool > applyVote(ApplyContext const &ctx, Sandbox &sb, AccountID const &accountID, beast::Journal j)
Definition AMMVote.cpp:79
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
@ temBAD_FEE
Definition TER.h:80
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecAMM_EMPTY
Definition TER.h:343
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecINTERNAL
Definition TER.h:321
constexpr std::uint32_t kVoteWeightScaleFactor
Definition AMMCore.h:30
@ tesSUCCESS
Definition TER.h:253
State information when determining if a tx is likely to claim a fee.
Definition Transactor.h:92
ReadView const & view
Definition Transactor.h:95
beast::Journal const j
Definition Transactor.h:100
State information when preflighting a tx.
Definition Transactor.h:39
beast::Journal const j
Definition Transactor.h:46