xrpld
Loading...
Searching...
No Matches
AMMInfo.cpp
1#include <xrpld/app/ledger/LedgerMaster.h>
2#include <xrpld/rpc/Context.h>
3#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
4
5#include <xrpl/basics/Log.h>
6#include <xrpl/basics/base_uint.h>
7#include <xrpl/basics/chrono.h>
8#include <xrpl/basics/safe_cast.h>
9#include <xrpl/beast/utility/Journal.h>
10#include <xrpl/beast/utility/instrumentation.h>
11#include <xrpl/core/ServiceRegistry.h>
12#include <xrpl/json/json_value.h>
13#include <xrpl/ledger/ReadView.h>
14#include <xrpl/ledger/helpers/AMMHelpers.h>
15#include <xrpl/ledger/helpers/TokenHelpers.h>
16#include <xrpl/protocol/AMMCore.h>
17#include <xrpl/protocol/AccountID.h>
18#include <xrpl/protocol/Asset.h>
19#include <xrpl/protocol/ErrorCodes.h>
20#include <xrpl/protocol/Feature.h> // IWYU pragma: keep
21#include <xrpl/protocol/Indexes.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STAmount.h>
24#include <xrpl/protocol/jss.h>
25
26#include <date/date.h>
27
28#include <chrono>
29#include <expected>
30#include <memory>
31#include <optional>
32#include <stdexcept>
33#include <string>
34#include <utility>
35
36namespace xrpl {
37
38std::expected<Asset, ErrorCodeI>
40{
41 try
42 {
43 return assetFromJson(v);
44 }
45 catch (std::runtime_error const& ex)
46 {
47 JLOG(j.debug()) << "getAsset " << ex.what();
48 }
50}
51
54{
55 // 2000-01-01 00:00:00 UTC is 946684800s from 1970-01-01 00:00:00 UTC
56 using namespace std::chrono;
57 return date::format(
58 "%Y-%Om-%dT%H:%M:%OS%z",
59 date::sys_time<system_clock::duration>(
60 system_clock::time_point{tp.time_since_epoch() + kEpochOffset}));
61}
62
65{
66 auto const& params(context.params);
67 json::Value result;
68
70 result = rpc::lookupLedger(ledger, context);
71 if (!ledger)
72 return result;
73
74 struct ValuesFromContextParams
75 {
77 Asset asset1;
78 Asset asset2;
80 };
81
82 auto const getValuesFromContextParams =
83 [&] -> std::expected<ValuesFromContextParams, ErrorCodeI> {
88
89 static constexpr auto kInvalid = [](json::Value const& params) -> bool {
90 return (params.isMember(jss::asset) != params.isMember(jss::asset2)) ||
91 (params.isMember(jss::asset) == params.isMember(jss::amm_account));
92 };
93
94 // NOTE, identical check for apVersion >= 3 below
95 if (context.apiVersion < 3 && kInvalid(params))
97
98 if (params.isMember(jss::asset))
99 {
100 if (auto const i = getAsset(params[jss::asset], context.j))
101 {
102 asset1 = *i;
103 }
104 else
105 {
106 return std::unexpected(i.error());
107 }
108 }
109
110 if (params.isMember(jss::asset2))
111 {
112 if (auto const i = getAsset(params[jss::asset2], context.j))
113 {
114 asset2 = *i;
115 }
116 else
117 {
118 return std::unexpected(i.error());
119 }
120 }
121
122 if (params.isMember(jss::amm_account))
123 {
124 auto const& ammAccount = params[jss::amm_account];
125 if (!ammAccount.isString())
127 auto const id = parseBase58<AccountID>(ammAccount.asString());
128 if (!id)
130 auto const sle = ledger->read(keylet::account(*id));
131 if (!sle)
133 ammID = sle->getFieldH256(sfAMMID);
134 if (ammID->isZero())
136 }
137
138 if (params.isMember(jss::account))
139 {
140 auto const& localAccount = params[jss::account];
141 if (!localAccount.isString())
143 accountID = parseBase58<AccountID>(localAccount.asString());
144 if (!accountID || !ledger->read(keylet::account(*accountID)))
146 }
147
148 // NOTE, identical check for apVersion < 3 above
149 if (context.apiVersion >= 3 && kInvalid(params))
151
152 XRPL_ASSERT(
153 (asset1.has_value() == asset2.has_value()) && (asset1.has_value() != ammID.has_value()),
154 "xrpl::doAMMInfo : asset1 and asset2 do match");
155
156 auto const ammKeylet = [&] {
157 if (asset1 && asset2)
158 return keylet::amm(*asset1, *asset2);
159 XRPL_ASSERT(ammID, "xrpl::doAMMInfo::ammKeylet : ammID is set");
160 return keylet::amm(*ammID);
161 }();
162 auto const amm = ledger->read(ammKeylet);
163 if (!amm)
165 if (!asset1 && !asset2)
166 {
167 asset1 = (*amm)[sfAsset];
168 asset2 = (*amm)[sfAsset2];
169 }
170
171 return ValuesFromContextParams{
172 .accountID = accountID,
173 .asset1 = *asset1,
174 .asset2 = *asset2,
175 .amm = amm,
176 };
177 };
178
179 auto const r = getValuesFromContextParams();
180 if (!r)
181 {
182 rpc::injectError(r.error(), result);
183 return result;
184 }
185
186 auto const& [accountID, asset1, asset2, amm] = *r;
187
188 auto const ammAccountID = amm->getAccountID(sfAccount);
189
190 // provide funds if frozen, specify asset_frozen flag
191 auto const [asset1Balance, asset2Balance] = ammPoolHolds(
192 *ledger,
193 ammAccountID,
194 asset1,
195 asset2,
198 context.j);
199 auto const lptAMMBalance =
200 accountID ? ammLPHolds(*ledger, *amm, *accountID, context.j) : (*amm)[sfLPTokenBalance];
201
202 json::Value ammResult;
203 asset1Balance.setJson(ammResult[jss::amount]);
204 asset2Balance.setJson(ammResult[jss::amount2]);
205 lptAMMBalance.setJson(ammResult[jss::lp_token]);
206 ammResult[jss::trading_fee] = (*amm)[sfTradingFee];
207 ammResult[jss::account] = to_string(ammAccountID);
209 if (amm->isFieldPresent(sfVoteSlots))
210 {
211 for (auto const& voteEntry : amm->getFieldArray(sfVoteSlots))
212 {
213 json::Value vote;
214 vote[jss::account] = to_string(voteEntry.getAccountID(sfAccount));
215 vote[jss::trading_fee] = voteEntry[sfTradingFee];
216 vote[jss::vote_weight] = voteEntry[sfVoteWeight];
217 voteSlots.append(std::move(vote));
218 }
219 }
220 if (voteSlots.size() > 0)
221 ammResult[jss::vote_slots] = std::move(voteSlots);
222 XRPL_ASSERT(amm->isFieldPresent(sfAuctionSlot), "xrpl::doAMMInfo : auction slot is present");
223 if (amm->isFieldPresent(sfAuctionSlot))
224 {
225 auto const& auctionSlot = safeDowncast<STObject const&>(amm->peekAtField(sfAuctionSlot));
226 if (auctionSlot.isFieldPresent(sfAccount))
227 {
228 json::Value auction;
229 auto const timeSlot = ammAuctionTimeSlot(
230 ledger->header().parentCloseTime.time_since_epoch().count(), auctionSlot);
231 auction[jss::time_interval] = timeSlot ? *timeSlot : kAuctionSlotTimeIntervals;
232 auctionSlot[sfPrice].setJson(auction[jss::price]);
233 auction[jss::discounted_fee] = auctionSlot[sfDiscountedFee];
234 auction[jss::account] = to_string(auctionSlot.getAccountID(sfAccount));
235 auction[jss::expiration] =
236 toIso8601(NetClock::time_point{NetClock::duration{auctionSlot[sfExpiration]}});
237 if (auctionSlot.isFieldPresent(sfAuthAccounts))
238 {
239 json::Value auth;
240 for (auto const& acct : auctionSlot.getFieldArray(sfAuthAccounts))
241 {
242 json::Value jv;
243 jv[jss::account] = to_string(acct.getAccountID(sfAccount));
244 auth.append(jv);
245 }
246 auction[jss::auth_accounts] = auth;
247 }
248 ammResult[jss::auction_slot] = std::move(auction);
249 }
250 }
251
252 if (!isXRP(asset1Balance))
253 {
254 ammResult[jss::asset_frozen] = isFrozen(*ledger, ammAccountID, asset1);
255 }
256 if (!isXRP(asset2Balance))
257 {
258 ammResult[jss::asset2_frozen] = isFrozen(*ledger, ammAccountID, asset2);
259 }
260
261 result[jss::amm] = std::move(ammResult);
262 if (!result.isMember(jss::ledger_index) && !result.isMember(jss::ledger_hash))
263 result[jss::ledger_current_index] = ledger->header().seq;
264 result[jss::validated] = context.ledgerMaster.isValidated(*ledger);
265
266 return result;
267}
268
269} // namespace xrpl
A generic endpoint for log messages.
Definition Journal.h:44
Stream debug() const
Definition Journal.h:344
Represents a JSON value.
Definition json_value.h:121
Value & append(Value const &value)
Append value to array at the end.
UInt size() const
Number of values in array or object.
bool isMember(char const *key) const
Return true if the object has a member named key.
bool isValidated(ReadView const &ledger)
Tests whether a ledger is on the validated chain, using the skip list when the ledger does not alread...
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
std::shared_ptr< STLedgerEntry const > const_pointer
@ Array
array value (ordered list)
Definition json_value.h:32
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
void injectError(ErrorCodeI code, json::Value &json)
Add or update the json update to reflect the error code.
::rpc::Status lookupLedger(std::shared_ptr< ReadView const > &ledger, JsonContext const &context, json::Value &result)
Looks up a ledger from a request and fills a json::Value with ledger data.
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
static constexpr std::chrono::seconds kEpochOffset
Clock for measuring the network time.
Definition chrono.h:35
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.
@ RpcActNotFound
Definition ErrorCodes.h:53
@ RpcActMalformed
Definition ErrorCodes.h:73
@ RpcIssueMalformed
Definition ErrorCodes.h:129
@ RpcInvalidParams
Definition ErrorCodes.h:67
bool isXRP(AccountID const &c)
Definition AccountID.h:84
std::string toIso8601(NetClock::time_point tp)
Definition AMMInfo.cpp:53
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
std::pair< STAmount, STAmount > ammPoolHolds(ReadView const &view, AccountID const &ammAccountID, Asset const &asset1, Asset const &asset2, FreezeHandling freezeHandling, AuthHandling authHandling, beast::Journal const j)
Get AMM pool balances.
json::Value doAMMInfo(rpc::JsonContext &)
Definition AMMInfo.cpp:64
Asset getAsset(T const &amt)
bool isFrozen(ReadView const &view, AccountID const &account, MPTIssue const &mptIssue, std::uint8_t depth=0)
Returns true if account cannot send or receive tokens of mptIssue because a freeze applies.
constexpr std::uint16_t kAuctionSlotTimeIntervals
Definition AMMCore.h:20
Dest safeDowncast(Src *s) noexcept
Definition safe_cast.h:84
std::optional< std::uint8_t > ammAuctionTimeSlot(std::uint64_t current, STObject const &auctionSlot)
Get time slot of the auction slot.
Definition AMMCore.cpp:109
Asset assetFromJson(json::Value const &jv)
Definition Asset.cpp:59
T has_value(T... args)
beast::Journal const j
Definition Context.h:28
unsigned int apiVersion
Definition Context.h:37
LedgerMaster & ledgerMaster
Definition Context.h:32
json::Value params
Definition Context.h:51
T time_since_epoch(T... args)
T unexpected(T... args)
T what(T... args)