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