20#include <xrpld/app/ledger/OrderBookDB.h>
21#include <xrpld/app/misc/AMMHelpers.h>
22#include <xrpld/app/misc/AMMUtils.h>
23#include <xrpld/app/tx/detail/AMMCreate.h>
24#include <xrpld/ledger/Sandbox.h>
25#include <xrpld/ledger/View.h>
27#include <xrpl/protocol/AMMCore.h>
28#include <xrpl/protocol/Feature.h>
29#include <xrpl/protocol/STIssue.h>
30#include <xrpl/protocol/TxFlags.h>
45 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid flags.";
49 auto const amount = ctx.
tx[sfAmount];
50 auto const amount2 = ctx.
tx[sfAmount2];
52 if (amount.issue() == amount2.issue())
55 <<
"AMM Instance: tokens can not have the same currency/issuer.";
61 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid asset1 amount.";
67 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid asset2 amount.";
73 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid trading fee.";
90 auto const accountID = ctx.
tx[sfAccount];
91 auto const amount = ctx.
tx[sfAmount];
92 auto const amount2 = ctx.
tx[sfAmount2];
95 if (
auto const ammKeylet =
keylet::amm(amount.issue(), amount2.issue());
98 JLOG(ctx.
j.
debug()) <<
"AMM Instance: ltAMM already exists.";
106 <<
"AMM Instance: account is not authorized, " << amount.issue();
110 if (
auto const ter =
requireAuth(ctx.
view, amount2.issue(), accountID);
114 <<
"AMM Instance: account is not authorized, " << amount2.issue();
122 JLOG(ctx.
j.
debug()) <<
"AMM Instance: involves frozen asset.";
130 if (
auto const issuerAccount =
137 if (noDefaultRipple(ctx.
view, amount.issue()) ||
138 noDefaultRipple(ctx.
view, amount2.issue()))
140 JLOG(ctx.
j.
debug()) <<
"AMM Instance: DefaultRipple not set";
147 if (xrpBalance <= beast::zero)
149 JLOG(ctx.
j.
debug()) <<
"AMM Instance: insufficient reserves";
153 auto insufficientBalance = [&](
STAmount const& asset) {
155 return xrpBalance < asset;
165 if (insufficientBalance(amount) || insufficientBalance(amount2))
168 <<
"AMM Instance: insufficient funds, " << amount <<
" " << amount2;
172 auto isLPToken = [&](
STAmount const& amount) ->
bool {
175 return sle->isFieldPresent(sfAMMID);
179 if (isLPToken(amount) || isLPToken(amount2))
181 JLOG(ctx.
j.
debug()) <<
"AMM Instance: can't create with LPTokens "
182 << amount <<
" " << amount2;
193 auto clawbackDisabled = [&](
Issue const& issue) ->
TER {
204 if (
auto const ter = clawbackDisabled(amount.issue()); ter !=
tesSUCCESS)
206 return clawbackDisabled(amount2.issue());
216 auto const amount = ctx_.
tx[sfAmount];
217 auto const amount2 = ctx_.
tx[sfAmount2];
219 auto const ammKeylet =
keylet::amm(amount.issue(), amount2.issue());
224 for (
auto p = 0; p < maxAccountAttempts; ++p)
226 auto const ammAccount =
237 JLOG(j_.
error()) <<
"AMM Instance: AMM already exists.";
238 return {ammAccount.error(),
false};
243 amount.issue().currency, amount2.issue().currency, *ammAccount);
246 JLOG(j_.
error()) <<
"AMM Instance: LP Token already exists.";
252 sleAMMRoot->setAccountID(sfAccount, *ammAccount);
253 sleAMMRoot->setFieldAmount(sfBalance,
STAmount{});
258 sleAMMRoot->setFieldU32(sfSequence, seqno);
268 sleAMMRoot->setFieldU32(
271 sleAMMRoot->setFieldH256(sfAMMID, ammKeylet.key);
275 auto const lpTokens =
ammLPTokens(amount, amount2, lptIss);
278 auto ammSle = std::make_shared<SLE>(ammKeylet);
279 ammSle->setAccountID(sfAccount, *ammAccount);
280 ammSle->setFieldAmount(sfLPTokenBalance, lpTokens);
281 auto const& [issue1, issue2] =
std::minmax(amount.issue(), amount2.issue());
282 ammSle->setFieldIssue(sfAsset,
STIssue{sfAsset, issue1});
283 ammSle->setFieldIssue(sfAsset2,
STIssue{sfAsset2, issue2});
286 ctx_.
view(), ammSle, account_, lptIss, ctx_.
tx[sfTradingFee]);
294 ammSle->setFieldU64(sfOwnerNode, *page);
298 JLOG(j_.
debug()) <<
"AMM Instance: failed to insert owner dir";
307 JLOG(j_.
debug()) <<
"AMM Instance: failed to send LPT " << lpTokens;
311 auto sendAndTrustSet = [&](
STAmount const& amount) ->
TER {
329 auto const flags = sleRippleState->getFlags();
330 sleRippleState->setFieldU32(sfFlags, flags |
lsfAMMNode);
331 sb.
update(sleRippleState);
338 res = sendAndTrustSet(amount);
341 JLOG(j_.
debug()) <<
"AMM Instance: failed to send " << amount;
346 res = sendAndTrustSet(amount2);
349 JLOG(j_.
debug()) <<
"AMM Instance: failed to send " << amount2;
353 JLOG(j_.
debug()) <<
"AMM Instance: success " << *ammAccount <<
" "
354 << ammKeylet.key <<
" " << lpTokens <<
" " << amount <<
" "
358 Book const book{issueIn, issueOut};
360 if (
auto const bookExisted =
static_cast<bool>(sb.
read(dir));
364 addOrderBook(amount.issue(), amount2.issue(),
getRate(amount2, amount));
365 addOrderBook(amount2.issue(), amount.issue(),
getRate(amount, amount2));
A generic endpoint for log messages.
static TER preclaim(PreclaimContext const &ctx)
TER doApply() override
Attempt to create the AMM instance.
static NotTEC preflight(PreflightContext const &ctx)
static XRPAmount calculateBaseFee(ReadView const &view, STTx const &tx)
virtual OrderBookDB & getOrderBookDB()=0
State information when applying a tx.
beast::Journal const journal
std::optional< std::uint64_t > dirInsert(Keylet const &directory, uint256 const &key, std::function< void(std::shared_ptr< SLE > const &)> const &describe)
Insert an entry to a directory.
A currency issued by an account.
void addOrderBook(Book const &)
virtual std::shared_ptr< SLE const > read(Keylet const &k) const =0
Return the state item associated with a key.
virtual Fees const & fees() const =0
Returns the fees for the base ledger.
LedgerIndex seq() const
Returns the sequence number of the base ledger.
virtual Rules const & rules() const =0
Returns the tx processing rules.
bool enabled(uint256 const &feature) const
Returns true if a feature is enabled.
Issue const & issue() const
std::uint32_t getFlags() const
Discardable, editable view to a ledger.
void update(std::shared_ptr< SLE > const &sle) override
Indicate changes to a peeked SLE.
void insert(std::shared_ptr< SLE > const &sle) override
Insert a new state SLE.
LedgerInfo const & info() const override
Returns information about the ledger.
std::shared_ptr< SLE const > read(Keylet const &k) const override
Return the state item associated with a key.
std::shared_ptr< SLE > peek(Keylet const &k) override
Prepare to modify the SLE associated with key.
Keylet quality(Keylet const &k, std::uint64_t q) noexcept
The initial directory page for a specific quality.
Keylet amm(Asset const &issue1, Asset const &issue2) noexcept
AMM entry.
Keylet line(AccountID const &id0, AccountID const &id1, Currency const ¤cy) noexcept
The index of a trust line for a given currency.
Keylet account(AccountID const &id) noexcept
AccountID root.
Keylet ownerDir(AccountID const &id) noexcept
The root page of an account's directory.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
NotTEC invalidAMMAmount(STAmount const &amount, std::optional< std::pair< Issue, Issue > > const &pair=std::nullopt, bool validZero=false)
Validate the amount.
bool isXRP(AccountID const &c)
TER requireAuth(ReadView const &view, Issue const &issue, AccountID const &account)
Check if the account lacks required authorization.
@ lsfAllowTrustLineClawback
std::function< void(SLE::ref)> describeOwnerDir(AccountID const &account)
bool ammEnabled(Rules const &)
Return true if required AMM amendments are enabled.
NotTEC preflight1(PreflightContext const &ctx)
Performs early sanity checks on the account and fee fields.
Issue ammLPTIssue(Currency const &cur1, Currency const &cur2, AccountID const &ammAccountID)
Calculate LPT Issue from AMM asset pair.
bool isFrozen(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer)
std::uint64_t getRate(STAmount const &offerOut, STAmount const &offerIn)
AccountID ammAccountID(std::uint16_t prefix, uint256 const &parentHash, uint256 const &ammID)
Calculate AMM account ID.
void initializeFeeAuctionVote(ApplyView &view, std::shared_ptr< SLE > &ammSle, AccountID const &account, Issue const &lptIssue, std::uint16_t tfee)
Initialize Auction and Voting slots and set the trading/discounted fee.
NotTEC preflight2(PreflightContext const &ctx)
Checks whether the signature appears valid.
static std::pair< TER, bool > applyCreate(ApplyContext &ctx_, Sandbox &sb, AccountID const &account_, beast::Journal j_)
STAmount accountHolds(ReadView const &view, AccountID const &account, Currency const ¤cy, AccountID const &issuer, FreezeHandling zeroIfFrozen, beast::Journal j)
STAmount ammLPTokens(STAmount const &asset1, STAmount const &asset2, Issue const &lptIssue)
Calculate LP Tokens given AMM pool reserves.
constexpr std::uint32_t tfUniversalMask
TERSubset< CanCvtToTER > TER
std::uint16_t constexpr TRADING_FEE_THRESHOLD
TER accountSend(ApplyView &view, AccountID const &uSenderID, AccountID const &uReceiverID, STAmount const &saAmount, beast::Journal j, WaiveTransferFee waiveFee)
Calls static accountSendIOU if saAmount represents Issue.
TERSubset< CanCvtToNotTEC > NotTEC
XRPAmount xrpLiquid(ReadView const &view, AccountID const &id, std::int32_t ownerCountAdj, beast::Journal j)
State information when determining if a tx is likely to claim a fee.
State information when preflighting a tx.