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>
26#include <xrpl/protocol/AMMCore.h>
27#include <xrpl/protocol/Feature.h>
28#include <xrpl/protocol/STIssue.h>
29#include <xrpl/protocol/TxFlags.h>
44 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid flags.";
48 auto const amount = ctx.
tx[sfAmount];
49 auto const amount2 = ctx.
tx[sfAmount2];
51 if (amount.issue() == amount2.issue())
54 <<
"AMM Instance: tokens can not have the same currency/issuer.";
60 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid asset1 amount.";
66 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid asset2 amount.";
72 JLOG(ctx.
j.
debug()) <<
"AMM Instance: invalid trading fee.";
89 auto const accountID = ctx.
tx[sfAccount];
90 auto const amount = ctx.
tx[sfAmount];
91 auto const amount2 = ctx.
tx[sfAmount2];
94 if (
auto const ammKeylet =
keylet::amm(amount.issue(), amount2.issue());
97 JLOG(ctx.
j.
debug()) <<
"AMM Instance: ltAMM already exists.";
105 <<
"AMM Instance: account is not authorized, " << amount.issue();
109 if (
auto const ter =
requireAuth(ctx.
view, amount2.issue(), accountID);
113 <<
"AMM Instance: account is not authorized, " << amount2.issue();
121 JLOG(ctx.
j.
debug()) <<
"AMM Instance: involves frozen asset.";
129 if (
auto const issuerAccount =
136 if (noDefaultRipple(ctx.
view, amount.issue()) ||
137 noDefaultRipple(ctx.
view, amount2.issue()))
139 JLOG(ctx.
j.
debug()) <<
"AMM Instance: DefaultRipple not set";
146 if (xrpBalance <= beast::zero)
148 JLOG(ctx.
j.
debug()) <<
"AMM Instance: insufficient reserves";
152 auto insufficientBalance = [&](
STAmount const& asset) {
154 return xrpBalance < asset;
164 if (insufficientBalance(amount) || insufficientBalance(amount2))
167 <<
"AMM Instance: insufficient funds, " << amount <<
" " << amount2;
171 auto isLPToken = [&](
STAmount const& amount) ->
bool {
174 return sle->isFieldPresent(sfAMMID);
178 if (isLPToken(amount) || isLPToken(amount2))
180 JLOG(ctx.
j.
debug()) <<
"AMM Instance: can't create with LPTokens "
181 << amount <<
" " << amount2;
192 auto clawbackDisabled = [&](
Issue const& issue) ->
TER {
203 if (
auto const ter = clawbackDisabled(amount.issue()); ter !=
tesSUCCESS)
205 return clawbackDisabled(amount2.issue());
215 auto const amount = ctx_.
tx[sfAmount];
216 auto const amount2 = ctx_.
tx[sfAmount2];
218 auto const ammKeylet =
keylet::amm(amount.issue(), amount2.issue());
223 for (
auto p = 0; p < maxAccountAttempts; ++p)
225 auto const ammAccount =
236 JLOG(j_.
error()) <<
"AMM Instance: AMM already exists.";
237 return {ammAccount.error(),
false};
242 amount.issue().currency, amount2.issue().currency, *ammAccount);
245 JLOG(j_.
error()) <<
"AMM Instance: LP Token already exists.";
251 sleAMMRoot->setAccountID(sfAccount, *ammAccount);
252 sleAMMRoot->setFieldAmount(sfBalance,
STAmount{});
257 sleAMMRoot->setFieldU32(sfSequence, seqno);
267 sleAMMRoot->setFieldU32(
270 sleAMMRoot->setFieldH256(sfAMMID, ammKeylet.key);
274 auto const lpTokens =
ammLPTokens(amount, amount2, lptIss);
277 auto ammSle = std::make_shared<SLE>(ammKeylet);
278 ammSle->setAccountID(sfAccount, *ammAccount);
279 ammSle->setFieldAmount(sfLPTokenBalance, lpTokens);
280 auto const& [issue1, issue2] =
std::minmax(amount.issue(), amount2.issue());
281 ammSle->setFieldIssue(sfAsset,
STIssue{sfAsset, issue1});
282 ammSle->setFieldIssue(sfAsset2,
STIssue{sfAsset2, issue2});
285 ctx_.
view(), ammSle, account_, lptIss, ctx_.
tx[sfTradingFee]);
293 ammSle->setFieldU64(sfOwnerNode, *page);
297 JLOG(j_.
debug()) <<
"AMM Instance: failed to insert owner dir";
306 JLOG(j_.
debug()) <<
"AMM Instance: failed to send LPT " << lpTokens;
310 auto sendAndTrustSet = [&](
STAmount const& amount) ->
TER {
328 auto const flags = sleRippleState->getFlags();
329 sleRippleState->setFieldU32(sfFlags, flags |
lsfAMMNode);
330 sb.
update(sleRippleState);
337 res = sendAndTrustSet(amount);
340 JLOG(j_.
debug()) <<
"AMM Instance: failed to send " << amount;
345 res = sendAndTrustSet(amount2);
348 JLOG(j_.
debug()) <<
"AMM Instance: failed to send " << amount2;
352 JLOG(j_.
debug()) <<
"AMM Instance: success " << *ammAccount <<
" "
353 << ammKeylet.key <<
" " << lpTokens <<
" " << amount <<
" "
357 Book const book{issueIn, issueOut};
359 if (
auto const bookExisted =
static_cast<bool>(sb.
read(dir));
363 addOrderBook(amount.issue(), amount2.issue(),
getRate(amount2, amount));
364 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.