@axis-markets/client 0.9.3 → 0.9.4

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,506 +1,506 @@
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 to pass to the contract: the orders the quote fills, followed on a
252
- * direct route by spare orders the contract reaches only when it passes over one of them (at most 19 in all)
253
- * @property {string} [worstPrice] - Highest price among the orders the quote fills (maker `buying` per `selling`, 18
254
- * decimals): a trade limit at this price crosses them all. Spares are priced at or below it, except in a `maxPrice`
255
- * crossing, where they reach up to `maxPrice`
256
- */
257
-
258
- /**
259
- * @typedef {{}} DepthParams
260
- * @property {string} market - Market identifier `BASE/QUOTE`
261
- * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)
262
- * @property {string} [step] - Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid
263
- * price by default)
264
- * @property {number} [limit] - Price levels per side (default 100, max 500)
265
- */
266
-
267
- /**
268
- * @typedef {{}} OrderbookDepth
269
- * @property {number} ledger - Ledger sequence
270
- * @property {number} timestamp - UNIX timestamp (seconds)
271
- * @property {string|null} step - Price step of the levels (null for an empty book)
272
- * @property {string|null} bestBid - Exact best bid price, before the rounding to levels
273
- * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels
274
- * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price
275
- * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price
276
- */
277
-
278
- /**
279
- * @typedef {{}} CandlesParams
280
- * @property {string} market - Market identifier `BASE/QUOTE`
281
- * @property {number} [from] - Lower boundary (UNIX seconds, default 0)
282
- * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)
283
- * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)
284
- * @property {'asc'|'desc'} [order] - Sort order (default `desc`)
285
- */
286
-
287
- /**
288
- * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`
289
- * @typedef {[number, string, string, string, string, string, string, number]} Candle
290
- */
291
-
292
- /**
293
- * @typedef {{}} Ticker24hResult
294
- * @property {number} ledger - Ledger sequence
295
- * @property {number} timestamp - UNIX timestamp (seconds)
296
- * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending
297
- */
298
-
299
- /**
300
- * @typedef {{}} TickerEntry
301
- * @property {string} symbol - Market symbol `BASE/QUOTE`
302
- * @property {string} openPrice - Opening price 24h ago
303
- * @property {string} highPrice - Highest price in the 24h window
304
- * @property {string} lowPrice - Lowest price in the 24h window
305
- * @property {string} lastPrice - Most recent trade price
306
- * @property {string} volume - 24h base asset volume
307
- * @property {string} quoteVolume - 24h quote asset volume
308
- * @property {number} change - 24h price change (percent)
309
- * @property {string} avgPrice - Volume-weighted average price
310
- * @property {number} trades - 24h trade count
311
- */
312
-
313
- /**
314
- * @typedef {{}} MarketsParams
315
- * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)
316
- * @property {number|string} [limit] - Max markets to return
317
- */
318
-
319
- /**
320
- * @typedef {{}} MarketInfo
321
- * @property {string} baseAsset - Base asset contract id
322
- * @property {string} quoteAsset - Quote asset contract id
323
- * @property {string} cursor - Pagination cursor for this market
324
- * @property {string[]} orderTypes - Supported order types
325
- */
326
-
327
- /**
328
- * @typedef {{}} ContractInfo - Contract state tracked by the indexer
329
- * @property {string} address - AXIS contract address
330
- * @property {'mainnet'|'testnet'} [network] - Stellar network of the contract
331
- * @property {boolean} frozen - Whether trading is blocked by the safety admin
332
- * @property {ContractInfoConfig} [config] - Contract configuration
333
- * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
334
- * @property {ContractInfoAsset[]} [assets] - Metadata of the market tokens
335
- */
336
-
337
- /**
338
- * @typedef {{}} ContractInfoAsset - Market token metadata (only `contract` until the AXIS API resolves it)
339
- * @property {string} contract - Token contract address
340
- * @property {string} [code] - Asset code (token symbol)
341
- * @property {string} [issuer] - Issuer account of a classic asset, `native` for XLM, absent for a SEP-41 token
342
- * @property {number} [decimals] - Token decimals
343
- * @property {string} [name] - Asset name
344
- * @property {string} [domain] - Home domain of the issuer
345
- * @property {string} [icon] - Icon URL
346
- */
347
-
348
- /**
349
- * @typedef {{}} ContractInfoConfig
350
- * @property {string} safetyAdmin - Safety admin address
351
- * @property {string} oracle - Price oracle contract address
352
- * @property {number} [listingMinDays] - Days of price feeds a new market must buy (0 opens markets without a fee)
353
- * @property {string} marketListingFee - Oracle fee tokens a market creator pays to provision the price feeds
354
- * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)
355
- * @property {number} [ledgerTime] - Expected ledger close time in seconds
356
- */
357
-
358
- /**
359
- * @typedef {{}} ContractInfoMarket
360
- * @property {string} base - Base market asset, the first of the pair in canonical order
361
- * @property {string} quote - Quote market asset, the second of the pair in canonical order
362
- * @property {string} created - Creation timestamp (UTC)
363
- * @property {string} refreshed - Last oracle check timestamp (UTC)
364
- */
365
-
366
- /**
367
- * @typedef {{}} OrdersParams
368
- * @property {string} [owner] - Filter by order owner address
369
- * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)
370
- * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
371
- * @property {number|string} [limit] - Max orders to return
372
- */
373
-
374
- /**
375
- * @typedef {{}} OrderHistoryParams
376
- * @property {string} [owner] - Filter by order owner address
377
- * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
378
- * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
379
- * @property {number|string} [limit] - Max orders to return
380
- */
381
-
382
- /**
383
- * @typedef {{}} TradesParams
384
- * @property {string} [trader] - Filter by trader address
385
- * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
386
- * @property {string|bigint} [cursor] - `cursor` of the last record received (the trade or swap id)
387
- * @property {number|string} [limit] - Max trades to return
388
- */
389
-
390
- /**
391
- * @typedef {{}} FailuresParams
392
- * @property {string} [account] - Caller of the failed transaction, or a party of the failed transfer
393
- * @property {string} [fn] - Contract function (`trade`, `swap`, `crossfill`, `update`, ...)
394
- * @property {string|bigint} [cursor] - `cursor` of the last record received
395
- * @property {number|string} [limit] - Max records to return (20 by default, at most 500)
396
- */
397
-
398
- /**
399
- * @typedef {{}} ApiFailure - Failed AXIS call (made by the transaction or through another contract, the transaction failed
400
- * or a calling contract caught the failure). It changes no state and blames no party:
401
- * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be
402
- * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller
403
- * @property {'failure'} type - Record type
404
- * @property {string} id - Record id (position of the transaction plus the index of the failed call)
405
- * @property {string} txHash - Transaction hash
406
- * @property {number} ledger - Ledger sequence
407
- * @property {string} timestamp - Ledger close time (UTC)
408
- * @property {string} fn - Contract function called
409
- * @property {string} caller - The `trader` or `sponsor` argument, the transaction source for other functions
410
- * @property {string[]} orders - Maker order ids listed by the call
411
- * @property {string} [takerOrder] - Taker order id of a `crossfill`
412
- * @property {string} result - Operation result code
413
- * @property {boolean} [caught] - The transaction succeeded: a calling contract caught the failed AXIS call
414
- * @property {'contract'|'transfer'|'resources'|'auth'|'unknown'} reason - `contract`: a contract error (`error`),
415
- * `transfer`: a token transfer failed (`transfer`, either side may be at fault), `resources`: a resource limit, the
416
- * refundable fee or an archived entry, `auth`: an authorization failure, `unknown`: no diagnostic events
417
- * @property {{contract: string|null, code: number, name?: string}} [error] - Contract error that failed the call
418
- * @property {{token: string, fn: string, from: string, to: string, amount: string}} [transfer] - Token transfer that failed
419
- * @property {string} cursor - Pagination cursor
420
- */
421
-
422
- /**
423
- * @typedef {{}} ApiOrder - Serialized order returned by the API
424
- * @property {string} id - Order ID (decimal u128)
425
- * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)
426
- * @property {string} buying - Buying asset contract id
427
- * @property {string} selling - Selling asset contract id
428
- * @property {string} price - Order price
429
- * @property {string} rprice - Rational price representation
430
- * @property {string} quote - Selling amount at creation
431
- * @property {string} amount - Amount left to sell
432
- * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing
433
- * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing
434
- * @property {string} owner - Maker address
435
- * @property {string} [expires] - Expiration timestamp (UTC)
436
- * @property {string} [created] - Creation timestamp (UTC)
437
- * @property {string} [updated] - Last update timestamp (UTC)
438
- * @property {string} [cursor] - Pagination cursor
439
- */
440
-
441
- /**
442
- * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset
443
- * @property {string} balance - Token balance
444
- * @property {string} allowance - Allowance granted to the AXIS contract
445
- * @property {number} liveUntil - Ledger sequence the allowance lives until
446
- * @property {boolean} authorized - Whether the maker can send and receive the token
447
- * @property {string} [updated] - Last load timestamp (UTC)
448
- * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it
449
- */
450
-
451
- /**
452
- * @typedef {{}} ApiBacking - Tracked backing of an account in a token
453
- * @property {string} owner - Account address
454
- * @property {string} asset - Token contract id
455
- * @property {string} balance - Token balance
456
- * @property {string} allowance - Allowance granted to the AXIS contract
457
- * @property {number} liveUntil - Ledger sequence the allowance lives until
458
- * @property {boolean} authorized - Whether the account can send and receive the token
459
- * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired
460
- * @property {string} [headroom] - Amount the account can still receive (trustline limit minus balance and buying
461
- * liabilities), omitted when unlimited or unknown
462
- * @property {string} [updated] - Last load timestamp (UTC)
463
- * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)
464
- * @property {boolean} [pending] - A reload confirming the latest event is still due
465
- */
466
-
467
- /**
468
- * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset
469
- * @property {string} address - Trader address
470
- * @property {number} ledger - Last processed ledger
471
- * @property {ApiOrder[]} orders - Live orders, oldest first
472
- * @property {Object<string, ApiBacking>} backing - Backing by token contract id
473
- */
474
-
475
- /**
476
- * @typedef {{}} ApiSwap - Serialized swap returned by the API, one per `swap` call
477
- * @property {'swap'} type - Record type
478
- * @property {string} id - Swap ID
479
- * @property {string} trader - Trader 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} price - Approximate swap price
485
- * @property {string} cursor - Pagination cursor
486
- * @property {string} timestamp - Swap timestamp (UTC)
487
- */
488
-
489
- /**
490
- * @typedef {{}} ApiTrade - Serialized trade returned by the API
491
- * @property {'trade'} type - Record type
492
- * @property {string} id - Trade ID
493
- * @property {string} order - Matched order ID
494
- * @property {string} taker - Taker account address
495
- * @property {string} maker - Maker account address
496
- * @property {string} soldAsset - Sold asset contract id
497
- * @property {string} boughtAsset - Bought asset contract id
498
- * @property {string} sold - Sold tokens amount
499
- * @property {string} bought - Bought tokens amount
500
- * @property {string} [left] - Order amount left after the fill
501
- * @property {boolean} [crossfill] - The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the
502
- * amounts mirror the makers' fills of the same call (left out of candles and volume)
503
- * @property {string} price - Approximate trade price
504
- * @property {string} [cursor] - Pagination cursor
505
- * @property {string} timestamp - Trade timestamp (UTC)
506
- */
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 to pass to the contract: the orders the quote fills, followed on a
252
+ * direct route by spare orders the contract reaches only when it passes over one of them (at most 19 in all)
253
+ * @property {string} [worstPrice] - Highest price among the orders the quote fills (maker `buying` per `selling`, 18
254
+ * decimals): a trade limit at this price crosses them all. Spares are priced at or below it, except in a `maxPrice`
255
+ * crossing, where they reach up to `maxPrice`
256
+ */
257
+
258
+ /**
259
+ * @typedef {{}} DepthParams
260
+ * @property {string} market - Market identifier `BASE/QUOTE`
261
+ * @property {number} [depth] - Percentage band (±) around the center price (0 < depth ≤ 100, default 20)
262
+ * @property {string} [step] - Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid
263
+ * price by default)
264
+ * @property {number} [limit] - Price levels per side (default 100, max 500)
265
+ */
266
+
267
+ /**
268
+ * @typedef {{}} OrderbookDepth
269
+ * @property {number} ledger - Ledger sequence
270
+ * @property {number} timestamp - UNIX timestamp (seconds)
271
+ * @property {string|null} step - Price step of the levels (null for an empty book)
272
+ * @property {string|null} bestBid - Exact best bid price, before the rounding to levels
273
+ * @property {string|null} bestAsk - Exact best ask price, before the rounding to levels
274
+ * @property {Array<[string, string]>} bids - `[price, quantity]` pairs sorted descending by price
275
+ * @property {Array<[string, string]>} asks - `[price, quantity]` pairs sorted ascending by price
276
+ */
277
+
278
+ /**
279
+ * @typedef {{}} CandlesParams
280
+ * @property {string} market - Market identifier `BASE/QUOTE`
281
+ * @property {number} [from] - Lower boundary (UNIX seconds, default 0)
282
+ * @property {number} [to] - Upper boundary (UNIX seconds, defaults to `from + resolution * 200`)
283
+ * @property {number|string} [resolution] - Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`)
284
+ * @property {'asc'|'desc'} [order] - Sort order (default `desc`)
285
+ */
286
+
287
+ /**
288
+ * OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]`
289
+ * @typedef {[number, string, string, string, string, string, string, number]} Candle
290
+ */
291
+
292
+ /**
293
+ * @typedef {{}} Ticker24hResult
294
+ * @property {number} ledger - Ledger sequence
295
+ * @property {number} timestamp - UNIX timestamp (seconds)
296
+ * @property {TickerEntry[]} ticker - Per-market 24h stats, sorted by trade count descending
297
+ */
298
+
299
+ /**
300
+ * @typedef {{}} TickerEntry
301
+ * @property {string} symbol - Market symbol `BASE/QUOTE`
302
+ * @property {string} openPrice - Opening price 24h ago
303
+ * @property {string} highPrice - Highest price in the 24h window
304
+ * @property {string} lowPrice - Lowest price in the 24h window
305
+ * @property {string} lastPrice - Most recent trade price
306
+ * @property {string} volume - 24h base asset volume
307
+ * @property {string} quoteVolume - 24h quote asset volume
308
+ * @property {number} change - 24h price change (percent)
309
+ * @property {string} avgPrice - Volume-weighted average price
310
+ * @property {number} trades - 24h trade count
311
+ */
312
+
313
+ /**
314
+ * @typedef {{}} MarketsParams
315
+ * @property {string} [cursor] - Pagination cursor (`baseAsset-quoteAsset`)
316
+ * @property {number|string} [limit] - Max markets to return
317
+ */
318
+
319
+ /**
320
+ * @typedef {{}} MarketInfo
321
+ * @property {string} baseAsset - Base asset contract id
322
+ * @property {string} quoteAsset - Quote asset contract id
323
+ * @property {string} cursor - Pagination cursor for this market
324
+ * @property {string[]} orderTypes - Supported order types
325
+ */
326
+
327
+ /**
328
+ * @typedef {{}} ContractInfo - Contract state tracked by the indexer
329
+ * @property {string} address - AXIS contract address
330
+ * @property {'mainnet'|'testnet'} [network] - Stellar network of the contract
331
+ * @property {boolean} frozen - Whether trading is blocked by the safety admin
332
+ * @property {ContractInfoConfig} [config] - Contract configuration
333
+ * @property {ContractInfoMarket[]} markets - Markets opened by `subsidize`
334
+ * @property {ContractInfoAsset[]} [assets] - Metadata of the market tokens
335
+ */
336
+
337
+ /**
338
+ * @typedef {{}} ContractInfoAsset - Market token metadata (only `contract` until the AXIS API resolves it)
339
+ * @property {string} contract - Token contract address
340
+ * @property {string} [code] - Asset code (token symbol)
341
+ * @property {string} [issuer] - Issuer account of a classic asset, `native` for XLM, absent for a SEP-41 token
342
+ * @property {number} [decimals] - Token decimals
343
+ * @property {string} [name] - Asset name
344
+ * @property {string} [domain] - Home domain of the issuer
345
+ * @property {string} [icon] - Icon URL
346
+ */
347
+
348
+ /**
349
+ * @typedef {{}} ContractInfoConfig
350
+ * @property {string} safetyAdmin - Safety admin address
351
+ * @property {string} oracle - Price oracle contract address
352
+ * @property {number} [listingMinDays] - Days of price feeds a new market must buy (0 opens markets without a fee)
353
+ * @property {string} marketListingFee - Oracle fee tokens a market creator pays to provision the price feeds
354
+ * @property {string} minTradeSize - Minimum trade value in USD with 7 decimals (0 = disabled)
355
+ * @property {number} [ledgerTime] - Expected ledger close time in seconds
356
+ */
357
+
358
+ /**
359
+ * @typedef {{}} ContractInfoMarket
360
+ * @property {string} base - Base market asset, the first of the pair in canonical order
361
+ * @property {string} quote - Quote market asset, the second of the pair in canonical order
362
+ * @property {string} created - Creation timestamp (UTC)
363
+ * @property {string} refreshed - Last oracle check timestamp (UTC)
364
+ */
365
+
366
+ /**
367
+ * @typedef {{}} OrdersParams
368
+ * @property {string} [owner] - Filter by order owner address
369
+ * @property {string|string[]} [asset] - Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair)
370
+ * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
371
+ * @property {number|string} [limit] - Max orders to return
372
+ */
373
+
374
+ /**
375
+ * @typedef {{}} OrderHistoryParams
376
+ * @property {string} [owner] - Filter by order owner address
377
+ * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
378
+ * @property {string|bigint} [cursor] - `cursor` of the last order received (its creation position, not the order id)
379
+ * @property {number|string} [limit] - Max orders to return
380
+ */
381
+
382
+ /**
383
+ * @typedef {{}} TradesParams
384
+ * @property {string} [trader] - Filter by trader address
385
+ * @property {string[]} [pair] - Asset pair `[base, quote]` (contract ids)
386
+ * @property {string|bigint} [cursor] - `cursor` of the last record received (the trade or swap id)
387
+ * @property {number|string} [limit] - Max trades to return
388
+ */
389
+
390
+ /**
391
+ * @typedef {{}} FailuresParams
392
+ * @property {string} [account] - Caller of the failed transaction, or a party of the failed transfer
393
+ * @property {string} [fn] - Contract function (`trade`, `swap`, `crossfill`, `update`, ...)
394
+ * @property {string|bigint} [cursor] - `cursor` of the last record received
395
+ * @property {number|string} [limit] - Max records to return (20 by default, at most 500)
396
+ */
397
+
398
+ /**
399
+ * @typedef {{}} ApiFailure - Failed AXIS call (made by the transaction or through another contract, the transaction failed
400
+ * or a calling contract caught the failure). It changes no state and blames no party:
401
+ * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be
402
+ * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller
403
+ * @property {'failure'} type - Record type
404
+ * @property {string} id - Record id (position of the transaction plus the index of the failed call)
405
+ * @property {string} txHash - Transaction hash
406
+ * @property {number} ledger - Ledger sequence
407
+ * @property {string} timestamp - Ledger close time (UTC)
408
+ * @property {string} fn - Contract function called
409
+ * @property {string} caller - The `trader` or `sponsor` argument, the transaction source for other functions
410
+ * @property {string[]} orders - Maker order ids listed by the call
411
+ * @property {string} [takerOrder] - Taker order id of a `crossfill`
412
+ * @property {string} result - Operation result code
413
+ * @property {boolean} [caught] - The transaction succeeded: a calling contract caught the failed AXIS call
414
+ * @property {'contract'|'transfer'|'resources'|'auth'|'unknown'} reason - `contract`: a contract error (`error`),
415
+ * `transfer`: a token transfer failed (`transfer`, either side may be at fault), `resources`: a resource limit, the
416
+ * refundable fee or an archived entry, `auth`: an authorization failure, `unknown`: no diagnostic events
417
+ * @property {{contract: string|null, code: number, name?: string}} [error] - Contract error that failed the call
418
+ * @property {{token: string, fn: string, from: string, to: string, amount: string}} [transfer] - Token transfer that failed
419
+ * @property {string} cursor - Pagination cursor
420
+ */
421
+
422
+ /**
423
+ * @typedef {{}} ApiOrder - Serialized order returned by the API
424
+ * @property {string} id - Order ID (decimal u128)
425
+ * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`)
426
+ * @property {string} buying - Buying asset contract id
427
+ * @property {string} selling - Selling asset contract id
428
+ * @property {string} price - Order price
429
+ * @property {string} rprice - Rational price representation
430
+ * @property {string} quote - Original selling amount
431
+ * @property {string} amount - Amount left to sell
432
+ * @property {string} [backed] - Amount the maker can actually deliver, when the indexer tracks backing
433
+ * @property {ApiOrderBacking} [backing] - Maker backing details, when the indexer tracks backing
434
+ * @property {string} owner - Maker address
435
+ * @property {string} [expires] - Expiration timestamp (UTC)
436
+ * @property {string} [created] - Creation timestamp (UTC)
437
+ * @property {string} [updated] - Last update timestamp (UTC)
438
+ * @property {string} [cursor] - Pagination cursor
439
+ */
440
+
441
+ /**
442
+ * @typedef {{}} ApiOrderBacking - Maker backing in the order's selling asset
443
+ * @property {string} balance - Token balance
444
+ * @property {string} allowance - Allowance granted to the AXIS contract
445
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
446
+ * @property {boolean} authorized - Whether the maker can send and receive the token
447
+ * @property {string} [updated] - Last load timestamp (UTC)
448
+ * @property {boolean} [pending] - A reload confirming the latest event is still due: the values may predate it
449
+ */
450
+
451
+ /**
452
+ * @typedef {{}} ApiBacking - Tracked backing of an account in a token
453
+ * @property {string} owner - Account address
454
+ * @property {string} asset - Token contract id
455
+ * @property {string} balance - Token balance
456
+ * @property {string} allowance - Allowance granted to the AXIS contract
457
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
458
+ * @property {boolean} authorized - Whether the account can send and receive the token
459
+ * @property {string} budget - Effective budget, min(balance, allowance), 0 when unauthorized or expired
460
+ * @property {string} [headroom] - Amount the account can still receive (trustline limit minus balance and buying
461
+ * liabilities), omitted when unlimited or unknown
462
+ * @property {string} [updated] - Last load timestamp (UTC)
463
+ * @property {string} [skipped] - Last `skip` event of an order selling the token (UTC)
464
+ * @property {boolean} [pending] - A reload confirming the latest event is still due
465
+ */
466
+
467
+ /**
468
+ * @typedef {{}} ApiAccount - Account state: every live order and the backing per traded asset
469
+ * @property {string} address - Trader address
470
+ * @property {number} ledger - Last processed ledger
471
+ * @property {ApiOrder[]} orders - Live orders, oldest first
472
+ * @property {Object<string, ApiBacking>} backing - Backing by token contract id
473
+ */
474
+
475
+ /**
476
+ * @typedef {{}} ApiSwap - Serialized swap returned by the API, one per `swap` call
477
+ * @property {'swap'} type - Record type
478
+ * @property {string} id - Swap ID
479
+ * @property {string} trader - Trader 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} price - Approximate swap price
485
+ * @property {string} cursor - Pagination cursor
486
+ * @property {string} timestamp - Swap timestamp (UTC)
487
+ */
488
+
489
+ /**
490
+ * @typedef {{}} ApiTrade - Serialized trade returned by the API
491
+ * @property {'trade'} type - Record type
492
+ * @property {string} id - Trade ID
493
+ * @property {string} order - Matched order ID
494
+ * @property {string} taker - Taker account address
495
+ * @property {string} maker - Maker account address
496
+ * @property {string} soldAsset - Sold asset contract id
497
+ * @property {string} boughtAsset - Bought asset contract id
498
+ * @property {string} sold - Sold tokens amount
499
+ * @property {string} bought - Bought tokens amount
500
+ * @property {string} [left] - Order amount left after the fill
501
+ * @property {boolean} [crossfill] - The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the
502
+ * amounts mirror the makers' fills of the same call (left out of candles and volume)
503
+ * @property {string} price - Approximate trade price
504
+ * @property {string} [cursor] - Pagination cursor
505
+ * @property {string} timestamp - Trade timestamp (UTC)
506
+ */