@axis-markets/client 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api-client.js CHANGED
@@ -1,423 +1,490 @@
1
- /**
2
- * Error thrown when the Aggregator API responds with a non-success HTTP status
3
- */
4
- export class AxisApiError extends Error {
5
- /**
6
- * @param {string} message - Error message returned by the API
7
- * @param {number} status - HTTP status code
8
- */
9
- constructor(message, status) {
10
- super(message)
11
- this.name = 'AxisApiError'
12
- this.status = status
13
- }
14
-
15
- /**
16
- * HTTP status code associated with the error
17
- * @type {number}
18
- * @readonly
19
- */
20
- status
21
- }
22
-
23
- /**
24
- * HTTP client for the AXIS Aggregator REST API
25
- */
26
- export class AxisApiClient {
27
- /**
28
- * @param {string} serverUrl - Base URL of the Aggregator server
29
- */
30
- constructor(serverUrl) {
31
- if (!serverUrl || typeof serverUrl !== 'string')
32
- throw new TypeError('Aggregator server URL is required')
33
- //trim trailing slashes to avoid double slashes when building request paths
34
- this.serverUrl = serverUrl.replace(/\/+$/, '')
35
- }
36
-
37
- /**
38
- * Base URL of the Aggregator server
39
- * @type {string}
40
- * @readonly
41
- */
42
- serverUrl
43
-
44
- /**
45
- * Price quote and candidate trade routes for selling a fixed amount of the source asset
46
- * @param {QuoteParams} params - Quote request parameters
47
- * @return {Promise<QuoteResult>} - Best routes ranked by profitability
48
- * @throws {AxisApiError} - If the server is not ready or there is not enough liquidity
49
- */
50
- async quoteSell(params) {
51
- return this.quote(params, 'strict_send')
52
- }
53
-
54
- /**
55
- * Price quote and candidate trade routes for buying a fixed amount of the destination asset
56
- * @param {QuoteParams} params - Quote request parameters
57
- * @return {Promise<QuoteResult>} - Best routes ranked by profitability
58
- * @throws {AxisApiError} - If the server is not ready or there is not enough liquidity
59
- */
60
- async quoteBuy(params) {
61
- return this.quote(params, 'strict_receive')
62
- }
63
-
64
- /**
65
- * Find viable multi-hop paths between two assets, simulate trades on each path, and return the best routes
66
- * @param {QuoteParams} params - Quote request parameters
67
- * @param {'strict_send'|'strict_receive'} direction - Trade direction
68
- * @return {Promise<QuoteResult>}
69
- * @private
70
- */
71
- async quote({sellingAsset, buyingAsset, amount, direct}, direction) {
72
- return this.request('/quote', {sellingAsset, buyingAsset, amount, direction, direct})
73
- }
74
-
75
- /**
76
- * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,
77
- * asks up, so a level price crosses every order in it)
78
- * @param {DepthParams} params - Depth request parameters
79
- * @return {Promise<OrderbookDepth>} - Aggregated bids and asks
80
- */
81
- async getDepth({market, depth, step, limit}) {
82
- return this.request('/depth', {market, depth, step, limit})
83
- }
84
-
85
- /**
86
- * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)
87
- * @param {CandlesParams} params - Candles request parameters
88
- * @return {Promise<Candle[]>} - Time-bucketed candles, max 200 per response
89
- */
90
- async getCandles({market, from, to, resolution, order}) {
91
- return this.request('/candles', {market, from, to, resolution, order})
92
- }
93
-
94
- /**
95
- * 24-hour ticker statistics for every available market
96
- * @return {Promise<Ticker24hResult>} - Aggregated 24h stats per market
97
- */
98
- async getTicker24h() {
99
- return this.request('/ticker/24h')
100
- }
101
-
102
- /**
103
- * List all active markets with pagination
104
- * @param {MarketsParams} [params] - Pagination parameters
105
- * @return {Promise<MarketInfo[]>} - Active markets
106
- */
107
- async getMarkets({cursor, limit} = {}) {
108
- return this.request('/markets', {cursor, limit})
109
- }
110
-
111
- /**
112
- * Contract state tracked by the indexer: frozen switch, configuration and active markets
113
- * @return {Promise<ContractInfo>} - Contract state
114
- */
115
- async getContract() {
116
- return this.request('/contract')
117
- }
118
-
119
- /**
120
- * Retrieve active orders, filterable by owner or asset
121
- * @param {OrdersParams} [params] - Filter parameters
122
- * @return {Promise<ApiOrder[]>} - Active orders matching the filter
123
- */
124
- async getOrders({owner, asset, cursor, limit} = {}) {
125
- return this.request('/order', {owner, asset, cursor, limit})
126
- }
127
-
128
- /**
129
- * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each
130
- * asset they trade
131
- * @param {string} address - Trader address
132
- * @return {Promise<ApiAccount>}
133
- */
134
- async getAccount(address) {
135
- return this.request(`/account/${encodeURIComponent(address)}`)
136
- }
137
-
138
- /**
139
- * Retrieve a single order by ID
140
- * @param {bigint|string|number} id - Order ID
141
- * @return {Promise<ApiOrder>} - Order (throws AxisApiError with status 404 if not found)
142
- */
143
- async getOrder(id) {
144
- return this.request(`/order/${encodeURIComponent(id.toString())}`)
145
- }
146
-
147
- /**
148
- * Retrieve archived/historical orders
149
- * @param {OrderHistoryParams} [params] - Filter parameters
150
- * @return {Promise<ApiOrder[]>} - Archived orders matching the filter
151
- */
152
- async getOrderHistory({owner, pair, cursor, limit} = {}) {
153
- return this.request('/order-history', {owner, pair, cursor, limit})
154
- }
155
-
156
- /**
157
- * Retrieve recent trades
158
- * @param {TradesParams} [params] - Filter parameters
159
- * @return {Promise<ApiTrade[]>} - Recent trades matching the filter
160
- */
161
- async getTrades({trader, pair, cursor, limit} = {}) {
162
- return this.request('/trades', {trader, pair, cursor, limit})
163
- }
164
-
165
- /**
166
- * Execute a GET request against the Aggregator API
167
- * @param {string} path - Relative route path
168
- * @param {object} [query] - Query parameters (undefined/null values skipped, arrays expanded to repeated params)
169
- * @return {Promise<*>} - Parsed JSON response
170
- * @throws {AxisApiError} - If the API responds with a non-success status
171
- * @private
172
- */
173
- async request(path, query) {
174
- let url = this.serverUrl + path
175
- if (query) {
176
- const search = new URLSearchParams()
177
- for (const [key, value] of Object.entries(query)) {
178
- if (value === undefined || value === null)
179
- continue
180
- if (Array.isArray(value)) {
181
- for (const item of value)
182
- search.append(key, item)
183
- } else {
184
- search.append(key, value)
185
- }
186
- }
187
- const qs = search.toString()
188
- if (qs)
189
- url += '?' + qs
190
- }
191
- const response = await fetch(url)
192
- let body
193
- try {
194
- body = await response.json()
195
- } catch (e) {
196
- //non-JSON response (e.g. proxy/gateway error) - fall back to status text
197
- body = null
198
- }
199
- if (!response.ok)
200
- throw new AxisApiError(body?.error || response.statusText, body?.status || response.status)
201
- return body
202
- }
203
- }
204
-
205
- /**
206
- * @typedef {{}} QuoteParams
207
- * @property {string} sellingAsset - Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId)
208
- * @property {string} buyingAsset - Asset to buy (same format as `sellingAsset`)
209
- * @property {string|number} amount - Trade amount in stroops (1 unit = 10,000,000 stroops)
210
- * @property {boolean} [direct] - Restrict to the direct market only (no intermediate-asset routes)
211
- */
212
-
213
- /**
214
- * @typedef {{}} QuoteResult
215
- * @property {string} id - Base58-encoded quote id
216
- * @property {'success'|'unfeasible'|'rejected'} status - Quote status
217
- * @property {'strict_send'|'strict_receive'} direction - Trade direction
218
- * @property {string} sellingAsset - Selling asset contract id
219
- * @property {string} buyingAsset - Buying asset contract id
220
- * @property {number} ledger - Ledger sequence the quote was computed for
221
- * @property {QuotePath[]} paths - Candidate routes ranked by profitability (up to 10)
222
- * @property {string} [error] - Error message (present only if status is not `success`)
223
- */
224
-
225
- /**
226
- * @typedef {{}} QuotePath
227
- * @property {string} sold - Amount sold, in stroops
228
- * @property {string} bought - Amount bought, in stroops
229
- * @property {QuotePathStep[]} path - Ordered list of hops in the route
230
- */
231
-
232
- /**
233
- * @typedef {{}} QuotePathStep
234
- * @property {string} selling - Selling asset contract id at this hop
235
- * @property {string} buying - Buying asset contract id at this hop
236
- * @property {string[]} orders - Maker order IDs matched at this hop
237
- * @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):
238
- * a trade limit at this price crosses every listed order
239
- */
240
-
241
- /**
242
- * @typedef {{}} DepthParams
243
- * @property {string} market - Market identifier `BASE/QUOTE`
244
- * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)
245
- * @property {string} [step] - Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid
246
- * price by default)
247
- * @property {number} [limit] - Price levels per side (default 100, max 500)
248
- */
249
-
250
- /**
251
- * @typedef {{}} OrderbookDepth
252
- * @property {number} ledger - Ledger sequence
253
- * @property {number} timestamp - UNIX timestamp (seconds)
254
- * @property {string|null} step - Price step of the levels (null for an empty book)
255
- * @property {string|null} bestBid - Exact best bid price, before the rounding to levels
256
- * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels
257
- * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price
258
- * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price
259
- */
260
-
261
- /**
262
- * @typedef {{}} CandlesParams
263
- * @property {string} market - Market identifier `BASE/QUOTE`
264
- * @property {number} [from] - Lower boundary (UNIX seconds, default 0)
265
- * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)
266
- * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)
267
- * @property {'asc'|'desc'} [order] - Sort order (default `desc`)
268
- */
269
-
270
- /**
271
- * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`
272
- * @typedef {[number, string, string, string, string, string, string, number]} Candle
273
- */
274
-
275
- /**
276
- * @typedef {{}} Ticker24hResult
277
- * @property {number} ledger - Ledger sequence
278
- * @property {number} timestamp - UNIX timestamp (seconds)
279
- * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending
280
- */
281
-
282
- /**
283
- * @typedef {{}} TickerEntry
284
- * @property {string} symbol - Market symbol `BASE/QUOTE`
285
- * @property {string} openPrice - Opening price 24h ago
286
- * @property {string} highPrice - Highest price in the 24h window
287
- * @property {string} lowPrice - Lowest price in the 24h window
288
- * @property {string} lastPrice - Most recent trade price
289
- * @property {string} volume - 24h base asset volume
290
- * @property {string} quoteVolume - 24h quote asset volume
291
- * @property {number} change - 24h price change (percent)
292
- * @property {string} avgPrice - Volume-weighted average price
293
- * @property {number} trades - 24h trade count
294
- */
295
-
296
- /**
297
- * @typedef {{}} MarketsParams
298
- * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)
299
- * @property {number|string} [limit] - Max markets to return
300
- */
301
-
302
- /**
303
- * @typedef {{}} MarketInfo
304
- * @property {string} baseAsset - Base asset contract id
305
- * @property {string} quoteAsset - Quote asset contract id
306
- * @property {string} cursor - Pagination cursor for this market
307
- * @property {string[]} orderTypes - Supported order types
308
- */
309
-
310
- /**
311
- * @typedef {{}} ContractInfo - Contract state tracked by the indexer
312
- * @property {boolean} frozen - Whether trading is blocked by the safety admin
313
- * @property {ContractInfoConfig} [config] - Contract configuration
314
- * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
315
- */
316
-
317
- /**
318
- * @typedef {{}} ContractInfoConfig
319
- * @property {string} safetyAdmin - Safety admin address
320
- * @property {string} oracle - Price oracle contract address
321
- * @property {string} marketListingFee - Fee token amount burned to open a market
322
- * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)
323
- */
324
-
325
- /**
326
- * @typedef {{}} ContractInfoMarket
327
- * @property {string} a - First market asset
328
- * @property {string} b - Second market asset
329
- * @property {string} created - Creation timestamp (UTC)
330
- * @property {string} refreshed - Last oracle check timestamp (UTC)
331
- */
332
-
333
- /**
334
- * @typedef {{}} OrdersParams
335
- * @property {string} [owner] - Filter by order owner address
336
- * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)
337
- * @property {string|bigint} [cursor] - Pagination cursor (order id)
338
- * @property {number|string} [limit] - Max orders to return
339
- */
340
-
341
- /**
342
- * @typedef {{}} OrderHistoryParams
343
- * @property {string} [owner] - Filter by order owner address
344
- * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
345
- * @property {string|bigint} [cursor] - Pagination cursor (order id)
346
- * @property {number|string} [limit] - Max orders to return
347
- */
348
-
349
- /**
350
- * @typedef {{}} TradesParams
351
- * @property {string} [trader] - Filter by trader address
352
- * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
353
- * @property {string|bigint} [cursor] - Pagination cursor (trade id)
354
- * @property {number|string} [limit] - Max trades to return
355
- */
356
-
357
- /**
358
- * @typedef {{}} ApiOrder - Serialized order returned by the API
359
- * @property {string} id - Order ID (decimal u128)
360
- * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)
361
- * @property {string} buying - Buying asset contract id
362
- * @property {string} selling - Selling asset contract id
363
- * @property {string} price - Order price
364
- * @property {string} rprice - Rational price representation
365
- * @property {string} quote - Selling amount at creation
366
- * @property {string} amount - Amount left to sell
367
- * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing
368
- * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing
369
- * @property {string} owner - Maker address
370
- * @property {string} [expires] - Expiration timestamp (UTC)
371
- * @property {string} [created] - Creation timestamp (UTC)
372
- * @property {string} [updated] - Last update timestamp (UTC)
373
- * @property {string} [cursor] - Pagination cursor
374
- */
375
-
376
- /**
377
- * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset
378
- * @property {string} balance - Token balance
379
- * @property {string} allowance - Allowance granted to the AXIS contract
380
- * @property {number} liveUntil - Ledger sequence the allowance lives until
381
- * @property {boolean} authorized - Whether the maker can send and receive the token
382
- * @property {string} [updated] - Last load timestamp (UTC)
383
- * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it
384
- */
385
-
386
- /**
387
- * @typedef {{}} ApiBacking - Tracked backing of an account in a token
388
- * @property {string} owner - Account address
389
- * @property {string} asset - Token contract id
390
- * @property {string} balance - Token balance
391
- * @property {string} allowance - Allowance granted to the AXIS contract
392
- * @property {number} liveUntil - Ledger sequence the allowance lives until
393
- * @property {boolean} authorized - Whether the account can send and receive the token
394
- * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired
395
- * @property {string} [updated] - Last load timestamp (UTC)
396
- * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)
397
- * @property {boolean} [pending] - A reload confirming the latest event is still due
398
- */
399
-
400
- /**
401
- * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset
402
- * @property {string} address - Trader address
403
- * @property {number} ledger - Last processed ledger
404
- * @property {ApiOrder[]} orders - Live orders, oldest first
405
- * @property {Object<string, ApiBacking>} backing - Backing by token contract id
406
- */
407
-
408
- /**
409
- * @typedef {{}} ApiTrade - Serialized trade returned by the API
410
- * @property {'trade'} type - Record type
411
- * @property {string} id - Trade ID
412
- * @property {string} order - Matched order ID
413
- * @property {string} taker - Taker account address
414
- * @property {string} maker - Maker account address
415
- * @property {string} soldAsset - Sold asset contract id
416
- * @property {string} boughtAsset - Bought asset contract id
417
- * @property {string} sold - Sold tokens amount
418
- * @property {string} bought - Bought tokens amount
419
- * @property {string} [left] - Order amount left after the fill
420
- * @property {string} price - Approximate trade price
421
- * @property {string} [cursor] - Pagination cursor
422
- * @property {string} timestamp - Trade timestamp (UTC)
423
- */
1
+ /**
2
+ * Error thrown when the AXIS API responds with a non-success HTTP status
3
+ */
4
+ export class AxisApiError extends Error {
5
+ /**
6
+ * @param {string} message - Error message returned by the API
7
+ * @param {number} status - HTTP status code
8
+ */
9
+ constructor(message, status) {
10
+ super(message)
11
+ this.name = 'AxisApiError'
12
+ this.status = status
13
+ }
14
+
15
+ /**
16
+ * HTTP status code associated with the error
17
+ * @type {number}
18
+ * @readonly
19
+ */
20
+ status
21
+ }
22
+
23
+ /**
24
+ * HTTP client for the AXIS REST API
25
+ */
26
+ export class AxisApiClient {
27
+ /**
28
+ * @param {string} serverUrl - Base URL of the AXIS API server
29
+ */
30
+ constructor(serverUrl) {
31
+ if (!serverUrl || typeof serverUrl !== 'string')
32
+ throw new TypeError('AXIS API server URL is required')
33
+ //trim trailing slashes to avoid double slashes when building request paths
34
+ this.serverUrl = serverUrl.replace(/\/+$/, '')
35
+ }
36
+
37
+ /**
38
+ * Base URL of the AXIS API server
39
+ * @type {string}
40
+ * @readonly
41
+ */
42
+ serverUrl
43
+
44
+ /**
45
+ * Price quote and candidate trade routes for selling a fixed amount of the source asset
46
+ * @param {QuoteParams} params - Quote request parameters
47
+ * @return {Promise<QuoteResult>} - Best routes ranked by profitability
48
+ * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough
49
+ * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`
50
+ */
51
+ async quoteSell(params) {
52
+ return this.quote(params, 'strict_send')
53
+ }
54
+
55
+ /**
56
+ * Price quote and candidate trade routes for buying a fixed amount of the destination asset
57
+ * @param {QuoteParams} params - Quote request parameters
58
+ * @return {Promise<QuoteResult>} - Best routes ranked by profitability
59
+ * @throws {AxisApiError} - 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough
60
+ * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`
61
+ */
62
+ async quoteBuy(params) {
63
+ return this.quote(params, 'strict_receive')
64
+ }
65
+
66
+ /**
67
+ * Find viable multi-hop paths between two assets, simulate trades on each path, and return the best routes
68
+ * @param {QuoteParams} params - Quote request parameters
69
+ * @param {'strict_send'|'strict_receive'} direction - Trade direction
70
+ * @return {Promise<QuoteResult>}
71
+ * @private
72
+ */
73
+ async quote({sellingAsset, buyingAsset, amount, direct, maxPrice}, direction) {
74
+ return this.request('/quote', {sellingAsset, buyingAsset, amount, direction, direct, maxPrice: maxPrice?.toString()})
75
+ }
76
+
77
+ /**
78
+ * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,
79
+ * asks up, so a level price crosses every order in it)
80
+ * @param {DepthParams} params - Depth request parameters
81
+ * @return {Promise<OrderbookDepth>} - Aggregated bids and asks
82
+ */
83
+ async getDepth({market, depth, step, limit}) {
84
+ return this.request('/depth', {market, depth, step, limit})
85
+ }
86
+
87
+ /**
88
+ * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)
89
+ * @param {CandlesParams} params - Candles request parameters
90
+ * @return {Promise<Candle[]>} - Time-bucketed candles, max 200 per response
91
+ */
92
+ async getCandles({market, from, to, resolution, order}) {
93
+ return this.request('/candles', {market, from, to, resolution, order})
94
+ }
95
+
96
+ /**
97
+ * 24-hour ticker statistics for every available market
98
+ * @return {Promise<Ticker24hResult>} - Aggregated 24h stats per market
99
+ */
100
+ async getTicker24h() {
101
+ return this.request('/ticker/24h')
102
+ }
103
+
104
+ /**
105
+ * List all active markets with pagination
106
+ * @param {MarketsParams} [params] - Pagination parameters
107
+ * @return {Promise<MarketInfo[]>} - Active markets
108
+ */
109
+ async getMarkets({cursor, limit} = {}) {
110
+ return this.request('/markets', {cursor, limit})
111
+ }
112
+
113
+ /**
114
+ * Contract state tracked by the indexer: frozen switch, configuration and active markets
115
+ * @return {Promise<ContractInfo>} - Contract state
116
+ */
117
+ async getContract() {
118
+ return this.request('/contract')
119
+ }
120
+
121
+ /**
122
+ * Retrieve active orders, filterable by owner or asset
123
+ * @param {OrdersParams} [params] - Filter parameters
124
+ * @return {Promise<ApiOrder[]>} - Active orders matching the filter
125
+ */
126
+ async getOrders({owner, asset, cursor, limit} = {}) {
127
+ return this.request('/order', {owner, asset, cursor, limit})
128
+ }
129
+
130
+ /**
131
+ * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each
132
+ * asset they trade
133
+ * @param {string} address - Trader address
134
+ * @return {Promise<ApiAccount>}
135
+ */
136
+ async getAccount(address) {
137
+ return this.request(`/account/${encodeURIComponent(address)}`)
138
+ }
139
+
140
+ /**
141
+ * Retrieve a single order by ID
142
+ * @param {bigint|string|number} id - Order ID
143
+ * @return {Promise<ApiOrder>} - Order (throws AxisApiError with status 404 if not found)
144
+ */
145
+ async getOrder(id) {
146
+ return this.request(`/order/${encodeURIComponent(id.toString())}`)
147
+ }
148
+
149
+ /**
150
+ * Retrieve archived/historical orders
151
+ * @param {OrderHistoryParams} [params] - Filter parameters
152
+ * @return {Promise<ApiOrder[]>} - Archived orders matching the filter
153
+ */
154
+ async getOrderHistory({owner, pair, cursor, limit} = {}) {
155
+ return this.request('/order-history', {owner, pair, cursor, limit})
156
+ }
157
+
158
+ /**
159
+ * Retrieve recent trades and swaps, newest first
160
+ * @param {TradesParams} [params] - Filter parameters
161
+ * @return {Promise<Array<ApiTrade|ApiSwap>>} - Recent trades and swaps matching the filter (told apart by `type`)
162
+ */
163
+ async getTrades({trader, pair, cursor, limit} = {}) {
164
+ return this.request('/trades', {trader, pair, cursor, limit})
165
+ }
166
+
167
+ /**
168
+ * Failed AXIS calls, newest first (diagnostics: a failure changes no state, and a record never blames a party, see
169
+ * {@link ApiFailure})
170
+ * @param {FailuresParams} [params] - Filter parameters
171
+ * @return {Promise<ApiFailure[]>}
172
+ */
173
+ async getFailures({account, fn, cursor, limit} = {}) {
174
+ return this.request('/failures', {account, fn, cursor, limit})
175
+ }
176
+
177
+ /**
178
+ * Execute a GET request against the AXIS API
179
+ * @param {string} path - Relative route path
180
+ * @param {object} [query] - Query parameters (undefined/null values skipped, arrays expanded to repeated params)
181
+ * @return {Promise<*>} - Parsed JSON response
182
+ * @throws {AxisApiError} - If the API responds with a non-success status
183
+ * @private
184
+ */
185
+ async request(path, query) {
186
+ let url = this.serverUrl + path
187
+ if (query) {
188
+ const search = new URLSearchParams()
189
+ for (const [key, value] of Object.entries(query)) {
190
+ if (value === undefined || value === null)
191
+ continue
192
+ if (Array.isArray(value)) {
193
+ for (const item of value)
194
+ search.append(key, item)
195
+ } else {
196
+ search.append(key, value)
197
+ }
198
+ }
199
+ const qs = search.toString()
200
+ if (qs)
201
+ url += '?' + qs
202
+ }
203
+ const response = await fetch(url)
204
+ let body
205
+ try {
206
+ body = await response.json()
207
+ } catch (e) {
208
+ //non-JSON response (e.g. proxy/gateway error) - fall back to status text
209
+ body = null
210
+ }
211
+ if (!response.ok)
212
+ throw new AxisApiError(body?.error || response.statusText, body?.status || response.status)
213
+ return body
214
+ }
215
+ }
216
+
217
+ /**
218
+ * @typedef {{}} QuoteParams
219
+ * @property {string} sellingAsset - Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId)
220
+ * @property {string} buyingAsset - Asset to buy (same format as `sellingAsset`)
221
+ * @property {string|number} amount - Trade amount in stroops (1 unit = 10,000,000 stroops)
222
+ * @property {boolean} [direct] - Restrict to the direct market only (no intermediate-asset routes)
223
+ * @property {bigint|string} [maxPrice] - Highest maker price to cross (requires `direct`), in the units of a hop
224
+ * `worstPrice`: `sellingAsset` per unit of `buyingAsset`, scaled by 10^18. Quotes the crossing of a limit order: orders
225
+ * priced above it are left out and the route may trade less than `amount`
226
+ */
227
+
228
+ /**
229
+ * @typedef {{}} QuoteResult
230
+ * @property {string} id - Base58-encoded quote id
231
+ * @property {'success'|'unfeasible'|'rejected'} status - Quote status
232
+ * @property {'strict_send'|'strict_receive'} direction - Trade direction
233
+ * @property {string} sellingAsset - Selling asset contract id
234
+ * @property {string} buyingAsset - Buying asset contract id
235
+ * @property {number} ledger - Ledger sequence the quote was computed for
236
+ * @property {QuotePath[]} paths - Candidate routes ranked by profitability (up to 10)
237
+ * @property {string} [error] - Error message (present only if status is not `success`)
238
+ */
239
+
240
+ /**
241
+ * @typedef {{}} QuotePath
242
+ * @property {string} sold - Amount sold, in stroops
243
+ * @property {string} bought - Amount bought, in stroops
244
+ * @property {QuotePathStep[]} path - Ordered list of hops in the route
245
+ */
246
+
247
+ /**
248
+ * @typedef {{}} QuotePathStep
249
+ * @property {string} selling - Selling asset contract id at this hop
250
+ * @property {string} buying - Buying asset contract id at this hop
251
+ * @property {string[]} orders - Maker order IDs matched at this hop
252
+ * @property {string} [worstPrice] - Highest price among the matched orders (maker `buying` per `selling`, 18 decimals):
253
+ * a trade limit at this price crosses every listed order
254
+ */
255
+
256
+ /**
257
+ * @typedef {{}} DepthParams
258
+ * @property {string} market - Market identifier `BASE/QUOTE`
259
+ * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)
260
+ * @property {string} [step] - Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid
261
+ * price by default)
262
+ * @property {number} [limit] - Price levels per side (default 100, max 500)
263
+ */
264
+
265
+ /**
266
+ * @typedef {{}} OrderbookDepth
267
+ * @property {number} ledger - Ledger sequence
268
+ * @property {number} timestamp - UNIX timestamp (seconds)
269
+ * @property {string|null} step - Price step of the levels (null for an empty book)
270
+ * @property {string|null} bestBid - Exact best bid price, before the rounding to levels
271
+ * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels
272
+ * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price
273
+ * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price
274
+ */
275
+
276
+ /**
277
+ * @typedef {{}} CandlesParams
278
+ * @property {string} market - Market identifier `BASE/QUOTE`
279
+ * @property {number} [from] - Lower boundary (UNIX seconds, default 0)
280
+ * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)
281
+ * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)
282
+ * @property {'asc'|'desc'} [order] - Sort order (default `desc`)
283
+ */
284
+
285
+ /**
286
+ * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`
287
+ * @typedef {[number, string, string, string, string, string, string, number]} Candle
288
+ */
289
+
290
+ /**
291
+ * @typedef {{}} Ticker24hResult
292
+ * @property {number} ledger - Ledger sequence
293
+ * @property {number} timestamp - UNIX timestamp (seconds)
294
+ * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending
295
+ */
296
+
297
+ /**
298
+ * @typedef {{}} TickerEntry
299
+ * @property {string} symbol - Market symbol `BASE/QUOTE`
300
+ * @property {string} openPrice - Opening price 24h ago
301
+ * @property {string} highPrice - Highest price in the 24h window
302
+ * @property {string} lowPrice - Lowest price in the 24h window
303
+ * @property {string} lastPrice - Most recent trade price
304
+ * @property {string} volume - 24h base asset volume
305
+ * @property {string} quoteVolume - 24h quote asset volume
306
+ * @property {number} change - 24h price change (percent)
307
+ * @property {string} avgPrice - Volume-weighted average price
308
+ * @property {number} trades - 24h trade count
309
+ */
310
+
311
+ /**
312
+ * @typedef {{}} MarketsParams
313
+ * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)
314
+ * @property {number|string} [limit] - Max markets to return
315
+ */
316
+
317
+ /**
318
+ * @typedef {{}} MarketInfo
319
+ * @property {string} baseAsset - Base asset contract id
320
+ * @property {string} quoteAsset - Quote asset contract id
321
+ * @property {string} cursor - Pagination cursor for this market
322
+ * @property {string[]} orderTypes - Supported order types
323
+ */
324
+
325
+ /**
326
+ * @typedef {{}} ContractInfo - Contract state tracked by the indexer
327
+ * @property {boolean} frozen - Whether trading is blocked by the safety admin
328
+ * @property {ContractInfoConfig} [config] - Contract configuration
329
+ * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
330
+ */
331
+
332
+ /**
333
+ * @typedef {{}} ContractInfoConfig
334
+ * @property {string} safetyAdmin - Safety admin address
335
+ * @property {string} oracle - Price oracle contract address
336
+ * @property {number} [listingMinDays] - Days of price feeds a new market must buy (0 opens markets without a fee)
337
+ * @property {string} marketListingFee - Oracle fee tokens a market creator pays to provision the price feeds
338
+ * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)
339
+ * @property {number} [ledgerTime] - Expected ledger close time in seconds
340
+ */
341
+
342
+ /**
343
+ * @typedef {{}} ContractInfoMarket
344
+ * @property {string} base - Base market asset, the first of the pair in canonical order
345
+ * @property {string} quote - Quote market asset, the second of the pair in canonical order
346
+ * @property {string} created - Creation timestamp (UTC)
347
+ * @property {string} refreshed - Last oracle check timestamp (UTC)
348
+ */
349
+
350
+ /**
351
+ * @typedef {{}} OrdersParams
352
+ * @property {string} [owner] - Filter by order owner address
353
+ * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)
354
+ * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
355
+ * @property {number|string} [limit] - Max orders to return
356
+ */
357
+
358
+ /**
359
+ * @typedef {{}} OrderHistoryParams
360
+ * @property {string} [owner] - Filter by order owner address
361
+ * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
362
+ * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
363
+ * @property {number|string} [limit] - Max orders to return
364
+ */
365
+
366
+ /**
367
+ * @typedef {{}} TradesParams
368
+ * @property {string} [trader] - Filter by trader address
369
+ * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
370
+ * @property {string|bigint} [cursor] - `cursor` of the last record received (the trade or swap id)
371
+ * @property {number|string} [limit] - Max trades to return
372
+ */
373
+
374
+ /**
375
+ * @typedef {{}} FailuresParams
376
+ * @property {string} [account] - Caller of the failed transaction, or a party of the failed transfer
377
+ * @property {string} [fn] - Contract function (`trade`, `swap`, `crossfill`, `update`, ...)
378
+ * @property {string|bigint} [cursor] - `cursor` of the last record received
379
+ * @property {number|string} [limit] - Max records to return (20 by default, at most 500)
380
+ */
381
+
382
+ /**
383
+ * @typedef {{}} ApiFailure - Failed AXIS call (made by the transaction or through another contract, the transaction failed
384
+ * or a calling contract caught the failure). It changes no state and blames no party:
385
+ * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be
386
+ * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller
387
+ * @property {'failure'} type - Record type
388
+ * @property {string} id - Record id (position of the transaction plus the index of the failed call)
389
+ * @property {string} txHash - Transaction hash
390
+ * @property {number} ledger - Ledger sequence
391
+ * @property {string} timestamp - Ledger close time (UTC)
392
+ * @property {string} fn - Contract function called
393
+ * @property {string} caller - The `trader` or `sponsor` argument, the transaction source for other functions
394
+ * @property {string[]} orders - Maker order ids listed by the call
395
+ * @property {string} [takerOrder] - Taker order id of a `crossfill`
396
+ * @property {string} result - Operation result code
397
+ * @property {boolean} [caught] - The transaction succeeded: a calling contract caught the failed AXIS call
398
+ * @property {'contract'|'transfer'|'resources'|'auth'|'unknown'} reason - `contract`: a contract error (`error`),
399
+ * `transfer`: a token transfer failed (`transfer`, either side may be at fault), `resources`: a resource limit, the
400
+ * refundable fee or an archived entry, `auth`: an authorization failure, `unknown`: no diagnostic events
401
+ * @property {{contract: string|null, code: number, name?: string}} [error] - Contract error that failed the call
402
+ * @property {{token: string, fn: string, from: string, to: string, amount: string}} [transfer] - Token transfer that failed
403
+ * @property {string} cursor - Pagination cursor
404
+ */
405
+
406
+ /**
407
+ * @typedef {{}} ApiOrder - Serialized order returned by the API
408
+ * @property {string} id - Order ID (decimal u128)
409
+ * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)
410
+ * @property {string} buying - Buying asset contract id
411
+ * @property {string} selling - Selling asset contract id
412
+ * @property {string} price - Order price
413
+ * @property {string} rprice - Rational price representation
414
+ * @property {string} quote - Selling amount at creation
415
+ * @property {string} amount - Amount left to sell
416
+ * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing
417
+ * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing
418
+ * @property {string} owner - Maker address
419
+ * @property {string} [expires] - Expiration timestamp (UTC)
420
+ * @property {string} [created] - Creation timestamp (UTC)
421
+ * @property {string} [updated] - Last update timestamp (UTC)
422
+ * @property {string} [cursor] - Pagination cursor
423
+ */
424
+
425
+ /**
426
+ * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset
427
+ * @property {string} balance - Token balance
428
+ * @property {string} allowance - Allowance granted to the AXIS contract
429
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
430
+ * @property {boolean} authorized - Whether the maker can send and receive the token
431
+ * @property {string} [updated] - Last load timestamp (UTC)
432
+ * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it
433
+ */
434
+
435
+ /**
436
+ * @typedef {{}} ApiBacking - Tracked backing of an account in a token
437
+ * @property {string} owner - Account address
438
+ * @property {string} asset - Token contract id
439
+ * @property {string} balance - Token balance
440
+ * @property {string} allowance - Allowance granted to the AXIS contract
441
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
442
+ * @property {boolean} authorized - Whether the account can send and receive the token
443
+ * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired
444
+ * @property {string} [headroom] - Amount the account can still receive (trustline limit minus balance and buying
445
+ * liabilities), omitted when unlimited or unknown
446
+ * @property {string} [updated] - Last load timestamp (UTC)
447
+ * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)
448
+ * @property {boolean} [pending] - A reload confirming the latest event is still due
449
+ */
450
+
451
+ /**
452
+ * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset
453
+ * @property {string} address - Trader address
454
+ * @property {number} ledger - Last processed ledger
455
+ * @property {ApiOrder[]} orders - Live orders, oldest first
456
+ * @property {Object<string, ApiBacking>} backing - Backing by token contract id
457
+ */
458
+
459
+ /**
460
+ * @typedef {{}} ApiSwap - Serialized swap returned by the API, one per `swap` call
461
+ * @property {'swap'} type - Record type
462
+ * @property {string} id - Swap ID
463
+ * @property {string} trader - Trader address
464
+ * @property {string} soldAsset - Sold asset contract id
465
+ * @property {string} boughtAsset - Bought asset contract id
466
+ * @property {string} sold - Sold tokens amount
467
+ * @property {string} bought - Bought tokens amount
468
+ * @property {string} price - Approximate swap price
469
+ * @property {string} cursor - Pagination cursor
470
+ * @property {string} timestamp - Swap timestamp (UTC)
471
+ */
472
+
473
+ /**
474
+ * @typedef {{}} ApiTrade - Serialized trade returned by the API
475
+ * @property {'trade'} type - Record type
476
+ * @property {string} id - Trade ID
477
+ * @property {string} order - Matched order ID
478
+ * @property {string} taker - Taker account address
479
+ * @property {string} maker - Maker account address
480
+ * @property {string} soldAsset - Sold asset contract id
481
+ * @property {string} boughtAsset - Bought asset contract id
482
+ * @property {string} sold - Sold tokens amount
483
+ * @property {string} bought - Bought tokens amount
484
+ * @property {string} [left] - Order amount left after the fill
485
+ * @property {boolean} [crossfill] - The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the
486
+ * amounts mirror the makers' fills of the same call (left out of candles and volume)
487
+ * @property {string} price - Approximate trade price
488
+ * @property {string} [cursor] - Pagination cursor
489
+ * @property {string} timestamp - Trade timestamp (UTC)
490
+ */