xrpld
Loading...
Searching...
No Matches
AMMCreate.cpp
1#include <xrpl/tx/transactors/dex/AMMCreate.h>
2
3#include <xrpl/basics/Log.h>
4#include <xrpl/beast/utility/Zero.h>
5#include <xrpl/ledger/ReadView.h>
6#include <xrpl/ledger/Sandbox.h>
7#include <xrpl/ledger/View.h>
8#include <xrpl/ledger/helpers/AMMHelpers.h>
9#include <xrpl/ledger/helpers/AccountRootHelpers.h>
10#include <xrpl/ledger/helpers/MPTokenHelpers.h>
11#include <xrpl/ledger/helpers/TokenHelpers.h>
12#include <xrpl/protocol/AMMCore.h>
13#include <xrpl/protocol/AccountID.h>
14#include <xrpl/protocol/Asset.h>
15#include <xrpl/protocol/Book.h>
16#include <xrpl/protocol/Feature.h>
17#include <xrpl/protocol/Indexes.h>
18#include <xrpl/protocol/Issue.h>
19#include <xrpl/protocol/LedgerFormats.h>
20#include <xrpl/protocol/MPTIssue.h>
21#include <xrpl/protocol/SField.h>
22#include <xrpl/protocol/STAmount.h>
23#include <xrpl/protocol/STIssue.h>
24#include <xrpl/protocol/STLedgerEntry.h>
25#include <xrpl/protocol/STTx.h>
26#include <xrpl/protocol/TER.h>
27#include <xrpl/protocol/XRPAmount.h>
28#include <xrpl/tx/ApplyContext.h>
29#include <xrpl/tx/Transactor.h>
30
31#include <algorithm>
32#include <cstdint>
33#include <memory>
34#include <optional>
35#include <utility>
36
37namespace xrpl {
38
39bool
41{
42 return ctx.rules.enabled(featureMPTokensV2) ||
43 (!ctx.tx[sfAmount].holds<MPTIssue>() && !ctx.tx[sfAmount2].holds<MPTIssue>());
44}
45
48{
49 auto const amount = ctx.tx[sfAmount];
50 auto const amount2 = ctx.tx[sfAmount2];
51
52 if (amount.asset() == amount2.asset())
53 {
54 JLOG(ctx.j.debug()) << "AMM Instance: tokens can not have the same asset.";
55 return temBAD_AMM_TOKENS;
56 }
57
58 if (auto const err = invalidAMMAmount(amount))
59 {
60 JLOG(ctx.j.debug()) << "AMM Instance: invalid asset1 amount.";
61 return err;
62 }
63
64 if (auto const err = invalidAMMAmount(amount2))
65 {
66 JLOG(ctx.j.debug()) << "AMM Instance: invalid asset2 amount.";
67 return err;
68 }
69
70 if (ctx.tx[sfTradingFee] > kTradingFeeThreshold)
71 {
72 JLOG(ctx.j.debug()) << "AMM Instance: invalid trading fee.";
73 return temBAD_FEE;
74 }
75
76 return tesSUCCESS;
77}
78
81{
82 // The fee required for AMMCreate is one owner reserve.
84}
85
86TER
88{
89 auto const accountID = ctx.tx[sfAccount];
90 auto const amount = ctx.tx[sfAmount];
91 auto const amount2 = ctx.tx[sfAmount2];
92
93 // Check if AMM already exists for the token pair
94 if (auto const ammKeylet = keylet::amm(amount.asset(), amount2.asset());
95 ctx.view.read(ammKeylet))
96 {
97 JLOG(ctx.j.debug()) << "AMM Instance: ltAMM already exists.";
98 return tecDUPLICATE;
99 }
100
101 if (auto const ter = requireAuth(ctx.view, amount.asset(), accountID); !isTesSuccess(ter))
102 {
103 JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount.asset();
104 return ter;
105 }
106
107 if (auto const ter = requireAuth(ctx.view, amount2.asset(), accountID); !isTesSuccess(ter))
108 {
109 JLOG(ctx.j.debug()) << "AMM Instance: account is not authorized, " << amount2.asset();
110 return ter;
111 }
112
113 // Globally or individually frozen
114 if (auto const ter = checkFrozen(ctx.view, accountID, amount.asset()); !isTesSuccess(ter))
115
116 {
117 JLOG(ctx.j.debug()) << "AMM Instance: involves frozen or locked asset.";
118 return ter;
119 }
120 if (auto const ter = checkFrozen(ctx.view, accountID, amount2.asset()); !isTesSuccess(ter))
121 {
122 JLOG(ctx.j.debug()) << "AMM Instance: involves frozen or locked asset.";
123 return ter;
124 }
125
126 auto const noDefaultRipple = [](ReadView const& view, Asset const& asset) {
127 if (asset.holds<MPTIssue>() || isXRP(asset))
128 return false;
129
130 if (auto const issuerAccount = view.read(keylet::account(asset.getIssuer())))
131 return !issuerAccount->isFlag(lsfDefaultRipple);
132
133 return false;
134 };
135
136 if (noDefaultRipple(ctx.view, amount.asset()) || noDefaultRipple(ctx.view, amount2.asset()))
137 {
138 JLOG(ctx.j.debug()) << "AMM Instance: DefaultRipple not set";
139 return terNO_RIPPLE;
140 }
141
142 // Check the reserve for LPToken trustline
143 STAmount const xrpBalance = xrpLiquid(ctx.view, accountID, 1, ctx.j);
144 // Insufficient reserve
145 if (xrpBalance <= beast::kZero)
146 {
147 JLOG(ctx.j.debug()) << "AMM Instance: insufficient reserves";
149 }
150
151 auto const insufficientBalance = [&](STAmount const& amount) {
152 if (isXRP(amount))
153 return xrpBalance < amount;
154 return accountFunds(
155 ctx.view,
156 accountID,
157 amount,
160 ctx.j) < amount;
161 };
162
163 if (insufficientBalance(amount) || insufficientBalance(amount2))
164 {
165 JLOG(ctx.j.debug()) << "AMM Instance: insufficient funds, " << amount << " " << amount2;
166 return tecUNFUNDED_AMM;
167 }
168
169 auto const isLPToken = [&](STAmount const& amount) -> bool {
170 if (auto const sle = ctx.view.read(keylet::account(amount.asset().getIssuer())))
171 return sle->isFieldPresent(sfAMMID);
172 return false;
173 };
174
175 if (isLPToken(amount) || isLPToken(amount2))
176 {
177 JLOG(ctx.j.debug()) << "AMM Instance: can't create with LPTokens " << amount << " "
178 << amount2;
180 }
181
182 if (ctx.view.rules().enabled(featureSingleAssetVault))
183 {
184 if (auto const accountId =
185 pseudoAccountAddress(ctx.view, keylet::amm(amount.asset(), amount2.asset()).key);
186 accountId == beast::kZero)
188
189 auto const isMPTIssuerPseudo = [&](Asset const& asset) {
190 if (asset.native())
191 return false;
192
193 if (asset.holds<Issue>())
194 return false;
195
196 return isPseudoAccount(ctx.view, asset.getIssuer());
197 };
198
199 if (isMPTIssuerPseudo(amount.asset()) || isMPTIssuerPseudo(amount2.asset()))
200 {
201 JLOG(ctx.j.debug()) << "AMM Instance: can't create with vault shares " << amount << " "
202 << amount2;
203 return tecWRONG_ASSET;
204 }
205 }
206
207 if (auto const ter = canMPTTradeAndTransfer(ctx.view, amount.asset(), accountID, accountID);
208 !isTesSuccess(ter))
209 return ter;
210 if (auto const ter = canMPTTradeAndTransfer(ctx.view, amount2.asset(), accountID, accountID);
211 !isTesSuccess(ter))
212 return ter;
213
214 // If featureAMMClawback is enabled, allow AMMCreate without checking
215 // if the issuer has clawback enabled
216 if (ctx.view.rules().enabled(featureAMMClawback))
217 return tesSUCCESS;
218
219 // Disallow AMM if the issuer has clawback enabled when featureAMMClawback
220 // is not enabled
221 auto const clawbackDisabled = [&](Asset const& asset) -> TER {
222 return asset.visit(
223 [&](MPTIssue const& issue) -> TER {
224 auto const sle = ctx.view.read(keylet::mptokenIssuance(issue.getMptID()));
225 if (!sle)
226 return tecINTERNAL; // LCOV_EXCL_LINE
227 if (sle->isFlag(lsfMPTCanClawback))
228 return tecNO_PERMISSION;
229 return tesSUCCESS;
230 },
231 [&](Issue const& issue) -> TER {
232 if (isXRP(issue))
233 return tesSUCCESS;
234 auto const sle = ctx.view.read(keylet::account(issue.account));
235 if (!sle)
236 return tecINTERNAL; // LCOV_EXCL_LINE
237 if (sle->isFlag(lsfAllowTrustLineClawback))
238 return tecNO_PERMISSION;
239 return tesSUCCESS;
240 });
241 };
242
243 if (auto const ter = clawbackDisabled(amount.asset()); !isTesSuccess(ter))
244 return ter;
245 if (auto const ter = clawbackDisabled(amount2.asset()); !isTesSuccess(ter))
246 return ter;
247
248 return tesSUCCESS;
249}
250
253{
254 auto const amount = ctx.tx[sfAmount];
255 auto const amount2 = ctx.tx[sfAmount2];
256
257 auto const ammKeylet = keylet::amm(amount.asset(), amount2.asset());
258
259 // Mitigate same account exists possibility
260 auto const maybeAccount = createPseudoAccount(sb, ammKeylet.key, sfAMMID);
261 // AMM account already exists (should not happen)
262 if (!maybeAccount)
263 {
264 JLOG(j.error()) << "AMM Instance: failed to create pseudo account.";
265 return {maybeAccount.error(), false};
266 }
267 auto& acc = *maybeAccount;
268 auto const accountId = (*acc)[sfAccount];
269
270 // LP Token already exists. (should not happen)
271 auto const lptIss = ammLPTIssue(amount.asset(), amount2.asset(), accountId);
272 if (sb.read(keylet::trustLine(accountId, lptIss)))
273 {
274 JLOG(j.error()) << "AMM Instance: LP Token already exists.";
275 return {tecDUPLICATE, false};
276 }
277
278 // Note, that the trustlines created by AMM have 0 credit limit.
279 // This prevents shifting the balance between accounts via AMM,
280 // or sending unsolicited LPTokens. This is a desired behavior.
281 // A user can only receive LPTokens through affirmative action -
282 // either an AMMDeposit, TrustSet, crossing an offer, etc.
283
284 // Calculate initial LPT balance.
285 auto const lpTokens = ammLPTokens(amount, amount2, lptIss);
286
287 // Create ltAMM
288 auto const ammSle = std::make_shared<SLE>(ammKeylet);
289 ammSle->setAccountID(sfAccount, accountId);
290 ammSle->setFieldAmount(sfLPTokenBalance, lpTokens);
291 auto const& [asset1, asset2] = std::minmax(amount.asset(), amount2.asset());
292 ammSle->setFieldIssue(sfAsset, STIssue{sfAsset, asset1});
293 ammSle->setFieldIssue(sfAsset2, STIssue{sfAsset2, asset2});
294 // AMM creator gets the auction slot and the voting slot.
295 initializeFeeAuctionVote(ctx.view(), ammSle, account, lptIss, ctx.tx[sfTradingFee]);
296
297 // Add owner directory to link the root account and AMM object.
298 if (auto const ter = dirLink(sb, accountId, ammSle); ter)
299 {
300 JLOG(j.debug()) << "AMM Instance: failed to insert owner dir";
301 return {ter, false};
302 }
303 sb.insert(ammSle);
304
305 // Send LPT to LP.
306 auto res = accountSend(sb, accountId, account, lpTokens, ctx.journal);
307 if (!isTesSuccess(res))
308 {
309 JLOG(j.debug()) << "AMM Instance: failed to send LPT " << lpTokens;
310 return {res, false};
311 }
312
313 auto const sendAndInitTrustOrMPT = [&](STAmount const& amount) -> TER {
314 // Authorize MPT
315 return amount.asset().visit(
316 [&](MPTIssue const& issue) -> TER {
317 auto const& mptIssue = issue;
318 auto const& mptID = mptIssue.getMptID();
319 // Implicitly authorize MPT asset for AMM pseudo-account.
320 std::uint32_t const flags = lsfMPTAMM | lsfMPTAuthorized;
321 if (auto const err = requireAuth(sb, mptIssue, accountId, AuthType::WeakAuth);
322 !isTesSuccess(err))
323 {
324 return err;
325 }
326
327 if (auto const err = createMPToken(sb, mptID, accountId, {}, flags);
328 !isTesSuccess(err))
329 return err;
330 // Don't adjust AMM owner count.
331 // It's irrelevant for pseudo-account like AMM.
332 return accountSend(
333 sb,
334 account,
335 accountId,
336 amount,
337 ctx.journal,
338 {}, // don't sponsor for AMM Trustline
340 },
341 // Set AMM flag on AMM trustline
342 [&](Issue const& issue) -> TER {
343 if (auto const res = accountSend(
344 sb,
345 account,
346 accountId,
347 amount,
348 ctx.journal,
349 {}, // don't sponsor for AMM Trustline
351 return res;
352 // Set AMM flag on AMM trustline
353 if (!isXRP(amount))
354 {
355 SLE::pointer const sleRippleState =
356 sb.peek(keylet::trustLine(accountId, issue));
357 if (!sleRippleState)
358 {
359 return tecINTERNAL; // LCOV_EXCL_LINE
360 }
361
362 auto const flags = sleRippleState->getFlags();
363 sleRippleState->setFieldU32(sfFlags, flags | lsfAMMNode);
364 sb.update(sleRippleState);
365 }
366 return tesSUCCESS;
367 });
368 };
369
370 // Send asset1.
371 res = sendAndInitTrustOrMPT(amount);
372 if (!isTesSuccess(res))
373 {
374 JLOG(j.debug()) << "AMM Instance: failed to send " << amount;
375 return {res, false};
376 }
377
378 // Send asset2.
379 res = sendAndInitTrustOrMPT(amount2);
380 if (!isTesSuccess(res))
381 {
382 JLOG(j.debug()) << "AMM Instance: failed to send " << amount2;
383 return {res, false};
384 }
385
386 JLOG(j.debug()) << "AMM Instance: success " << accountId << " " << ammKeylet.key << " "
387 << lpTokens << " " << amount << " " << amount2;
388 auto const addOrderBook =
389 [&](Asset const& assetIn, Asset const& assetOut, std::uint64_t uRate) {
390 Book const book{assetIn, assetOut, std::nullopt};
391 auto const dir = keylet::quality(keylet::book(book), uRate);
392 if (auto const bookExisted = static_cast<bool>(sb.read(dir)); !bookExisted)
393 ctx.addOrderBook(book);
394 };
395 addOrderBook(amount.asset(), amount2.asset(), getRate(amount2, amount));
396 addOrderBook(amount2.asset(), amount.asset(), getRate(amount, amount2));
397
398 return {res, isTesSuccess(res)};
399}
400
401TER
403{
404 // This is the ledger view that we work against. Transactions are applied
405 // as we go on processing transactions.
406 Sandbox sb(&ctx_.view());
407
408 auto const result = applyCreate(ctx_, sb, accountID_, j_);
409 if (result.second)
410 sb.apply(ctx_.rawView());
411
412 return result.first;
413}
414
415void
417{
418 // No transaction-specific invariants yet (future work).
419}
420
421bool
423{
424 // No transaction-specific invariants yet (future work).
425 return true;
426}
427
428} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream error() const
Definition Journal.h:362
Stream debug() const
Definition Journal.h:344
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.
TER doApply() override
Attempt to create the AMM instance.
static bool checkExtraFeatures(PreflightContext const &ctx)
Definition AMMCreate.cpp:40
void visitInvariantEntry(bool isDelete, SLE::ConstRef before, SLE::ConstRef after) override
Inspect a single ledger entry modified by this transaction.
static TER preclaim(PreclaimContext const &ctx)
Definition AMMCreate.cpp:87
static NotTEC preflight(PreflightContext const &ctx)
Definition AMMCreate.cpp:47
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
Definition AMMCreate.cpp:80
State information when applying a tx.
STTx const & tx
void addOrderBook(Book const &book)
Registers a newly-created order book directory with the shared, process-wide OrderBookDB,...
beast::Journal const journal
ApplyView & view()
Specifies an order book.
Definition Book.h:28
A currency issued by an account.
Definition Issue.h:18
constexpr MPTID const & getMptID() const
Definition MPTIssue.h:43
A view into a ledger.
Definition ReadView.h:41
virtual Rules const & rules() const =0
Returns the tx processing rules.
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
std::shared_ptr< STLedgerEntry > pointer
std::shared_ptr< STLedgerEntry const > const & ConstRef
void setFieldU32(SField const &field, std::uint32_t)
Definition STObject.cpp:743
std::uint32_t getFlags() const
Definition STObject.cpp:517
Discardable, editable view to a ledger.
Definition Sandbox.h:18
void apply(RawView &to)
Definition Sandbox.h:38
static XRPAmount calculateOwnerReserveFee(ReadView const &view, STTx const &tx)
beast::Journal const j_
Definition Transactor.h:164
ApplyView & view()
Definition Transactor.h:184
AccountID const accountID_
Definition Transactor.h:166
ApplyContext & ctx_
Definition Transactor.h:162
void insert(SLE::Ref sle) override
Insert a new state SLE.
SLE::pointer peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
SLE::const_pointer read(Keylet const &k) const override
Return the state item associated with a key.
void update(SLE::Ref sle) override
Indicate changes to a peeked SLE.
T make_shared(T... args)
T minmax(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet quality(Keylet const &k, std::uint64_t const q) noexcept
The initial directory page for a specific quality.
Definition Indexes.cpp:316
Keylet book(Book const &b)
The beginning of an order book.
Definition Indexes.cpp:281
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Definition Indexes.cpp:483
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Keylet trustLine(AccountID const &id0, AccountID const &id1, Currency const &currency) noexcept
The index of a trust line for a given currency.
Definition Indexes.cpp:287
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Asset, Asset > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
Definition AMMCore.cpp:96
@ terNO_RIPPLE
Definition TER.h:226
@ terADDRESS_COLLISION
Definition TER.h:230
constexpr std::uint16_t kTradingFeeThreshold
Definition AMMCore.h:16
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
Calculate liquid XRP balance for an account.
bool isXRP(AccountID const &c)
Definition AccountID.h:84
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Asset const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
TER checkFrozen(ReadView const &view, AccountID const &account, Issue const &issue)
std::expected< SLE::pointer, TER > createPseudoAccount(ApplyView &view, UInt256 const &pseudoOwnerKey, SField const &ownerField)
Create pseudo-account, storing pseudoOwnerKey into ownerField.
TER canMPTTradeAndTransfer(ReadView const &v, Asset const &asset, AccountID const &from, AccountID const &to)
Convenience to combine canTrade/Transfer.
STAmount accountFunds(ReadView const &view, AccountID const &id, STAmount const &saDefault, FreezeHandling freezeHandling, beast::Journal j)
static std::pair< TER, bool > applyCreate(ApplyContext &ctx, Sandbox &sb, AccountID const &account, beast::Journal j)
TERSubset< CanCvtToNotTEC > NotTEC
Definition TER.h:617
TER accountSend(ApplyView &view, AccountID const &from, AccountID const &to, STAmount const &saAmount, beast::Journal j, SLE::Ref sponsorSle={}, WaiveTransferFee waiveFee=WaiveTransferFee::No, AllowMPTOverflow allowOverflow=AllowMPTOverflow::No)
Calls static accountSendIOU if saAmount represents Issue.
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
AccountID pseudoAccountAddress(ReadView const &view, UInt256 const &pseudoOwnerKey)
Generate a pseudo-account address from a pseudo owner key.
bool isPseudoAccount(SLE::const_pointer sleAcct)
Returns true if and only if sleAcct is a pseudo-account of any kind (i.e.
BaseUInt< 160, detail::AccountIDTag > AccountID
A 160-bit unsigned that uniquely identifies an account.
Definition AccountID.h:34
void initializeFeeAuctionVote(ApplyView const &view, SLE::pointer const &ammSle, AccountID const &account, Asset const &lptAsset, std::uint16_t tfee)
Initialize Auction and Voting slots and set the trading/discounted fee.
@ temBAD_FEE
Definition TER.h:80
@ temBAD_AMM_TOKENS
Definition TER.h:117
bool isTesSuccess(TER x) noexcept
Definition TER.h:686
TER dirLink(ApplyView &view, AccountID const &owner, SLE::pointer const &object, SF_UINT64 const &node=sfOwnerNode)
Definition View.cpp:385
TERSubset< CanCvtToTER > TER
Definition TER.h:657
TER requireAuth(ReadView const &view, MPTIssue const &mptIssue, AccountID const &account, AuthType authType=AuthType::Legacy, std::uint8_t depth=0)
Check if the account lacks required authorization for MPT.
@ tecWRONG_ASSET
Definition TER.h:371
@ tecAMM_INVALID_TOKENS
Definition TER.h:342
@ tecINSUF_RESERVE_LINE
Definition TER.h:299
@ tecUNFUNDED_AMM
Definition TER.h:339
@ tecINTERNAL
Definition TER.h:321
@ tecNO_PERMISSION
Definition TER.h:316
@ tecDUPLICATE
Definition TER.h:326
TER createMPToken(ApplyView &view, MPTID const &mptIssuanceID, AccountID const &account, SLE::Ref sponsorSle, std::uint32_t const flags)
Issue ammLPTIssue(Asset const &asset1, Asset const &asset2, AccountID const &ammAccountID)
Calculate LPT Issue from AMM asset pair.
Definition AMMCore.cpp:52
@ 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