xrpld
Loading...
Searching...
No Matches
GatewayBalances.cpp
1#include <xrpld/app/main/Application.h>
2#include <xrpld/rpc/Context.h>
3#include <xrpld/rpc/detail/RPCLedgerHelpers.h>
4#include <xrpld/rpc/detail/TrustLine.h>
5
6#include <xrpl/beast/utility/Zero.h>
7#include <xrpl/beast/utility/instrumentation.h>
8#include <xrpl/json/json_value.h>
9#include <xrpl/ledger/ReadView.h>
10#include <xrpl/ledger/helpers/DirectoryHelpers.h>
11#include <xrpl/protocol/AccountID.h>
12#include <xrpl/protocol/ErrorCodes.h>
13#include <xrpl/protocol/Indexes.h>
14#include <xrpl/protocol/LedgerFormats.h>
15#include <xrpl/protocol/MPTIssue.h>
16#include <xrpl/protocol/RPCErr.h>
17#include <xrpl/protocol/SField.h>
18#include <xrpl/protocol/STAmount.h>
19#include <xrpl/protocol/UintTypes.h>
20#include <xrpl/protocol/jss.h>
21#include <xrpl/resource/Fees.h>
22
23#include <map>
24#include <memory>
25#include <set>
26#include <stdexcept>
27#include <string>
28#include <utility>
29#include <vector>
30
31namespace xrpl {
32
33// Query:
34// 1) Specify ledger to query.
35// 2) Specify issuer account (cold wallet) in "account" field.
36// 3) Specify accounts that hold gateway assets (such as hot wallets)
37// using "hotwallet" field which should be either a string (if just
38// one wallet) or an array of strings (if more than one).
39
40// Response:
41// 1) Array, "obligations", indicating the total obligations of the
42// gateway in each currency. Obligations to specified hot wallets
43// are not counted here.
44// 2) Object, "balances", indicating balances in each account
45// that holds gateway assets. (Those specified in the "hotwallet"
46// field.)
47// 3) Object of "assets" indicating accounts that owe the gateway.
48// (Gateways typically do not hold positive balances. This is unusual.)
49
50// gateway_balances [<ledger>] <account> [<hotwallet> [<hotwallet [...
51
52json::Value
54{
55 auto& params = context.params;
56
57 // Get the current ledger
59 auto result = rpc::lookupLedger(ledger, context);
60
61 if (!ledger)
62 return result;
63
64 if (!(params.isMember(jss::account) || params.isMember(jss::ident)))
65 return rpc::missingFieldError(jss::account);
66
67 if (params.isMember(jss::account) && !params[jss::account].isString())
68 return rpc::invalidFieldError(jss::account);
69
70 if (params.isMember(jss::ident) && !params[jss::ident].isString())
71 return rpc::invalidFieldError(jss::ident);
72
73 std::string const strIdent(
74 params.isMember(jss::account) ? params[jss::account].asString()
75 : params[jss::ident].asString());
76
77 // Get info on account.
78 auto id = parseBase58<AccountID>(strIdent);
79 if (!id)
81 auto const accountID{id.value()};
83
84 result[jss::account] = toBase58(accountID);
85
86 if (context.apiVersion > 1u && !ledger->exists(keylet::account(accountID)))
87 {
89 return result;
90 }
91
92 // Parse the specified hotwallet(s), if any
93 std::set<AccountID> hotWallets;
94
95 if (params.isMember(jss::hotwallet))
96 {
97 auto const addHotWallet = [&hotWallets](json::Value const& j) {
98 if (j.isString())
99 {
100 if (auto id = parseBase58<AccountID>(j.asString()); id)
101 {
102 hotWallets.insert(id.value());
103 return true;
104 }
105 }
106
107 return false;
108 };
109
110 json::Value const& hw = params[jss::hotwallet];
111 bool valid = true;
112
113 // null is treated as a valid 0-sized array of hotwallet
114 if (hw.isArrayOrNull())
115 {
116 for (auto const& wallet : hw)
117 valid &= addHotWallet(wallet);
118 }
119 else if (hw.isString())
120 {
121 valid &= addHotWallet(hw);
122 }
123 else
124 {
125 valid = false;
126 }
127
128 if (!valid)
129 {
130 // The documentation states that invalidParams is used when
131 // One or more fields are specified incorrectly.
132 // invalidHotwallet should be used when the account exists, but does
133 // not have currency issued by the account from the request.
134 if (context.apiVersion < 2u)
135 {
137 }
138 else
139 {
141 }
142 return result;
143 }
144 }
145
151
152 // Traverse the cold wallet's trust lines
153 {
154 forEachItem(*ledger, accountID, [&](SLE::ConstRef sle) {
155 if (!sle)
156 {
157 // LCOV_EXCL_START
158 UNREACHABLE("xrpl::doGatewayBalances : null SLE");
159 return;
160 // LCOV_EXCL_STOP
161 }
162
163 if (sle->getType() == ltESCROW)
164 {
165 auto const& escrow = sle->getFieldAmount(sfAmount);
166 // Gateway Balance should not include MPTs
167 if (escrow.holds<MPTIssue>())
168 return;
169
170 auto& bal = locked[escrow.get<Issue>().currency];
171 if (bal == beast::kZero)
172 {
173 // This is needed to set the currency code correctly
174 bal = escrow;
175 }
176 else
177 {
178 try
179 {
180 bal += escrow;
181 }
182 catch (std::runtime_error const&)
183 {
184 // Presumably the exception was caused by overflow.
185 // On overflow return the largest valid STAmount.
186 // Very large sums of STAmount are approximations
187 // anyway.
189 }
190 }
191 }
192
193 auto rs = PathFindTrustLine::makeItem(accountID, sle);
194
195 if (!rs)
196 return;
197
198 int const balSign = rs->getBalance().signum();
199 if (balSign == 0)
200 return;
201
202 auto const& peer = rs->getAccountIDPeer();
203
204 // Here, a negative balance means the cold wallet owes (normal)
205 // A positive balance means the cold wallet has an asset
206 // (unusual)
207
208 if (hotWallets.contains(peer))
209 {
210 // This is a specified hot wallet
211 hotBalances[peer].push_back(-rs->getBalance());
212 }
213 else if (balSign > 0)
214 {
215 // This is a gateway asset
216 assets[peer].push_back(rs->getBalance());
217 }
218 else if (rs->getFreeze())
219 {
220 // An obligation the gateway has frozen
221 frozenBalances[peer].push_back(-rs->getBalance());
222 }
223 else
224 {
225 // normal negative balance, obligation to customer
226 auto& bal = sums[rs->getBalance().get<Issue>().currency];
227 if (bal == beast::kZero)
228 {
229 // This is needed to set the currency code correctly
230 bal = -rs->getBalance();
231 }
232 else
233 {
234 try
235 {
236 bal -= rs->getBalance();
237 }
238 catch (std::runtime_error const&)
239 {
240 // Presumably the exception was caused by overflow.
241 // On overflow return the largest valid STAmount.
242 // Very large sums of STAmount are approximations
243 // anyway.
245 }
246 }
247 }
248 });
249 }
250
251 if (!sums.empty())
252 {
253 json::Value j;
254 for (auto const& [k, v] : sums)
255 {
256 j[to_string(k)] = v.getText();
257 }
258 result[jss::obligations] = std::move(j);
259 }
260
261 auto const populateResult = [&result](
263 json::StaticString const& name) {
264 if (!array.empty())
265 {
266 json::Value j;
267 for (auto const& [accId, accBalances] : array)
268 {
269 json::Value balanceArray;
270 for (auto const& balance : accBalances)
271 {
272 json::Value entry;
273 entry[jss::currency] = to_string(balance.get<Issue>().currency);
274 entry[jss::value] = balance.getText();
275 balanceArray.append(std::move(entry));
276 }
277 j[to_string(accId)] = std::move(balanceArray);
278 }
279 result[name] = std::move(j);
280 }
281 };
282
283 populateResult(hotBalances, jss::balances);
284 populateResult(frozenBalances, jss::frozen_balances);
285 populateResult(assets, jss::assets);
286
287 // Add total escrow to the result
288 if (!locked.empty())
289 {
290 json::Value j;
291 for (auto const& [k, v] : locked)
292 {
293 j[to_string(k)] = v.getText();
294 }
295 result[jss::locked] = std::move(j);
296 }
297
298 return result;
299}
300
301} // namespace xrpl
Lightweight wrapper to tag static string.
Definition json_value.h:52
Represents a JSON value.
Definition json_value.h:121
bool isString() const
Value & append(Value const &value)
Append value to array at the end.
bool isArrayOrNull() const
A currency issued by an account.
Definition Issue.h:18
Currency currency
Definition Issue.h:20
static std::optional< PathFindTrustLine > makeItem(AccountID const &accountID, SLE::ConstRef sle)
Definition TrustLine.cpp:39
static constexpr std::uint64_t kMaxValue
Definition STAmount.h:67
static constexpr int kMaxOffset
Definition STAmount.h:62
std::shared_ptr< STLedgerEntry const > const & ConstRef
T contains(T... args)
T empty(T... args)
T insert(T... args)
constexpr Zero kZero
Definition Zero.h:30
TER valid(STTx const &tx, ReadView const &view, AccountID const &src, beast::Journal j)
Keylet account(AccountID const &id) noexcept
AccountID root.
Definition Indexes.cpp:233
Charge const kFeeHeavyBurdenRpc
void injectError(ErrorCodeI code, json::Value &json)
Add or update the json update to reflect the error code.
json::Value invalidFieldError(std::string const &name)
Definition ErrorCodes.h:285
::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.
json::Value missingFieldError(std::string const &name)
Definition ErrorCodes.h:243
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
void forEachItem(ReadView const &view, Keylet const &root, std::function< void(SLE::ConstRef)> const &f)
Iterate all items in the given directory.
@ RpcInvalidHotwallet
Definition ErrorCodes.h:64
@ RpcActNotFound
Definition ErrorCodes.h:53
@ RpcActMalformed
Definition ErrorCodes.h:73
@ RpcInvalidParams
Definition ErrorCodes.h:67
std::optional< AccountID > parseBase58(std::string const &s)
Parse AccountID from checked, base58 string.
std::string toBase58(AccountID const &v)
Convert AccountID to base58 checked string.
Definition AccountID.cpp:95
std::string to_string(BaseUInt< Bits, Tag > const &a)
Definition base_uint.h:658
json::Value rpcError(ErrorCodeI iError)
Definition RPCErr.cpp:13
json::Value doGatewayBalances(rpc::JsonContext &context)
resource::Charge & loadType
Definition Context.h:30
unsigned int apiVersion
Definition Context.h:37
json::Value params
Definition Context.h:51