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