@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/index.d.ts CHANGED
@@ -1,1446 +1,1626 @@
1
- import type {rpc} from "@stellar/stellar-sdk";
2
-
3
- /** Trading order type */
4
- export enum OrderKind {
5
- /** Execute trade, create a limit order if not executed in full */
6
- Limit = 1,
7
- /** Execute trade without creating a limit order */
8
- Fill = 2,
9
- /** Execute trade, cancel if was not executed in full */
10
- FillOrKill = 3,
11
- }
12
-
13
- /** Trade direction instructions */
14
- export enum TradeDirection {
15
- Sell = 1,
16
- Buy = 2,
17
- }
18
-
19
- /** Order properties, stored on-chain */
20
- export interface Order {
21
- /** Amount left to sell */
22
- amount: bigint;
23
- /** Buying token address */
24
- buying: string;
25
- /** Expiration timestamp (0 = no expiration) */
26
- expires: bigint;
27
- /** Unique order identifier, derived from the owner and the client nonce */
28
- id: bigint;
29
- /** Maker address */
30
- owner: string;
31
- /** Order price (`buying` per 1 `selling`, 18 decimals) */
32
- price: bigint;
33
- /** Selling token address */
34
- selling: string;
35
- }
36
-
37
- /** Token allowance granted to the contract as part of the call */
38
- export interface Approval {
39
- /** Token the allowance is granted on: defaults to `selling` for `buy`, `sell` and `swap`, required in `update` approvals */
40
- asset?: string;
41
- /** Absolute allowance amount (0 revokes the approval) */
42
- amount: bigint;
43
- /** Ledger sequence the allowance lives until */
44
- liveUntil: number;
45
- }
46
-
47
- /** New amount, price and expiration for an existing order */
48
- export interface OrderUpdate {
49
- /** Order id */
50
- id: bigint;
51
- /** New amount to sell, 0 removes the order */
52
- amount: bigint;
53
- /** New order price (ignored for a removal) */
54
- price: bigint;
55
- /** New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration */
56
- expires?: bigint | number;
57
- }
58
-
59
- /** Contract configuration */
60
- export interface Config {
61
- /** Oracle contract address */
62
- oracle: string;
63
- /** Amount of oracle tokens burned by the market creator to provision the oracle price feeds (always the oracle daily fee x 90) */
64
- market_listing_fee: bigint;
65
- /** Address of the account allowed to freeze the contract, change the minimum trade size and replace the oracle */
66
- safety_admin: string;
67
- /** Minimum trade value in USD, with 7 decimals precision (0 disables the limit) */
68
- min_trade_size: bigint;
69
- }
70
-
71
- /** Market asset descriptor */
72
- export interface MarketSide {
73
- /** Token contract address */
74
- asset: string;
75
- /** Whether the asset is quoted by the oracle */
76
- listed: boolean;
77
- /** Token decimals (fetched only for listed assets) */
78
- decimals: number;
79
- }
80
-
81
- /** Market record, stored on-chain */
82
- export interface Market {
83
- /** First asset (canonical order) */
84
- a: MarketSide;
85
- /** Second asset (canonical order) */
86
- b: MarketSide;
87
- /** Creation timestamp */
88
- created: bigint;
89
- }
90
-
91
- /** Orderbook `trade` event, one per fill (topics: `trade`, `selling`, `buying`) */
92
- export interface TradeContractEvent {
93
- /** Asset sold by the taker (topic) */
94
- selling: string;
95
- /** Asset bought by the taker (topic) */
96
- buying: string;
97
- /** Maker order id */
98
- order: bigint;
99
- /** Trader account address */
100
- taker: string;
101
- /** Seller account address */
102
- maker: string;
103
- /** Sold tokens amount */
104
- sold: bigint;
105
- /** Bought tokens amount */
106
- bought: bigint;
107
- /** Order amount left after the fill (0 = removed) */
108
- left: bigint;
109
- }
110
-
111
- /** Orderbook `swap` event, one per call (topics: `swap`, `selling`, `buying`) */
112
- export interface SwapContractEvent {
113
- /** Asset sold by the trader (topic) */
114
- selling: string;
115
- /** Asset received by the trader (topic) */
116
- buying: string;
117
- /** Trader account address */
118
- trader: string;
119
- /** Amount of `selling` tokens sold */
120
- sold: bigint;
121
- /** Amount of `buying` tokens received */
122
- bought: bigint;
123
- }
124
-
125
- /** Orderbook `new` event, an order created (topics: `new`, `selling`, `buying`) */
126
- export interface OrderCreatedContractEvent {
127
- /** Selling asset address (topic) */
128
- selling: string;
129
- /** Buying asset address (topic) */
130
- buying: string;
131
- /** Unique order identifier */
132
- id: bigint;
133
- /** Maker address */
134
- owner: string;
135
- /** Order price */
136
- price: bigint;
137
- /** Current amount */
138
- amount: bigint;
139
- /** Expiration timestamp (0 = no expiration) */
140
- expires: bigint;
141
- }
142
-
143
- /** Orderbook `mod` event, an order changed outside a fill (topics: `mod`) */
144
- export interface OrderUpdatedContractEvent {
145
- /** Unique order identifier */
146
- id: bigint;
147
- /** Order price */
148
- price: bigint;
149
- /** Current amount (0 = removed) */
150
- amount: bigint;
151
- /** Expiration timestamp (0 = no expiration) */
152
- expires: bigint;
153
- }
154
-
155
- /**
156
- * Orderbook `skip` event, a listed order its maker could not settle (backing short of the fill, cannot receive the
157
- * taker's asset, or the transfer failed); the order is left unchanged (topics: `skip`)
158
- */
159
- export interface OrderSkippedContractEvent {
160
- /** Order id */
161
- order: bigint;
162
- }
163
-
164
- /** Orderbook `refresh` event, a market checked against the oracle (topics: `refresh`, `a`, `b`; no data) */
165
- export interface MarketRefreshContractEvent {
166
- /** First market asset (canonical order, topic) */
167
- a: string;
168
- /** Second market asset (canonical order, topic) */
169
- b: string;
170
- }
171
-
172
- /** `freeze` event (topics: `freeze`) */
173
- export interface FreezeContractEvent {
174
- /** Whether trading is blocked after the call */
175
- frozen: boolean;
176
- }
177
-
178
- /** `config` update notification event, emitted by the constructor, `delegate`, `set_oracle` or `set_floor` (topics: `config`) */
179
- export interface ConfigChangedContractEvent {
180
- /** Contract configuration after the call */
181
- config: Config;
182
- }
183
-
184
- /** A trade step in a multi-market swap path. */
185
- export interface TradeStep {
186
- /** Asset to buy at this step */
187
- asset: string;
188
- /** Maker order IDs to match */
189
- orders: Array<bigint>;
190
- }
191
-
192
- /** Standard contract errors */
193
- export declare const ContractErrors: {
194
- 701: {message: "NotAuthorized"};
195
- 702: {message: "InsufficientBalance"};
196
- 703: {message: "InsufficientAllowance"};
197
- 704: {message: "InvalidMatch"};
198
- 705: {message: "InvalidPrice"};
199
- 706: {message: "InvalidAmount"};
200
- 707: {message: "InvalidExpiration"};
201
- 708: {message: "CannotReceive"};
202
- 709: {message: "NotFilled"};
203
- 710: {message: "OrderNotFound"};
204
- 711: {message: "OrderExists"};
205
- 720: {message: "OrderSizeTooSmall"};
206
- 721: {message: "AssetsNotVerifiedByOracle"};
207
- 722: {message: "AssetPriceOracleFetchFailed"};
208
- 723: {message: "InvalidOracleConfig"};
209
- 730: {message: "Frozen"};
210
- 740: {message: "Overflow"};
211
- }
212
-
213
- /**
214
- * Compute the id of the order `owner` creates with `nonce`
215
- * (first 16 bytes of `sha256(xdr([owner, nonce]))` as a big-endian u128)
216
- * @param owner - Order owner address
217
- * @param nonce - u64 nonce the order was created with
218
- */
219
- export declare function orderId(owner: string, nonce: bigint | number | string): bigint;
220
-
221
- export interface ClientInitializationParams {
222
- /** Public key of the account that will interact with the contract */
223
- publicKey: string;
224
- /** Callback for signing transactions generated by the client */
225
- signTransaction: SignTransactionCallback;
226
- /** URL of the RPC server */
227
- rpcUrl: string;
228
- /** DEX contract ID */
229
- contractId: string;
230
- /** Network passphrase (Pubnet passphrase by default) */
231
- networkPassphrase?: string;
232
- /** Transaction fee (0.1 XLM by default) */
233
- fee?: string;
234
- /** Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default) */
235
- autoFootprint?: boolean;
236
- }
237
-
238
- export type SignTransactionCallback = (
239
- tx: string,
240
- context: {network: string; networkPassphrase: string; accountToSign: string}
241
- ) => Promise<{signedTxXdr: string; signerAddress?: string}>;
242
-
243
- export interface TradeArguments {
244
- /** Trading order behavior */
245
- kind: OrderKind,
246
- /** Trader address */
247
- trader: string;
248
- /** Tokens amount */
249
- amount: bigint;
250
- /** Selling token address */
251
- selling: string;
252
- /** Buying token address */
253
- buying: string;
254
- /** Price a trader willing to accept */
255
- price: bigint;
256
- /** List of order IDs to match before creating the order on-chain */
257
- orders?: Array<bigint>;
258
- /** Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration */
259
- expires?: bigint | number;
260
- /** Optional allowance granted to the contract before trading (on `selling` unless `asset` is set) */
261
- approve?: Approval;
262
- }
263
-
264
- export interface SellTradeArguments extends TradeArguments {
265
- /** Amount of `selling` tokens to sell */
266
- amount: bigint;
267
- /** Price a trader willing to accept, minimum `buying` tokens per 1 `selling` */
268
- price: bigint;
269
- }
270
-
271
- export interface BuyTradeArguments extends TradeArguments {
272
- /** Amount of `buying` tokens to acquire */
273
- amount: bigint;
274
- /** Price a trader willing to accept, maximum `selling` tokens per 1 `buying` */
275
- price: bigint;
276
- }
277
-
278
- export interface SwapArguments {
279
- /** Trade direction: `Sell` or `Buy` */
280
- direction: TradeDirection,
281
- /** Trader address */
282
- trader: string,
283
- /** Token address sent by the trader */
284
- selling: string,
285
- /** Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`) */
286
- sellingAmount: bigint,
287
- /** Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`) */
288
- buyingAmount: bigint,
289
- /** Ordered list of the trade route steps */
290
- path: Array<TradeStep>,
291
- /** Optional allowance granted to the contract before trading (on `selling` unless `asset` is set) */
292
- approve?: Approval
293
- }
294
-
295
- export interface UpdateArguments {
296
- /** Orders owner */
297
- trader: string;
298
- /** New amount, price and expiration per order */
299
- updates: Array<OrderUpdate>;
300
- /** Allowances granted before the backing check, each naming its `asset`; an asset without an approval keeps its current allowance */
301
- approvals?: Array<Approval & {asset: string}>;
302
- }
303
-
304
- export interface SubsidizeArguments {
305
- /** Address paying for the oracle feeds (and the listing fee of a new market) */
306
- sponsor: string;
307
- /** First market asset */
308
- selling: string;
309
- /** Second market asset (either order opens the same market) */
310
- buying: string;
311
- /** Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market */
312
- amount: bigint;
313
- }
314
-
315
- export declare class AxisContractClient {
316
- constructor(params: ClientInitializationParams);
317
-
318
- /** Account that signs and pays for the transactions */
319
- readonly publicKey: string;
320
-
321
- /**
322
- * Fetch existing order
323
- * @param id - ID of the order to fetch
324
- * @returns Order fetched from the storage, undefined if not found or expired
325
- */
326
- order(id: bigint): Promise<Order | undefined>;
327
-
328
- /** Fetch contract configuration */
329
- loadConfig(): Promise<Config>;
330
-
331
- /**
332
- * Check whether the contract is frozen
333
- * @returns `true` if contract is frozen (trading and order management operations blocked)
334
- */
335
- isFrozen(): Promise<boolean>;
336
-
337
- /**
338
- * Fetch market for the given asset pair
339
- * @param selling - First market asset
340
- * @param buying - Second market asset
341
- * @returns Market record if the market exists
342
- */
343
- getMarket(selling: string, buying: string): Promise<Market | undefined>;
344
-
345
- /**
346
- * Cancel existing orders, expired ones included: `update` with a zero amount per order (the contract has no
347
- * `cancel`). A transaction can process up to 100 orders in one batch
348
- * @param trader - Trader address
349
- * @param ids - IDs of the orders to cancel (non-existent orders are ignored)
350
- * @throws If trader is not the owner of any existing order in `ids` or if the contract is frozen
351
- */
352
- cancel(trader: string, ids: Array<bigint>): Promise<void>;
353
-
354
- /**
355
- * Update the amount, price, or expiration of several orders in place, or remove them.
356
- * Orders that no longer exist are skipped; expired orders revived with the new expiration.
357
- * A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover
358
- * its expiration +1 day. Approvals and removals work in a frozen contract. A transaction can process up to 100
359
- * orders in one batch
360
- * @param params - Update parameters
361
- * @returns IDs of the orders to update
362
- * @throws If the trader does not own an updated order, if order parameters are invalid, if an order is below the
363
- * minimum value, if the new amounts are not backed by the trader's balance and allowance, if the contract is frozen
364
- */
365
- update(params: UpdateArguments): Promise<Array<bigint>>;
366
-
367
- /**
368
- * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader
369
- * @param trader - Trader address
370
- * @param takerOrderId - ID of the order that serves as a taker
371
- * @param orders - List of order IDs to match against
372
- * @returns Amount the taker order sold, amount the taker received, surplus paid to the trader
373
- * @throws If the taker order does not exist or has expired, if any of the orders provided do not match
374
- * selling/buying asset, if the taker order's owner or the trader cannot receive the bought asset, if the contract is
375
- * frozen
376
- */
377
- crossfill(trader: string, takerOrderId: bigint, orders: Array<bigint>): Promise<[bigint, bigint, bigint]>;
378
-
379
- /**
380
- * Trade with DEX and create a buy limit order if the quote not executed in full
381
- * @param params - Trade parameters
382
- * @returns Amount of sold and bought tokens, ID of the newly created order if any
383
- * @throws If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade
384
- * targets a pair without a market, no reference price is available, any of the counter orders provided do not match
385
- * selling/buying asset, or a live order with the same id exists
386
- */
387
- buy(params: BuyTradeArguments): Promise<[bigint, bigint, bigint | undefined]>;
388
-
389
- /**
390
- * Trade with DEX and create a sell limit order if the quote not executed in full
391
- * @param params - Trade parameters
392
- * @returns Amount of sold and bought tokens, ID of the newly created order if any
393
- * @throws If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade
394
- * targets a pair without a market, no reference price is available, any of the counter orders provided do not match
395
- * selling/buying asset, or a live order with the same id exists
396
- */
397
- sell(params: SellTradeArguments): Promise<[bigint, bigint, bigint | undefined]>;
398
-
399
- /**
400
- * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call
401
- * @param params - Swap path and settings
402
- * @returns Amount of sold and bought tokens
403
- * @throws If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid, if any
404
- * of the orders provided do not match trade step selling/buying asset, if the trader cannot pay for the fills or
405
- * receive tokens, if the contract is frozen
406
- */
407
- swap(params: SwapArguments): Promise<[bigint, bigint]>;
408
-
409
- /** Extend the contract instance and code lifetime */
410
- keepalive(): Promise<void>;
411
-
412
- /**
413
- * Re-check both market assets against the price oracle and cache oracle prices.
414
- * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting new limit orders; its
415
- * outstanding orders stay cancellable and fillable. The record and the cached prices are rewritten only when they
416
- * change. When the simulation writes nothing (the market and the cached prices are current, or the oracle has no
417
- * newer price), the simulated result is returned and no transaction is submitted
418
- * @param selling - First market asset
419
- * @param buying - Second market asset
420
- * @returns Updated market record, undefined if the market does not exist
421
- * @throws If the contract is frozen
422
- */
423
- requote(selling: string, buying: string): Promise<Market | undefined>;
424
-
425
- /**
426
- * Extend oracle price feeds access for a market, creating the market if it does not exist yet
427
- * @param params - Subsidy parameters
428
- * @returns New access expiration UNIX timestamps (in seconds) per oracle-listed asset
429
- * @throws If `amount` is invalid, if the market does not exist and the amount is below the market listing fee, if
430
- * neither market asset is quoted by the oracle, if the contract is frozen
431
- */
432
- subsidize(params: SubsidizeArguments): Promise<Array<bigint>>;
433
- }
434
-
435
- /** Error thrown when the Aggregator API responds with a non-success HTTP status */
436
- export declare class AxisApiError extends Error {
437
- constructor(message: string, status: number);
438
-
439
- /** HTTP status code associated with the error */
440
- readonly status: number;
441
- }
442
-
443
- export interface QuoteParams {
444
- /** Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId) */
445
- sellingAsset: string;
446
- /** Asset to buy (same format as `sellingAsset`) */
447
- buyingAsset: string;
448
- /** Trade amount in stroops (1 unit = 10,000,000 stroops) */
449
- amount: string | number;
450
- /** Restrict to the direct market only (no intermediate-asset routes) */
451
- direct?: boolean;
452
- }
453
-
454
- export interface QuotePathStep {
455
- /** Selling asset contract id at this hop */
456
- selling: string;
457
- /** Buying asset contract id at this hop */
458
- buying: string;
459
- /** Maker order IDs matched at this hop */
460
- orders: string[];
461
- /** Highest price among the matched orders (maker `buying` per `selling`, 18 decimals): a trade limit at this price crosses every listed order */
462
- worstPrice?: string;
463
- }
464
-
465
- export interface QuotePath {
466
- /** Amount sold, in stroops */
467
- sold: string;
468
- /** Amount bought, in stroops */
469
- bought: string;
470
- /** Ordered list of hops in the route */
471
- path: QuotePathStep[];
472
- }
473
-
474
- export interface QuoteResult {
475
- /** Base58-encoded quote id */
476
- id: string;
477
- /** Quote status */
478
- status: 'success' | 'unfeasible' | 'rejected';
479
- /** Trade direction */
480
- direction: 'strict_send' | 'strict_receive';
481
- /** Selling asset contract id */
482
- sellingAsset: string;
483
- /** Buying asset contract id */
484
- buyingAsset: string;
485
- /** Ledger sequence the quote was computed for */
486
- ledger: number;
487
- /** Candidate routes ranked by profitability (up to 10) */
488
- paths: QuotePath[];
489
- /** Error message (present only if status is not `success`) */
490
- error?: string;
491
- }
492
-
493
- export interface DepthParams {
494
- /** Market identifier `BASE/QUOTE` */
495
- market: string;
496
- /** Percentage band (±) around the center price (0 < depth ≤ 100, default 20) */
497
- depth?: number;
498
- /** Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid price by default) */
499
- step?: string;
500
- /** Price levels per side (default 100, max 500) */
501
- limit?: number;
502
- }
503
-
504
- export interface OrderbookDepth {
505
- /** Ledger sequence */
506
- ledger: number;
507
- /** UNIX timestamp (seconds) */
508
- timestamp: number;
509
- /** Price step of the levels (null for an empty book) */
510
- step: string | null;
511
- /** Exact best bid price, before the rounding to levels */
512
- bestBid: string | null;
513
- /** Exact best ask price, before the rounding to levels */
514
- bestAsk: string | null;
515
- /** `[price, quantity]` pairs sorted descending by price */
516
- bids: Array<[string, string]>;
517
- /** `[price, quantity]` pairs sorted ascending by price */
518
- asks: Array<[string, string]>;
519
- }
520
-
521
- export interface CandlesParams {
522
- /** Market identifier `BASE/QUOTE` */
523
- market: string;
524
- /** Lower boundary (UNIX seconds, default 0) */
525
- from?: number;
526
- /** Upper boundary (UNIX seconds, defaults to `from + resolution * 200`) */
527
- to?: number;
528
- /** Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`) */
529
- resolution?: number | string;
530
- /** Sort order (default `desc`) */
531
- order?: 'asc' | 'desc';
532
- }
533
-
534
- /** OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]` */
535
- export type Candle = [number, string, string, string, string, string, string, number];
536
-
537
- export interface TickerEntry {
538
- /** Market symbol `BASE/QUOTE` */
539
- symbol: string;
540
- /** Opening price 24h ago */
541
- openPrice: string;
542
- /** Highest price in the 24h window */
543
- highPrice: string;
544
- /** Lowest price in the 24h window */
545
- lowPrice: string;
546
- /** Most recent trade price */
547
- lastPrice: string;
548
- /** 24h base asset volume */
549
- volume: string;
550
- /** 24h quote asset volume */
551
- quoteVolume: string;
552
- /** 24h price change (percent) */
553
- change: number;
554
- /** Volume-weighted average price */
555
- avgPrice: string;
556
- /** 24h trade count */
557
- trades: number;
558
- }
559
-
560
- export interface Ticker24hResult {
561
- /** Ledger sequence */
562
- ledger: number;
563
- /** UNIX timestamp (seconds) */
564
- timestamp: number;
565
- /** Per-market 24h stats, sorted by trade count descending */
566
- ticker: TickerEntry[];
567
- }
568
-
569
- export interface MarketsParams {
570
- /** Pagination cursor (`baseAsset-quoteAsset`) */
571
- cursor?: string;
572
- /** Max markets to return */
573
- limit?: number | string;
574
- }
575
-
576
- export interface MarketInfo {
577
- /** Base asset contract id */
578
- baseAsset: string;
579
- /** Quote asset contract id */
580
- quoteAsset: string;
581
- /** Pagination cursor for this market */
582
- cursor: string;
583
- /** Supported order types */
584
- orderTypes: string[];
585
- }
586
-
587
- /** Contract configuration tracked by the indexer */
588
- export interface ContractInfoConfig {
589
- /** Safety admin address */
590
- safetyAdmin: string;
591
- /** Price oracle contract address */
592
- oracle: string;
593
- /** Fee token amount burned to open a market */
594
- marketListingFee: string;
595
- /** Minimum trade value in USD with 7 decimals (0 = disabled) */
596
- minTradeSize: string;
597
- }
598
-
599
- /** Market tracked by the indexer */
600
- export interface ContractInfoMarket {
601
- /** First market asset */
602
- a: string;
603
- /** Second market asset */
604
- b: string;
605
- /** Creation timestamp (UTC) */
606
- created: string;
607
- /** Last oracle check timestamp (UTC) */
608
- refreshed: string;
609
- }
610
-
611
- /** Contract state tracked by the indexer */
612
- export interface ContractInfo {
613
- /** Whether trading is blocked by the safety admin */
614
- frozen: boolean;
615
- /** Contract configuration */
616
- config?: ContractInfoConfig;
617
- /** Markets opened by `subsidize` */
618
- markets: ContractInfoMarket[];
619
- }
620
-
621
- export interface OrdersParams {
622
- /** Filter by order owner address */
623
- owner?: string;
624
- /** Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair) */
625
- asset?: string | string[];
626
- /** Pagination cursor (order id) */
627
- cursor?: string | bigint;
628
- /** Max orders to return */
629
- limit?: number | string;
630
- }
631
-
632
- export interface OrderHistoryParams {
633
- /** Filter by order owner address */
634
- owner?: string;
635
- /** Asset pair `[base, quote]` (contract ids) */
636
- pair?: string[];
637
- /** Pagination cursor (order id) */
638
- cursor?: string | bigint;
639
- /** Max orders to return */
640
- limit?: number | string;
641
- }
642
-
643
- export interface TradesParams {
644
- /** Filter by trader address */
645
- trader?: string;
646
- /** Asset pair `[base, quote]` (contract ids) */
647
- pair?: string[];
648
- /** Pagination cursor (trade id) */
649
- cursor?: string | bigint;
650
- /** Max trades to return */
651
- limit?: number | string;
652
- }
653
-
654
- /** Maker backing in the order's selling asset */
655
- export interface ApiOrderBacking {
656
- /** Token balance */
657
- balance: string;
658
- /** Allowance granted to the AXIS contract */
659
- allowance: string;
660
- /** Ledger sequence the allowance lives until */
661
- liveUntil: number;
662
- /** Whether the maker can send and receive the token */
663
- authorized: boolean;
664
- /** Last load timestamp (UTC) */
665
- updated?: string;
666
- /** A reload confirming the latest event is still due: the values may predate it */
667
- pending?: boolean;
668
- }
669
-
670
- /** Tracked backing of an account in a token */
671
- export interface ApiBacking {
672
- /** Account address */
673
- owner: string;
674
- /** Token contract id */
675
- asset: string;
676
- /** Token balance */
677
- balance: string;
678
- /** Allowance granted to the AXIS contract */
679
- allowance: string;
680
- /** Ledger sequence the allowance lives until */
681
- liveUntil: number;
682
- /** Whether the account can send and receive the token */
683
- authorized: boolean;
684
- /** Effective budget, min(balance, allowance), 0 when unauthorized or expired */
685
- budget: string;
686
- /** Last load timestamp (UTC) */
687
- updated?: string;
688
- /** Last `skip` event of an order selling the token (UTC) */
689
- skipped?: string;
690
- /** A reload confirming the latest event is still due */
691
- pending?: boolean;
692
- }
693
-
694
- /** Account state: every live order and the backing per traded asset */
695
- export interface ApiAccount {
696
- /** Trader address */
697
- address: string;
698
- /** Last processed ledger */
699
- ledger: number;
700
- /** Live orders, oldest first */
701
- orders: ApiOrder[];
702
- /** Backing by token contract id */
703
- backing: Record<string, ApiBacking>;
704
- }
705
-
706
- /** Serialized order returned by the API */
707
- export interface ApiOrder {
708
- /** Order ID (decimal u128) */
709
- id: string;
710
- /** Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`) */
711
- status: 'ACTIVE' | 'FILLED' | 'CANCELED' | 'EXPIRED';
712
- /** Buying asset contract id */
713
- buying: string;
714
- /** Selling asset contract id */
715
- selling: string;
716
- /** Order price */
717
- price: string;
718
- /** Rational price representation */
719
- rprice: string;
720
- /** Selling amount at creation */
721
- quote: string;
722
- /** Amount left to sell */
723
- amount: string;
724
- /** Amount the maker can actually deliver, when the indexer tracks backing */
725
- backed?: string;
726
- /** Maker backing details, when the indexer tracks backing */
727
- backing?: ApiOrderBacking;
728
- /** Maker address */
729
- owner: string;
730
- /** Expiration timestamp (UTC) */
731
- expires?: string;
732
- /** Creation timestamp (UTC) */
733
- created?: string;
734
- /** Last update timestamp (UTC) */
735
- updated?: string;
736
- /** Pagination cursor */
737
- cursor?: string;
738
- }
739
-
740
- /** Serialized trade returned by the API */
741
- export interface ApiTrade {
742
- /** Record type */
743
- type: 'trade';
744
- /** Trade ID */
745
- id: string;
746
- /** Matched order ID */
747
- order: string;
748
- /** Taker account address */
749
- taker: string;
750
- /** Maker account address */
751
- maker: string;
752
- /** Sold asset contract id */
753
- soldAsset: string;
754
- /** Bought asset contract id */
755
- boughtAsset: string;
756
- /** Sold tokens amount */
757
- sold: string;
758
- /** Bought tokens amount */
759
- bought: string;
760
- /** Order amount left after the fill */
761
- left?: string;
762
- /** Approximate trade price */
763
- price: string;
764
- /** Pagination cursor */
765
- cursor?: string;
766
- /** Trade timestamp (UTC) */
767
- timestamp: string;
768
- }
769
-
770
- /** HTTP client for the AXIS Aggregator REST API */
771
- export declare class AxisApiClient {
772
- /** @param serverUrl - Base URL of the Aggregator server */
773
- constructor(serverUrl: string);
774
-
775
- /** Base URL of the Aggregator server */
776
- readonly serverUrl: string;
777
-
778
- /**
779
- * Price quote and candidate trade routes for selling a fixed amount of the source asset
780
- * @param params - Quote request parameters
781
- * @returns Best routes ranked by profitability
782
- * @throws {AxisApiError} If the server is not ready or there is not enough liquidity
783
- */
784
- quoteSell(params: QuoteParams): Promise<QuoteResult>;
785
-
786
- /**
787
- * Price quote and candidate trade routes for buying a fixed amount of the destination asset
788
- * @param params - Quote request parameters
789
- * @returns Best routes ranked by profitability
790
- * @throws {AxisApiError} If the server is not ready or there is not enough liquidity
791
- */
792
- quoteBuy(params: QuoteParams): Promise<QuoteResult>;
793
-
794
- /**
795
- * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,
796
- * asks up, so a level price crosses every order in it)
797
- * @param params - Depth request parameters
798
- * @returns Aggregated bids and asks
799
- */
800
- getDepth(params: DepthParams): Promise<OrderbookDepth>;
801
-
802
- /**
803
- * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)
804
- * @param params - Candles request parameters
805
- * @returns Time-bucketed candles, max 200 per response
806
- */
807
- getCandles(params: CandlesParams): Promise<Candle[]>;
808
-
809
- /**
810
- * 24-hour ticker statistics for every available market
811
- * @returns Aggregated 24h stats per market
812
- */
813
- getTicker24h(): Promise<Ticker24hResult>;
814
-
815
- /**
816
- * List all active markets with pagination
817
- * @param params - Pagination parameters
818
- * @returns Active markets
819
- */
820
- getMarkets(params?: MarketsParams): Promise<MarketInfo[]>;
821
-
822
- /**
823
- * Contract state tracked by the indexer: frozen switch, configuration and active markets
824
- * @returns Contract state
825
- */
826
- getContract(): Promise<ContractInfo>;
827
-
828
- /**
829
- * Retrieve active orders, filterable by owner or asset
830
- * @param params - Filter parameters
831
- * @returns Active orders matching the filter
832
- */
833
- getOrders(params?: OrdersParams): Promise<ApiOrder[]>;
834
-
835
- /**
836
- * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each
837
- * asset they trade
838
- * @param address - Trader address
839
- */
840
- getAccount(address: string): Promise<ApiAccount>;
841
-
842
- /**
843
- * Retrieve a single order by ID
844
- * @param id - Order ID
845
- * @returns Order (throws `AxisApiError` with status 404 if not found)
846
- */
847
- getOrder(id: bigint | string | number): Promise<ApiOrder>;
848
-
849
- /**
850
- * Retrieve archived/historical orders
851
- * @param params - Filter parameters
852
- * @returns Archived orders matching the filter
853
- */
854
- getOrderHistory(params?: OrderHistoryParams): Promise<ApiOrder[]>;
855
-
856
- /**
857
- * Retrieve recent trades
858
- * @param params - Filter parameters
859
- * @returns Recent trades matching the filter
860
- */
861
- getTrades(params?: TradesParams): Promise<ApiTrade[]>;
862
- }
863
-
864
- /** Price scale of the contract (18 decimals) */
865
- export declare const PRICE_SCALE: bigint;
866
-
867
- /**
868
- * Compare two assets in the contract canonical order
869
- * @param a - Token contract address
870
- * @param b - Token contract address
871
- * @returns Negative if `a` first, positive if `b` first, 0 if equal
872
- */
873
- export declare function compareAssets(a: string, b: string): number;
874
-
875
- /**
876
- * Reorder an asset pair the way the contract stores markets
877
- * @param x - Token contract address
878
- * @param y - Token contract address
879
- * @returns `[a, b]`: `a` is the base, `b` the quote of the canonical market symbol
880
- */
881
- export declare function canonicalPair(x: string, y: string): [string, string];
882
-
883
- /**
884
- * Canonical market key `a/b`
885
- * @param a - Token contract address
886
- * @param b - Token contract address
887
- */
888
- export declare function pairKey(a: string, b: string): string;
889
-
890
- /**
891
- * Calculate inverted price, rounded down: `floor(10^36 / price)`
892
- * @param price - Price in the contract scale
893
- */
894
- export declare function invertPrice(price: bigint): bigint;
895
-
896
- /**
897
- * 24h ticker entry of the market seen in the inverted orientation (`b/a`)
898
- * @param entry - Standard ticker entry
899
- */
900
- export declare function invertTicker(entry: TickerEntry): TickerEntry;
901
-
902
- /**
903
- * Parse an Aggregator API timestamp (`YYYY-MM-DD HH:mm:ss` UTC)
904
- * @returns UNIX milliseconds, 0 when missing or invalid
905
- */
906
- export declare function parseApiDate(value: string | number | undefined): number;
907
-
908
- /** Allowance lifetime granted with a trade, in ledgers: ~30 days at 5s per ledger (the maximum entry TTL ~180 days) */
909
- export declare const APPROVAL_TTL_LEDGERS: number;
910
- /** An allowance expiring within this number of ledgers is renewed with the next trade (~1 day) */
911
- export declare const APPROVAL_RENEW_LEDGERS: number;
912
-
913
- export interface ApprovalPlanParams {
914
- /** Max amount of the selling asset the call may spend */
915
- required: bigint;
916
- /** Remaining amount of orders in the book selling the asset */
917
- committed: bigint;
918
- /** Current allowance (0 once expired) */
919
- allowance: bigint;
920
- /** Current ledger sequence */
921
- ledger: number;
922
- /** Ledger the current allowance lives until (0 or omitted when unknown) */
923
- liveUntil?: number;
924
- }
925
-
926
- /**
927
- * Decide whether a call needs an in-call approval and adjust it. The approval amount is absolute and one allowance
928
- * backs every order selling the token across all markets, so it has to cover this call plus every order selling the
929
- * same asset
930
- * @returns Approval to pass with the call, undefined when the current allowance already covers it
931
- */
932
- export declare function planApproval(params: ApprovalPlanParams): {amount: bigint, liveUntil: number} | undefined;
933
-
934
- /**
935
- * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`
936
- * @param amount - Amount of `buying` tokens to acquire
937
- * @param price - Limit price (`selling` per 1 `buying`, with AXIS standard price decimals)
938
- */
939
- export declare function maxQuoteSpend(amount: bigint, price: bigint): bigint;
940
-
941
- /** Minimal event emitter that works in browsers and Node */
942
- export declare class Emitter {
943
- /**
944
- * Subscribe to an event
945
- * @returns Unsubscribe function
946
- */
947
- on(event: string, listener: (...args: any[]) => void): () => void;
948
- /**
949
- * Subscribe to the next occurrence of an event
950
- * @returns Unsubscribe function
951
- */
952
- once(event: string, listener: (...args: any[]) => void): () => void;
953
- /** Unsubscribe from an event */
954
- off(event: string, listener: (...args: any[]) => void): void;
955
- }
956
-
957
- /** Server message; `type` names the payload, `topic` the subscription it belongs to */
958
- export interface StreamMessage {
959
- type: string;
960
- topic?: string;
961
- /** Echoed request id (snapshots and errors) */
962
- id?: number;
963
- [key: string]: any;
964
- }
965
-
966
- export interface StreamClientOptions {
967
- /** WebSocket implementation (the global one by default) */
968
- WebSocket?: typeof WebSocket;
969
- /** Application-level ping period, in milliseconds (20 s by default) */
970
- pingInterval?: number;
971
- /** First reconnect delay, doubled after each failure (1 s by default) */
972
- minReconnectDelay?: number;
973
- /** Reconnect delay cap (30 s by default) */
974
- maxReconnectDelay?: number;
975
- }
976
-
977
- /**
978
- * WebSocket client of the Aggregator push API.
979
- * Emits `open`, `close` and `error` (server errors not tied to a subscription).
980
- */
981
- export declare class AxisStreamClient extends Emitter {
982
- /** @param url - WebSocket endpoint, e.g. `wss://api.axis.markets/ws` */
983
- constructor(url: string, options?: StreamClientOptions);
984
-
985
- /** WebSocket endpoint */
986
- readonly url: string;
987
- /** Whether the connection is open */
988
- readonly connected: boolean;
989
-
990
- /**
991
- * Subscribe to a channel; connects on the first subscription
992
- * @param channel - Channel name
993
- * @param params - Channel parameters
994
- * @param handler - Receives the snapshot (again after every reconnect), the changes, and `{type: 'error'}` if the
995
- * server rejects the subscription
996
- * @returns Unsubscribe function
997
- */
998
- subscribe(channel: 'contract' | 'ticker' | 'account' | 'trades' | 'depth' | 'candles', params: {address?: string, market?: string, depth?: number, step?: string, resolution?: number | string, limit?: number}, handler: (message: StreamMessage) => void): () => void;
999
-
1000
- /** Close the connection and drop every subscription */
1001
- close(): void;
1002
- }
1003
-
1004
- /** Token state for allowance calculation, token balances, and current ledger */
1005
- export declare class TokenBalance {
1006
- /** @param options - `spender` is the AXIS contract */
1007
- constructor(options: {rpcUrl: string, networkPassphrase: string, spender: string, server?: rpc.Server});
1008
-
1009
- /**
1010
- * Allowance `owner` granted to the AXIS contract on a token, 0 when expired
1011
- * @param token - Token contract address
1012
- * @param owner - Token holder address
1013
- * @throws If the simulation fails
1014
- */
1015
- getAllowance(token: string, owner: string): Promise<bigint>;
1016
- /**
1017
- * Token balance of an account
1018
- * @param token - Token contract address
1019
- * @param owner - Token holder address
1020
- * @returns 0 if the account holds no balance entry
1021
- */
1022
- getBalance(token: string, owner: string): Promise<bigint>;
1023
- /** Latest closed ledger sequence */
1024
- getLatestLedger(): Promise<number>;
1025
- }
1026
-
1027
- /** Account signing contract calls */
1028
- export interface Signer {
1029
- /** Transaction source account */
1030
- publicKey: string;
1031
- signTransaction: SignTransactionCallback;
1032
- }
1033
-
1034
- export interface AxisOptions {
1035
- /** Aggregator REST API URL */
1036
- apiUrl: string;
1037
- /** AXIS contract address */
1038
- contractId: string;
1039
- /** Aggregator push API URL (`<apiUrl>/ws` with the `ws(s)` scheme by default) */
1040
- wsUrl?: string;
1041
- /** Stellar RPC URL, required to trade; also reads allowances and the ledger when the push API does not provide them */
1042
- rpcUrl?: string;
1043
- /** Network passphrase (Pubnet by default) */
1044
- networkPassphrase?: string;
1045
- /** Transaction fee */
1046
- fee?: string;
1047
- /** Default signer settings for contract operations (`keepalive`, `requote`, `subsidize`) */
1048
- signer?: Signer;
1049
- /** REST polling period while the push connection is down, in milliseconds (15 s by default) */
1050
- fallbackPollInterval?: number;
1051
- /** WebSocket implementation (the global one by default) */
1052
- WebSocket?: typeof WebSocket;
1053
- }
1054
-
1055
- /**
1056
- * High-level AXIS DEX state.
1057
- * Emits:
1058
- * - `change` - anything in the contract state changed
1059
- * - `frozen` `boolean` - the frozen state toggled
1060
- * - `config` {@link ContractInfoConfig} - contract configuration changed
1061
- * - `market` `{market: AxisMarket, created: boolean}` - a market was opened or updated
1062
- * - `connection` `boolean` - WebSocket push connection opened or dropped
1063
- * - `ledger` `number` - new ledger processed by the indexer
1064
- */
1065
- export declare class Axis extends Emitter {
1066
- constructor(options: AxisOptions);
1067
-
1068
- /** Aggregator REST client */
1069
- readonly api: AxisApiClient;
1070
- /** Aggregator WebSocket API client */
1071
- readonly stream: AxisStreamClient;
1072
- /** Token balance wrappers; undefined without `rpcUrl` */
1073
- readonly tokenBalances: TokenBalance | undefined;
1074
- /** Contract address of the native XLM token */
1075
- readonly nativeAsset: string;
1076
- /** Last known ledger (0 until pushed) */
1077
- readonly ledger: number;
1078
- /** When `ledger` was last updated, UNIX milliseconds */
1079
- readonly ledgerTime: number;
1080
- /** Whether trading is suspended */
1081
- readonly frozen: boolean;
1082
- /** Contract configuration, undefined until loaded */
1083
- readonly config: ContractInfoConfig | undefined;
1084
- /** Available AXIS markets, by the canonical key `a/b` */
1085
- readonly markets: Map<string, AxisMarket>;
1086
- /** 24h ticker entries by the canonical key, filled while `subscribeTicker` runs */
1087
- readonly tickers: Map<string, TickerEntry>;
1088
- /** Whether the contract state loaded */
1089
- readonly loaded: boolean;
1090
-
1091
- /** Load the contract state and track its changes */
1092
- connect(): Promise<Axis>;
1093
- /** Current ledger sequence: the pushed one while connected and fresh, otherwise read over RPC */
1094
- getLedger(): Promise<number>;
1095
- /**
1096
- * Get market of the asset pair, in either order
1097
- * @param asset1 - Token contract address
1098
- * @param asset2 - Token contract address
1099
- */
1100
- getMarket(asset1: string, asset2: string): AxisMarket | undefined;
1101
- /**
1102
- * Get live order by id, from a tracked account or the Aggregator
1103
- * @returns Undefined if not found (filled, removed, expired)
1104
- */
1105
- getOrder(id: bigint | string): Promise<AccountOrder | undefined>;
1106
- /**
1107
- * Trader wrapper tracking the orders and allowances for an account (one instance per account address)
1108
- * @param address - Trader address
1109
- * @param options - Transaction signing callback
1110
- */
1111
- account(address: string, options?: {signTransaction?: SignTransactionCallback}): AxisAccount;
1112
- /**
1113
- * Stream the 24h ticker of every market (canonical orientation).
1114
- * Sends a full snapshot, then updates caused by trades
1115
- * @returns Unsubscribe function
1116
- */
1117
- subscribeTicker(callback?: (ticker: Ticker24hResult) => void): () => void;
1118
- /**
1119
- * Extend the contract instance and code lifetime
1120
- * @param signer - Transaction source, the default signer by default
1121
- */
1122
- keepalive(signer?: Signer): Promise<void>;
1123
- /** Stop following the contract state and tracked accounts */
1124
- close(): void;
1125
- }
1126
-
1127
- /** Derive the push API endpoint from the REST API URL */
1128
- export declare function toWsUrl(apiUrl: string): string;
1129
-
1130
- /** DEX Market; assets in the contract canonical order */
1131
- export declare class AxisMarket {
1132
- /** Base asset */
1133
- readonly a: string;
1134
- /** Quote asset */
1135
- readonly b: string;
1136
- /** Canonical market key `a/b` */
1137
- readonly key: string;
1138
- /** Base asset (`a`) */
1139
- readonly base: string;
1140
- /** Quote asset (`b`) */
1141
- readonly quote: string;
1142
- /** Creation timestamp (first oracle check) (UNIX milliseconds) */
1143
- readonly created: number;
1144
- /** Last oracle check (UNIX milliseconds) */
1145
- readonly refreshed: number;
1146
- /** Last 24h ticker entry of the market, available while {@link Axis.subscribeTicker} runs */
1147
- readonly ticker: TickerEntry | undefined;
1148
-
1149
- /** Check whether the asset is one of the market assets */
1150
- has(asset: string): boolean;
1151
- /**
1152
- * The other market asset
1153
- * @param asset - One of the market assets
1154
- * @throws If the asset does not belong to the market
1155
- */
1156
- counter(asset: string): string;
1157
- /**
1158
- * Re-check both market assets against the price oracle and cache oracle prices
1159
- * @param signer - Transaction source, the {@link Axis} signer by default
1160
- */
1161
- requote(signer?: Signer): Promise<Market | undefined>;
1162
- /**
1163
- * Extend oracle price feeds access for the market
1164
- * @param params - `amount` of fee tokens to burn
1165
- * @returns New access expiration UNIX timestamps (in seconds) for each oracle-listed asset
1166
- */
1167
- subsidize(params: {amount: bigint, sponsor?: string, signer?: Signer}): Promise<bigint[]>;
1168
- /**
1169
- * Orderbook depth data with given precision
1170
- * @param params - `base` is the base asset (`a` by default), `step` the price step (automatic by default)
1171
- */
1172
- getDepth(params?: {base?: string, depth?: number, step?: string, limit?: number}): Promise<OrderbookDepth>;
1173
- /**
1174
- * Stream the orderbook depth.
1175
- * Returns a snapshot, then updates on book changes
1176
- * @returns Unsubscribe function
1177
- */
1178
- subscribeDepth(params: {base?: string, depth?: number, step?: string, limit?: number}, callback: (depth: OrderbookDepth) => void): () => void;
1179
- /**
1180
- * Stream the market trades.
1181
- * Returns a snapshot, then updates on trades
1182
- * @param callback - Trades and whether they are the snapshot
1183
- * @returns Unsubscribe function
1184
- */
1185
- subscribeTrades(callback: (trades: ApiTrade[], snapshot: boolean) => void): () => void;
1186
- /**
1187
- * Stream the market candles.
1188
- * Returns a snapshot, then updates on trades
1189
- * @param params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit`
1190
- * the candles in the snapshot (200 by default, at most 200)
1191
- * @param callback - Candles and whether they are the snapshot
1192
- * @returns Unsubscribe function
1193
- */
1194
- subscribeCandles(params: {base?: string, resolution: number | string, limit?: number}, callback: (candles: Candle[], snapshot: boolean) => void): () => void;
1195
- }
1196
-
1197
- /** Open order of a tracked account */
1198
- export interface AccountOrder {
1199
- /** Order id (decimal u128) */
1200
- id: string;
1201
- /** Maker address */
1202
- owner: string;
1203
- /** Sold token */
1204
- selling: string;
1205
- /** Bought token */
1206
- buying: string;
1207
- /** Market key (canonical `a/b`) */
1208
- market: string;
1209
- /** Current status */
1210
- status: 'ACTIVE' | 'FILLED' | 'CANCELED' | 'EXPIRED';
1211
- /** `buying` per 1 `selling`, contract scale (18 decimals) */
1212
- price: bigint;
1213
- /** Amount of `selling` left */
1214
- amount: bigint;
1215
- /** Amount of `selling` at creation */
1216
- quote: bigint;
1217
- /** Expiration UNIX timestamp in seconds, 0 = none */
1218
- expires: number;
1219
- /** Creation time, UNIX milliseconds */
1220
- created: number;
1221
- /** Last change, UNIX milliseconds */
1222
- updated: number;
1223
- /** Paging cursor (undefined for unconfirmed local orders) */
1224
- cursor?: bigint;
1225
- /** Share of the account budget in `selling` that backs the order; null when unknown */
1226
- backed: bigint | null;
1227
- /** `backed / amount` (0..1), null when unknown */
1228
- backedPct: number | null;
1229
- /** The backing is not confirmed yet */
1230
- backingPending: boolean;
1231
- /** Filled share of the initial amount (0..1) */
1232
- filledPct: number;
1233
- /** Created by this client, not reported by the indexer yet */
1234
- pending: boolean;
1235
- }
1236
-
1237
- /** Balance and allowance of the account in a token, as tracked by the indexer */
1238
- export interface AccountBacking {
1239
- asset: string;
1240
- /** Spendable amount (balance minus reserve and liabilities) */
1241
- balance: bigint;
1242
- /** Allowance granted to the AXIS contract */
1243
- allowance: bigint;
1244
- /** Ledger sequence the allowance lives until */
1245
- liveUntil: number;
1246
- /** Whether the account can send and receive the token */
1247
- authorized: boolean;
1248
- /** min(balance, allowance), 0 when unauthorized or expired */
1249
- budget: bigint;
1250
- /** Last load, UNIX milliseconds (0 = not loaded) */
1251
- updated: number;
1252
- /** Last skipped fill of an order selling the token, UNIX milliseconds (0 = none) */
1253
- skipped: number;
1254
- /** A reload confirming the latest change is due */
1255
- pending: boolean;
1256
- }
1257
-
1258
- export interface AccountAllowance {
1259
- asset: string;
1260
- /** Whether the backing is tracked and loaded */
1261
- known: boolean;
1262
- balance?: bigint;
1263
- allowance?: bigint;
1264
- liveUntil?: number;
1265
- authorized?: boolean;
1266
- pending?: boolean;
1267
- /** min(balance, allowance) */
1268
- available?: bigint;
1269
- /** Remaining amount of the open orders selling the token */
1270
- committed: bigint;
1271
- }
1272
-
1273
- export interface AccountFill {
1274
- /** Order after the fill */
1275
- order: AccountOrder;
1276
- /** Amount of `selling` delivered */
1277
- sold: bigint;
1278
- /** Amount of `buying` received */
1279
- bought: bigint;
1280
- /** Taker address */
1281
- taker: string;
1282
- /** Trade id */
1283
- trade: string;
1284
- /** Trade time, UNIX milliseconds */
1285
- ts: number;
1286
- /** Whether the order is still open */
1287
- partial: boolean;
1288
- }
1289
-
1290
- export interface AccountTradeParams {
1291
- /** Token sent */
1292
- selling: string;
1293
- /** Token received */
1294
- buying: string;
1295
- /** `selling` amount of a sell, `buying` amount of a buy (raw units) */
1296
- amount: bigint | string;
1297
- /** Limit price, contract scale; omitted for a market order */
1298
- price?: bigint | string;
1299
- /** `Limit` by default, `Fill` for a market order */
1300
- kind?: OrderKind;
1301
- /** Expiration UNIX timestamp (seconds) of the resting remainder */
1302
- expires?: number;
1303
- /** Counter orders to cross, looked up automatically when omitted */
1304
- orders?: Array<bigint | string>;
1305
- /** Explicit approval (`null` for none), planned automatically when omitted */
1306
- approve?: Approval | null;
1307
- }
1308
-
1309
- export interface AccountTradeResult {
1310
- /** Amount of `selling` sent */
1311
- sold: bigint;
1312
- /** Amount of `buying` received */
1313
- bought: bigint;
1314
- /** ID of the order created for a limit remainder */
1315
- orderId?: string;
1316
- /** The created order (unconfirmed until the indexer reports it) */
1317
- order?: AccountOrder;
1318
- /** Approval granted with the trade */
1319
- approve?: Approval;
1320
- }
1321
-
1322
- export interface AccountSwapParams {
1323
- /** Token sent */
1324
- selling: string;
1325
- /** Token received */
1326
- buying: string;
1327
- /** `selling` amount of a sell, `buying` amount of a buy (raw units) */
1328
- amount: bigint | string;
1329
- /** `Sell` by default */
1330
- direction?: TradeDirection;
1331
- /** Price tolerance as a fraction (0.005 = 0.5%), 0 by default */
1332
- slippage?: number;
1333
- }
1334
-
1335
- /** Market filter: a market key `x/y`, an {@link AxisMarket} or a pair of assets, in any order */
1336
- export type AccountMarketFilter = string | {a: string, b: string} | string[];
1337
-
1338
- /**
1339
- * Trader wrapper that tracks every open order of an account across all markets and the account backing.
1340
- * Create it with {@link Axis.account}.
1341
- * Emits:
1342
- * - `ready` - the account state was loaded
1343
- * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
1344
- * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
1345
- * - `fill` {@link AccountFill} - an order was partially filled
1346
- * - `filled` {@link AccountFill} - an order was filled in full
1347
- * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
1348
- * - `cancel` {@link AccountOrder} - an order was removed by the owner
1349
- * - `expire` {@link AccountOrder} - an order expired
1350
- * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
1351
- * - `order` `{action, order, fill?}` - any order change
1352
- * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
1353
- * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
1354
- * - `trade` {@link ApiTrade} - the account performed a trade
1355
- * - `swap` - the account performed a swap
1356
- * - `change` - the open orders or the backing changed
1357
- * - `error` `Error` - the push API rejected the account subscription
1358
- */
1359
- export declare class AxisAccount extends Emitter {
1360
- /** Trader address */
1361
- readonly address: string;
1362
- /** Wallet signing callback, required to trade */
1363
- signTransaction?: SignTransactionCallback;
1364
- /** Open orders by id */
1365
- readonly orders: Map<string, AccountOrder>;
1366
- /** Account backing by token contract id */
1367
- readonly backing: Map<string, AccountBacking>;
1368
- /** Resolves once the account state has been loaded */
1369
- readonly ready: Promise<void>;
1370
- /** Whether the account state has been loaded */
1371
- readonly loaded: boolean;
1372
- /** Spendable balances in every tracked token by token contract id */
1373
- readonly balances: Map<string, bigint>;
1374
- /** Whether the account exists on the ledger; undefined until its XLM backing is known */
1375
- readonly funded: boolean | undefined;
1376
-
1377
- /**
1378
- * Get spendable balance of the account in a token
1379
- * @param asset - Token contract id
1380
- * @returns Undefined if not tracked
1381
- */
1382
- getBalance(asset: string): bigint | undefined;
1383
- /**
1384
- * Retrieve open orders, newest first, including unconfirmed ones created by this client
1385
- * @param filter - `market` is an {@link AxisMarket}, a market key or a pair of assets in any order
1386
- */
1387
- getOrders(filter?: {market?: AccountMarketFilter, selling?: string, buying?: string}): AccountOrder[];
1388
- /** Get open order by id */
1389
- getOrder(id: bigint | string): AccountOrder | undefined;
1390
- /**
1391
- * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must
1392
- * cover)
1393
- * @param asset - Token contract id
1394
- */
1395
- committed(asset: string): bigint;
1396
- /**
1397
- * Get balance, allowance and commitments of the account in a token
1398
- * @param asset - Token contract id
1399
- */
1400
- getAllowance(asset: string): AccountAllowance;
1401
- /**
1402
- * Sell tokens creating a limit remainder order if not executed in full (market order without `price`)
1403
- * @param params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
1404
- */
1405
- sell(params: AccountTradeParams): Promise<AccountTradeResult>;
1406
- /**
1407
- * Buy tokens creating a limit remainder order if not executed in full (market order without `price`)
1408
- * @param params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
1409
- */
1410
- buy(params: AccountTradeParams): Promise<AccountTradeResult>;
1411
- /**
1412
- * Change the amount, price or expiration of open orders (omitted fields keep their current values); the allowance
1413
- * is raised as needed
1414
- * @returns Updated order ids
1415
- */
1416
- update(updates: Array<{id: bigint | string, amount?: bigint, price?: bigint, expires?: number}>): Promise<bigint[]>;
1417
- /** Cancel open orders */
1418
- cancel(ids: Array<bigint | string>): Promise<void>;
1419
- /**
1420
- * Cancel all open orders, optionally of one market
1421
- * @returns Canceled order ids
1422
- */
1423
- cancelAll(filter?: {market?: AccountMarketFilter}): Promise<string[]>;
1424
- /**
1425
- * Fill an open order against the book while keeping profits from price inefficiencies
1426
- * @param takerOrderId - Order acting as the taker
1427
- * @param orders - Counter orders, looked up automatically when omitted
1428
- */
1429
- crossfill(takerOrderId: bigint | string, orders?: Array<bigint | string>): Promise<{sold: bigint, bought: bigint, surplus: bigint}>;
1430
- /** Swap across one or several markets along the best route found by the Aggregator */
1431
- swap(params: AccountSwapParams): Promise<{sold: bigint, bought: bigint, approve?: Approval}>;
1432
- /**
1433
- * Compute approval for a call
1434
- * @param asset - Token contract id
1435
- * @param required - Max amount the call may spend
1436
- * @returns Undefined when the current allowance covers the call
1437
- */
1438
- planApproval(asset: string, required: bigint): Promise<{amount: bigint, liveUntil: number} | undefined>;
1439
- /** Reload current account state from the REST API */
1440
- refresh(): Promise<void>;
1441
- /** Stop tracking this account */
1442
- close(): void;
1443
- }
1444
-
1445
- /** Convert an API order to the client form (bigint amounts and prices, numeric timestamps) */
1446
- export declare function parseApiOrder(raw: ApiOrder): AccountOrder;
1
+ import type {rpc} from "@stellar/stellar-sdk";
2
+
3
+ /** Trading order type */
4
+ export enum OrderKind {
5
+ /** Execute trade, create a limit order if not executed in full */
6
+ Limit = 1,
7
+ /** Execute trade without creating a limit order */
8
+ Fill = 2,
9
+ /** Execute trade, cancel if was not executed in full */
10
+ FillOrKill = 3,
11
+ }
12
+
13
+ /** Trade direction instructions */
14
+ export enum TradeDirection {
15
+ Sell = 1,
16
+ Buy = 2,
17
+ }
18
+
19
+ /** Order properties, stored on-chain */
20
+ export interface Order {
21
+ /** Amount left to sell */
22
+ amount: bigint;
23
+ /** Buying token address */
24
+ buying: string;
25
+ /** Expiration UNIX timestamp in seconds (0 = no expiration) */
26
+ expires: bigint;
27
+ /** Unique order identifier, derived from the owner and the client nonce */
28
+ id: bigint;
29
+ /** Maker address */
30
+ owner: string;
31
+ /** Order price (`buying` per 1 `selling`, 18 decimals) */
32
+ price: bigint;
33
+ /** Selling token address */
34
+ selling: string;
35
+ }
36
+
37
+ /** Token allowance granted to the contract as part of the call */
38
+ export interface Approval {
39
+ /** Token the allowance is granted on */
40
+ asset?: string;
41
+ /** Absolute allowance amount (0 revokes the approval) */
42
+ amount: bigint;
43
+ /** Ledger sequence the allowance lives until */
44
+ liveUntil: number;
45
+ }
46
+
47
+ /** New amount, price and expiration for an existing order */
48
+ export interface OrderUpdate {
49
+ /** Order id */
50
+ id: bigint;
51
+ /** New amount to sell, 0 removes the order */
52
+ amount: bigint;
53
+ /** New order price (ignored for a removal) */
54
+ price: bigint;
55
+ /** New expiration UNIX timestamp (in seconds), 0 or omitted = no expiration */
56
+ expires?: bigint | number;
57
+ }
58
+
59
+ /** Contract configuration */
60
+ export interface Config {
61
+ /** Address of the account allowed to freeze the contract and change the configuration */
62
+ safety_admin: string;
63
+ /** Oracle contract address */
64
+ oracle: string;
65
+ /** Days of price feeds a new market must buy (0 opens markets without a fee) */
66
+ listing_min_days: number;
67
+ /** Amount of oracle fee tokens paid by the market creator to provision the oracle price feeds (the oracle daily fee x `listing_min_days`) */
68
+ market_listing_fee: bigint;
69
+ /** Minimum trade value in USD, with 7 decimals precision (0 disables the limit) */
70
+ min_trade_size: bigint;
71
+ /** Expected average ledger close time in seconds, used to convert entry lifetimes into ledgers */
72
+ ledger_time: number;
73
+ }
74
+
75
+ /** Market asset descriptor */
76
+ export interface MarketSide {
77
+ /** Token contract address */
78
+ asset: string;
79
+ /** Whether the asset is quoted by the oracle (with token decimals the valuation can handle) */
80
+ listed: boolean;
81
+ /** Token decimals (fetched only for listed assets) */
82
+ decimals: number;
83
+ }
84
+
85
+ /** Market record, stored on-chain */
86
+ export interface Market {
87
+ /** Base asset, the first of the pair in canonical order */
88
+ base: MarketSide;
89
+ /** Quote asset, the second of the pair in canonical order */
90
+ quote: MarketSide;
91
+ /** Creation UNIX timestamp in seconds */
92
+ created: bigint;
93
+ }
94
+
95
+ /** Orderbook `trade` event, one per fill */
96
+ export interface TradeContractEvent {
97
+ /** Asset sold by the taker (topic) */
98
+ selling: string;
99
+ /** Asset bought by the taker (topic) */
100
+ buying: string;
101
+ /** Maker order id */
102
+ order: bigint;
103
+ /** Trader account address */
104
+ taker: string;
105
+ /** Seller account address */
106
+ maker: string;
107
+ /** Sold tokens amount */
108
+ sold: bigint;
109
+ /** Bought tokens amount */
110
+ bought: bigint;
111
+ /** Order amount left after the fill (0 = removed) */
112
+ left: bigint;
113
+ }
114
+
115
+ /** Orderbook `swap` event, one per call */
116
+ export interface SwapContractEvent {
117
+ /** Asset sold by the trader (topic) */
118
+ selling: string;
119
+ /** Asset received by the trader (topic) */
120
+ buying: string;
121
+ /** Trader account address */
122
+ trader: string;
123
+ /** Amount of `selling` tokens sold */
124
+ sold: bigint;
125
+ /** Amount of `buying` tokens received */
126
+ bought: bigint;
127
+ }
128
+
129
+ /** Orderbook `new` event, an order created */
130
+ export interface OrderCreatedContractEvent {
131
+ /** Selling asset address (topic) */
132
+ selling: string;
133
+ /** Buying asset address (topic) */
134
+ buying: string;
135
+ /** Unique order identifier */
136
+ id: bigint;
137
+ /** Maker address */
138
+ owner: string;
139
+ /** Order price */
140
+ price: bigint;
141
+ /** Current amount */
142
+ amount: bigint;
143
+ /** Expiration UNIX timestamp in seconds (0 = no expiration) */
144
+ expires: bigint;
145
+ }
146
+
147
+ /** Orderbook `mod` event, an order changed outside a fill */
148
+ export interface OrderUpdatedContractEvent {
149
+ /** Unique order identifier */
150
+ id: bigint;
151
+ /** Order price */
152
+ price: bigint;
153
+ /** Current amount (0 = removed) */
154
+ amount: bigint;
155
+ /** Expiration UNIX timestamp in seconds (0 = no expiration) */
156
+ expires: bigint;
157
+ }
158
+
159
+ /**
160
+ * Orderbook `skip` event, a listed order its maker could not settle: backing short of the fill, a missing or
161
+ * deauthorized trustline for the taker's asset, or the maker's asset could not be collected. The order is left
162
+ * unchanged. For `crossfill` it also flags a taker order its owner cannot back or be paid for
163
+ */
164
+ export interface OrderSkippedContractEvent {
165
+ /** Order id */
166
+ order: bigint;
167
+ }
168
+
169
+ /** Orderbook `refresh` event, a market checked against the oracle (topics: `refresh`, `base`, `quote`, no data) */
170
+ export interface MarketRefreshContractEvent {
171
+ /** Base market asset (canonical order, topic) */
172
+ base: string;
173
+ /** Quote market asset (canonical order, topic) */
174
+ quote: string;
175
+ }
176
+
177
+ /** `freeze` event */
178
+ export interface FreezeContractEvent {
179
+ /** Whether trading is blocked after the call */
180
+ frozen: boolean;
181
+ }
182
+
183
+ /**
184
+ * `config` update notification event (constructor, `delegate`, `set_oracle`, `set_floor`, `set_listing_min_days`,
185
+ * `set_ledger_time`)
186
+ */
187
+ export interface ConfigChangedContractEvent {
188
+ /** Contract configuration after the call */
189
+ config: Config;
190
+ }
191
+
192
+ /** A trade step in a multi-market swap path */
193
+ export interface TradeStep {
194
+ /** Asset to buy at this step */
195
+ asset: string;
196
+ /** Maker order IDs to match */
197
+ orders: Array<bigint>;
198
+ }
199
+
200
+ /** Standard contract errors */
201
+ export declare const ContractErrors: {
202
+ 701: {message: "NotAuthorized"};
203
+ 702: {message: "InsufficientBalance"};
204
+ 703: {message: "InsufficientAllowance"};
205
+ 704: {message: "InvalidMatch"};
206
+ 705: {message: "InvalidPrice"};
207
+ 706: {message: "InvalidAmount"};
208
+ 707: {message: "InvalidExpiration"};
209
+ 708: {message: "CannotReceive"};
210
+ 709: {message: "NotFilled"};
211
+ 710: {message: "OrderNotFound"};
212
+ 711: {message: "OrderExists"};
213
+ 712: {message: "IntermediaryCannotReceive"};
214
+ 720: {message: "OrderSizeTooSmall"};
215
+ 721: {message: "AssetsNotVerifiedByOracle"};
216
+ 722: {message: "AssetPriceOracleFetchFailed"};
217
+ 723: {message: "InvalidOracleConfig"};
218
+ 730: {message: "Frozen"};
219
+ 740: {message: "Overflow"};
220
+ }
221
+
222
+ /** Errors of the Stellar Asset Contract, raised by the token transfers a trading call settles with */
223
+ export declare const TokenErrors: {
224
+ 1: {message: "InternalError"};
225
+ 2: {message: "OperationNotSupportedError"};
226
+ 3: {message: "AlreadyInitializedError"};
227
+ 4: {message: "UnauthorizedError"};
228
+ 5: {message: "AuthenticationError"};
229
+ 6: {message: "AccountMissingError"};
230
+ 7: {message: "AccountIsNotClassic"};
231
+ 8: {message: "NegativeAmountError"};
232
+ 9: {message: "AllowanceError"};
233
+ 10: {message: "BalanceError"};
234
+ 11: {message: "BalanceDeauthorizedError"};
235
+ 12: {message: "OverflowError"};
236
+ 13: {message: "TrustlineMissingError"};
237
+ }
238
+
239
+ /**
240
+ * Compute the id of the order `owner` creates with `nonce`.
241
+ * Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`
242
+ * interpreted as a big-endian `u128` (the full 128 bits, no mask).
243
+ * @param owner - Order owner address (account or contract)
244
+ * @param nonce - Client-chosen u64 nonce
245
+ * @returns u128 order id
246
+ */
247
+ export declare function orderId(owner: string, nonce: bigint | number | string): bigint;
248
+
249
+ export interface ClientInitializationParams {
250
+ /** Public key of the account that will interact with the contract */
251
+ publicKey: string;
252
+ /** Callback for signing transactions generated by the client */
253
+ signTransaction: SignTransactionCallback;
254
+ /** URL of the RPC server */
255
+ rpcUrl: string;
256
+ /** DEX contract ID */
257
+ contractId: string;
258
+ /** Network passphrase (Pubnet passphrase by default) */
259
+ networkPassphrase?: string;
260
+ /** Inclusion fee bid in stroops (100,000 = 0.01 XLM by default), the simulated resource fee is added on top */
261
+ fee?: string;
262
+ /** Declare every supplied order id, and the balances and allowances of the makers behind them, in the read-write footprint of trading transactions (enabled by default) */
263
+ autoFootprint?: boolean;
264
+ }
265
+
266
+ /**
267
+ * Callback for signing transactions generated by the client (`@stellar/stellar-sdk` 17 contract client shape)
268
+ * @param xdr - Transaction XDR to sign
269
+ * @param opts - Signing options passed by the SDK
270
+ * @returns Signed transaction response
271
+ */
272
+ export type SignTransactionCallback = (
273
+ xdr: string,
274
+ opts?: {networkPassphrase?: string; address?: string; submit?: boolean; submitUrl?: string}
275
+ ) => Promise<{signedTxXdr: string; signerAddress?: string; error?: unknown}>;
276
+
277
+ export interface TradeArguments {
278
+ /** Trading order behavior */
279
+ kind: OrderKind,
280
+ /** Trader address */
281
+ trader: string;
282
+ /** Tokens amount */
283
+ amount: bigint;
284
+ /** Selling token address */
285
+ selling: string;
286
+ /** Buying token address */
287
+ buying: string;
288
+ /** Price a trader willing to accept */
289
+ price: bigint;
290
+ /** List of order IDs to match before creating the order on-chain */
291
+ orders?: Array<bigint>;
292
+ /** Expiration UNIX timestamp (in seconds) of the order created for a `Limit` remainder, 0 or omitted = no expiration */
293
+ expires?: bigint | number;
294
+ /** Optional allowance granted to the contract before trading (on `selling` unless `asset` is set) */
295
+ approve?: Approval;
296
+ }
297
+
298
+ export interface SellTradeArguments extends TradeArguments {
299
+ /** Amount of `selling` tokens to sell */
300
+ amount: bigint;
301
+ /** Price a trader willing to accept, minimum `buying` tokens per 1 `selling` */
302
+ price: bigint;
303
+ }
304
+
305
+ export interface BuyTradeArguments extends TradeArguments {
306
+ /** Amount of `buying` tokens to acquire */
307
+ amount: bigint;
308
+ /** Price a trader willing to accept, maximum `selling` tokens per 1 `buying` */
309
+ price: bigint;
310
+ }
311
+
312
+ /** Simulated trade, nothing signed or submitted */
313
+ export interface TradeEstimate {
314
+ /** Maximum total network fee of the transaction, in stroops (inclusion fee bid plus resource fee) */
315
+ fee: bigint;
316
+ /** Inclusion fee bid, in stroops (the network charges the market rate up to it) */
317
+ inclusionFee: bigint;
318
+ /** Resource fee, in stroops, including the rent of an order created for the remainder */
319
+ resourceFee: bigint;
320
+ /** Expected amount of sold tokens */
321
+ sold: bigint;
322
+ /** Expected amount of bought tokens */
323
+ bought: bigint;
324
+ /** ID of the order the remainder would create */
325
+ orderId?: bigint;
326
+ }
327
+
328
+ /** Swap path and settings */
329
+ export interface SwapArguments {
330
+ /** Trade direction: `Sell` or `Buy` */
331
+ direction: TradeDirection,
332
+ /** Trader address */
333
+ trader: string,
334
+ /** Token address sent by the trader */
335
+ selling: string,
336
+ /** Amount of selling tokens to send (`Sell`) or the maximum to spend (`Buy`) */
337
+ sellingAmount: bigint,
338
+ /** Minimum amount of buying tokens to receive (`Sell`) or the exact amount (`Buy`) */
339
+ buyingAmount: bigint,
340
+ /** Ordered list of the trade route steps */
341
+ path: Array<TradeStep>,
342
+ /** Optional allowance granted to the contract before trading (on `selling` unless `asset` is set) */
343
+ approve?: Approval
344
+ }
345
+
346
+ export interface UpdateArguments {
347
+ /** Orders owner */
348
+ trader: string;
349
+ /** New amount, price and expiration per order */
350
+ updates: Array<OrderUpdate>;
351
+ /** Allowances granted before the backing check, each naming its `asset`; an asset without an approval keeps its current allowance */
352
+ approvals?: Array<Approval & {asset: string}>;
353
+ }
354
+
355
+ export interface SubsidizeArguments {
356
+ /** Address paying for the oracle feeds (and the listing fee of a new market) */
357
+ sponsor: string;
358
+ /** First market asset */
359
+ selling: string;
360
+ /** Second market asset (either order opens the same market) */
361
+ buying: string;
362
+ /** Amount of XRF fee tokens to burn, at least `Config.market_listing_fee` to open a market */
363
+ amount: bigint;
364
+ }
365
+
366
+ /** Smart contract client for trading with AXIS DEX */
367
+ export declare class AxisContractClient {
368
+ constructor(params: ClientInitializationParams);
369
+
370
+ /** Account that signs and pays for the transactions */
371
+ readonly publicKey: string;
372
+
373
+ /**
374
+ * Fetch existing order.
375
+ * @param id - ID of the order to fetch
376
+ * @returns Order fetched from the storage, undefined if not found or expired
377
+ */
378
+ order(id: bigint): Promise<Order | undefined>;
379
+
380
+ /** Fetch contract configuration. */
381
+ loadConfig(): Promise<Config>;
382
+
383
+ /**
384
+ * Check whether the contract is frozen.
385
+ * @returns `true` if contract is frozen (trading and order management operations blocked)
386
+ */
387
+ isFrozen(): Promise<boolean>;
388
+
389
+ /**
390
+ * Fetch market for the given asset pair.
391
+ * @param selling - First market asset
392
+ * @param buying - Second market asset
393
+ * @returns Market record if the market exists
394
+ */
395
+ getMarket(selling: string, buying: string): Promise<Market | undefined>;
396
+
397
+ /**
398
+ * Cancel existing orders, expired ones included. A transaction can process up to 100 orders in one batch.
399
+ * @param trader - Trader address
400
+ * @param ids - IDs of the orders to cancel (non-existent orders are ignored)
401
+ * @throws If trader is not the owner of any existing order in `ids` (works while the contract is frozen)
402
+ */
403
+ cancel(trader: string, ids: Array<bigint>): Promise<void>;
404
+
405
+ /**
406
+ * Update the amount, price, or expiration of several orders in place, or remove them.
407
+ * Orders that no longer exist are skipped; expired orders revived with the new expiration.
408
+ * A zero amount removes the order, expired ones included. An updated order's entry lifetime is extended to cover its expiration +1 day.
409
+ * Approvals and removals work in a frozen contract and on a market without quoted assets.
410
+ * A transaction can process up to 100 orders in one batch.
411
+ * @returns IDs of the orders to update
412
+ * @throws If the trader does not own an updated order, if order parameters are invalid, if an order is below the minimum value,
413
+ * if the new amounts are not backed by the trader's balance and allowance, an update changes an order on the frozen or not-quoted market
414
+ */
415
+ update(params: UpdateArguments): Promise<Array<bigint>>;
416
+
417
+ /**
418
+ * Fill an existing order against matching orders from the orderbook. Profits from inefficiencies go to the trader.
419
+ * @param trader - Trader address
420
+ * @param takerOrderId - ID of the order that serves as a taker
421
+ * @param orders - List of order IDs to match against
422
+ * @returns Amount the taker order sold, amount the makers delivered, surplus paid to the trader.
423
+ * @throws If the taker order does not exist or has expired, if the trader cannot receive the bought asset, if the
424
+ * contract cannot hold the bought asset, if the contract is frozen.
425
+ */
426
+ crossfill(trader: string, takerOrderId: bigint, orders: Array<bigint>): Promise<[bigint, bigint, bigint]>;
427
+
428
+ /**
429
+ * Trade with DEX and create a buy limit order if the quote not executed in full.
430
+ * @returns Amount of sold and bought tokens, ID of the newly created order if any
431
+ * @throws If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
432
+ * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
433
+ * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
434
+ */
435
+ buy(params: BuyTradeArguments): Promise<[bigint, bigint, bigint | undefined]>;
436
+
437
+ /**
438
+ * Trade with DEX and create a sell limit order if the quote not executed in full.
439
+ * @returns Amount of sold and bought tokens, ID of the newly created order if any
440
+ * @throws If the trader has insufficient balance or allowance, invalid `expires` field specified, a `Limit` trade targets a pair without a market,
441
+ * no reference price is available, a live order with the same id exists, the trader cannot receive `buying` (`CannotReceive`), or the contract
442
+ * cannot hold `buying` until its issuer authorizes it (`IntermediaryCannotReceive`).
443
+ */
444
+ sell(params: SellTradeArguments): Promise<[bigint, bigint, bigint | undefined]>;
445
+
446
+ /**
447
+ * Simulate a buy trade without signing or submitting it, to show the network fee before the trade.
448
+ * @throws If the simulation fails, for the same reasons as `buy`
449
+ */
450
+ estimateBuy(params: BuyTradeArguments): Promise<TradeEstimate>;
451
+
452
+ /**
453
+ * Simulate a sell trade without signing or submitting it, to show the network fee before the trade.
454
+ * @throws If the simulation fails, for the same reasons as `sell`
455
+ */
456
+ estimateSell(params: SellTradeArguments): Promise<TradeEstimate>;
457
+
458
+ /**
459
+ * Swap tokens across several markets. The contract holds the intermediate hop proceeds only within the call.
460
+ * @returns Amount of sold and bought tokens
461
+ * @throws If the route cannot satisfy the selling/buying amount, if `path` is empty or an amount is invalid,
462
+ * if the contract cannot hold an asset of the path, if the contract is frozen.
463
+ */
464
+ swap(params: SwapArguments): Promise<[bigint, bigint]>;
465
+
466
+ /**
467
+ * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring the archived
468
+ * ones first with a `RestoreFootprint` transaction.
469
+ * @param days - Lifetime in days, 30 by default, at most the network maximum (180 days on mainnet)
470
+ * @returns Ledger sequence both entries live at least until
471
+ * @throws If `days` is invalid, if the instance is not found, if a simulation or a transaction fails
472
+ */
473
+ keepalive(days?: number): Promise<number>;
474
+
475
+ /**
476
+ * Re-check both market assets against the price oracle and cache oracle prices.
477
+ * A cached price is valid for up to 72 hours. A market without quoted assets stops accepting
478
+ * new limit orders; its outstanding orders stay cancellable and fillable. The record and the
479
+ * cached prices are rewritten only when they change. When the simulation writes nothing (the market and the
480
+ * cached prices are current, or the oracle has no newer price), the simulated result is
481
+ * returned and no transaction is submitted.
482
+ * @param selling - First market asset
483
+ * @param buying - Second market asset
484
+ * @returns Updated market record, undefined if the market does not exist
485
+ * @throws If the contract is frozen
486
+ */
487
+ requote(selling: string, buying: string): Promise<Market | undefined>;
488
+
489
+ /**
490
+ * Extend oracle price feeds access for a market, creating the market if it does not exist yet.
491
+ * @returns New access expiration UNIX timestamps (in seconds) per oracle-listed asset
492
+ * @throws If `amount` is invalid, if `selling` equals `buying`, if the market does not exist and the amount is below
493
+ * the market listing fee, if neither market asset is quoted by the oracle, if the contract is frozen
494
+ */
495
+ subsidize(params: SubsidizeArguments): Promise<Array<bigint>>;
496
+ }
497
+
498
+ /** Error thrown when the AXIS API responds with a non-success HTTP status */
499
+ export declare class AxisApiError extends Error {
500
+ /**
501
+ * @param message - Error message returned by the API
502
+ * @param status - HTTP status code
503
+ */
504
+ constructor(message: string, status: number);
505
+
506
+ /** HTTP status code associated with the error */
507
+ readonly status: number;
508
+ }
509
+
510
+ export interface QuoteParams {
511
+ /** Asset to sell (`XLM` | `CODE:Issuer` | `CODE-Issuer` | contractId) */
512
+ sellingAsset: string;
513
+ /** Asset to buy (same format as `sellingAsset`) */
514
+ buyingAsset: string;
515
+ /** Trade amount in stroops (1 unit = 10,000,000 stroops) */
516
+ amount: string | number;
517
+ /** Restrict to the direct market only (no intermediate-asset routes) */
518
+ direct?: boolean;
519
+ /**
520
+ * Highest maker price to cross (requires `direct`), in the units of a hop `worstPrice`: `sellingAsset` per unit of
521
+ * `buyingAsset`, scaled by 10^18. Quotes the crossing of a limit order: orders priced above it are left out and the
522
+ * route may trade less than `amount`
523
+ */
524
+ maxPrice?: bigint | string;
525
+ }
526
+
527
+ export interface QuotePathStep {
528
+ /** Selling asset contract id at this hop */
529
+ selling: string;
530
+ /** Buying asset contract id at this hop */
531
+ buying: string;
532
+ /** Maker order IDs matched at this hop */
533
+ orders: string[];
534
+ /** Highest price among the matched orders (maker `buying` per `selling`, 18 decimals): a trade limit at this price crosses every listed order */
535
+ worstPrice?: string;
536
+ }
537
+
538
+ export interface QuotePath {
539
+ /** Amount sold, in stroops */
540
+ sold: string;
541
+ /** Amount bought, in stroops */
542
+ bought: string;
543
+ /** Ordered list of hops in the route */
544
+ path: QuotePathStep[];
545
+ }
546
+
547
+ export interface QuoteResult {
548
+ /** Base58-encoded quote id */
549
+ id: string;
550
+ /** Quote status */
551
+ status: 'success' | 'unfeasible' | 'rejected';
552
+ /** Trade direction */
553
+ direction: 'strict_send' | 'strict_receive';
554
+ /** Selling asset contract id */
555
+ sellingAsset: string;
556
+ /** Buying asset contract id */
557
+ buyingAsset: string;
558
+ /** Ledger sequence the quote was computed for */
559
+ ledger: number;
560
+ /** Candidate routes ranked by profitability (up to 10) */
561
+ paths: QuotePath[];
562
+ /** Error message (present only if status is not `success`) */
563
+ error?: string;
564
+ }
565
+
566
+ export interface DepthParams {
567
+ /** Market identifier `BASE/QUOTE` */
568
+ market: string;
569
+ /** Percentage band (±) around the center price (0 < depth ≤ 100, default 20) */
570
+ depth?: number;
571
+ /** Price step of the levels, a decimal such as `"0.0005"` (5 significant digits of the mid price by default) */
572
+ step?: string;
573
+ /** Price levels per side (default 100, max 500) */
574
+ limit?: number;
575
+ }
576
+
577
+ export interface OrderbookDepth {
578
+ /** Ledger sequence */
579
+ ledger: number;
580
+ /** UNIX timestamp (seconds) */
581
+ timestamp: number;
582
+ /** Price step of the levels (null for an empty book) */
583
+ step: string | null;
584
+ /** Exact best bid price, before the rounding to levels */
585
+ bestBid: string | null;
586
+ /** Exact best ask price, before the rounding to levels */
587
+ bestAsk: string | null;
588
+ /** `[price, quantity]` pairs sorted descending by price */
589
+ bids: Array<[string, string]>;
590
+ /** `[price, quantity]` pairs sorted ascending by price */
591
+ asks: Array<[string, string]>;
592
+ }
593
+
594
+ export interface CandlesParams {
595
+ /** Market identifier `BASE/QUOTE` */
596
+ market: string;
597
+ /** Lower boundary (UNIX seconds, default 0) */
598
+ from?: number;
599
+ /** Upper boundary (UNIX seconds, defaults to `from + resolution * 200`) */
600
+ to?: number;
601
+ /** Resolution in seconds or alias (`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`12h`,`1d`,`3d`,`1w`,`2w`, default `auto`) */
602
+ resolution?: number | string;
603
+ /** Sort order (default `desc`) */
604
+ order?: 'asc' | 'desc';
605
+ }
606
+
607
+ /** OHLCVT candle row: `[timestamp, open, high, low, close, baseVolume, quoteVolume, tradeCount]` */
608
+ export type Candle = [number, string, string, string, string, string, string, number];
609
+
610
+ export interface TickerEntry {
611
+ /** Market symbol `BASE/QUOTE` */
612
+ symbol: string;
613
+ /** Opening price 24h ago */
614
+ openPrice: string;
615
+ /** Highest price in the 24h window */
616
+ highPrice: string;
617
+ /** Lowest price in the 24h window */
618
+ lowPrice: string;
619
+ /** Most recent trade price */
620
+ lastPrice: string;
621
+ /** 24h base asset volume */
622
+ volume: string;
623
+ /** 24h quote asset volume */
624
+ quoteVolume: string;
625
+ /** 24h price change (percent) */
626
+ change: number;
627
+ /** Volume-weighted average price */
628
+ avgPrice: string;
629
+ /** 24h trade count */
630
+ trades: number;
631
+ }
632
+
633
+ export interface Ticker24hResult {
634
+ /** Ledger sequence */
635
+ ledger: number;
636
+ /** UNIX timestamp (seconds) */
637
+ timestamp: number;
638
+ /** Per-market 24h stats, sorted by trade count descending */
639
+ ticker: TickerEntry[];
640
+ }
641
+
642
+ export interface MarketsParams {
643
+ /** Pagination cursor (`baseAsset-quoteAsset`) */
644
+ cursor?: string;
645
+ /** Max markets to return */
646
+ limit?: number | string;
647
+ }
648
+
649
+ export interface MarketInfo {
650
+ /** Base asset contract id */
651
+ baseAsset: string;
652
+ /** Quote asset contract id */
653
+ quoteAsset: string;
654
+ /** Pagination cursor for this market */
655
+ cursor: string;
656
+ /** Supported order types */
657
+ orderTypes: string[];
658
+ }
659
+
660
+ export interface ContractInfoConfig {
661
+ /** Safety admin address */
662
+ safetyAdmin: string;
663
+ /** Price oracle contract address */
664
+ oracle: string;
665
+ /** Days of price feeds a new market must buy (0 opens markets without a fee) */
666
+ listingMinDays?: number;
667
+ /** Oracle fee tokens a market creator pays to provision the price feeds */
668
+ marketListingFee: string;
669
+ /** Minimum trade value in USD with 7 decimals (0 = disabled) */
670
+ minTradeSize: string;
671
+ /** Expected ledger close time in seconds */
672
+ ledgerTime?: number;
673
+ }
674
+
675
+ export interface ContractInfoMarket {
676
+ /** Base market asset, the first of the pair in canonical order */
677
+ base: string;
678
+ /** Quote market asset, the second of the pair in canonical order */
679
+ quote: string;
680
+ /** Creation timestamp (UTC) */
681
+ created: string;
682
+ /** Last oracle check timestamp (UTC) */
683
+ refreshed: string;
684
+ }
685
+
686
+ /** Contract state tracked by the indexer */
687
+ export interface ContractInfo {
688
+ /** Whether trading is blocked by the safety admin */
689
+ frozen: boolean;
690
+ /** Contract configuration */
691
+ config?: ContractInfoConfig;
692
+ /** Markets opened by `subsidize` */
693
+ markets: ContractInfoMarket[];
694
+ }
695
+
696
+ export interface OrdersParams {
697
+ /** Filter by order owner address */
698
+ owner?: string;
699
+ /** Filter by asset(s) - every listed asset must be one of the order assets (two assets select a pair) */
700
+ asset?: string | string[];
701
+ /** `cursor` of the last order received (its creation position, not the order id) */
702
+ cursor?: string | bigint;
703
+ /** Max orders to return */
704
+ limit?: number | string;
705
+ }
706
+
707
+ export interface OrderHistoryParams {
708
+ /** Filter by order owner address */
709
+ owner?: string;
710
+ /** Asset pair `[base, quote]` (contract ids) */
711
+ pair?: string[];
712
+ /** `cursor` of the last order received (its creation position, not the order id) */
713
+ cursor?: string | bigint;
714
+ /** Max orders to return */
715
+ limit?: number | string;
716
+ }
717
+
718
+ export interface TradesParams {
719
+ /** Filter by trader address */
720
+ trader?: string;
721
+ /** Asset pair `[base, quote]` (contract ids) */
722
+ pair?: string[];
723
+ /** `cursor` of the last record received (the trade or swap id) */
724
+ cursor?: string | bigint;
725
+ /** Max trades to return */
726
+ limit?: number | string;
727
+ }
728
+
729
+ /** Maker backing in the order's selling asset */
730
+ export interface ApiOrderBacking {
731
+ /** Token balance */
732
+ balance: string;
733
+ /** Allowance granted to the AXIS contract */
734
+ allowance: string;
735
+ /** Ledger sequence the allowance lives until */
736
+ liveUntil: number;
737
+ /** Whether the maker can send and receive the token */
738
+ authorized: boolean;
739
+ /** Last load timestamp (UTC) */
740
+ updated?: string;
741
+ /** A reload confirming the latest event is still due: the values may predate it */
742
+ pending?: boolean;
743
+ }
744
+
745
+ /** Tracked backing of an account in a token */
746
+ export interface ApiBacking {
747
+ /** Account address */
748
+ owner: string;
749
+ /** Token contract id */
750
+ asset: string;
751
+ /** Token balance */
752
+ balance: string;
753
+ /** Allowance granted to the AXIS contract */
754
+ allowance: string;
755
+ /** Ledger sequence the allowance lives until */
756
+ liveUntil: number;
757
+ /** Whether the account can send and receive the token */
758
+ authorized: boolean;
759
+ /** Effective budget, min(balance, allowance), 0 when unauthorized or expired */
760
+ budget: string;
761
+ /**
762
+ * Amount the account can still receive (trustline limit minus balance and buying
763
+ * liabilities), omitted when unlimited or unknown
764
+ */
765
+ headroom?: string;
766
+ /** Last load timestamp (UTC) */
767
+ updated?: string;
768
+ /** Last `skip` event of an order selling the token (UTC) */
769
+ skipped?: string;
770
+ /** A reload confirming the latest event is still due */
771
+ pending?: boolean;
772
+ }
773
+
774
+ /** Account state: every live order and the backing per traded asset */
775
+ export interface ApiAccount {
776
+ /** Trader address */
777
+ address: string;
778
+ /** Last processed ledger */
779
+ ledger: number;
780
+ /** Live orders, oldest first */
781
+ orders: ApiOrder[];
782
+ /** Backing by token contract id */
783
+ backing: Record<string, ApiBacking>;
784
+ }
785
+
786
+ /** Serialized order returned by the API */
787
+ export interface ApiOrder {
788
+ /** Order ID (decimal u128) */
789
+ id: string;
790
+ /** Order status: `ACTIVE`, `FILLED`, `CANCELED` (removed by the owner) or `EXPIRED` (archived once past `expires`) */
791
+ status: 'ACTIVE' | 'FILLED' | 'CANCELED' | 'EXPIRED';
792
+ /** Buying asset contract id */
793
+ buying: string;
794
+ /** Selling asset contract id */
795
+ selling: string;
796
+ /** Order price */
797
+ price: string;
798
+ /** Rational price representation */
799
+ rprice: string;
800
+ /** Selling amount at creation */
801
+ quote: string;
802
+ /** Amount left to sell */
803
+ amount: string;
804
+ /** Amount the maker can actually deliver, when the indexer tracks backing */
805
+ backed?: string;
806
+ /** Maker backing details, when the indexer tracks backing */
807
+ backing?: ApiOrderBacking;
808
+ /** Maker address */
809
+ owner: string;
810
+ /** Expiration timestamp (UTC) */
811
+ expires?: string;
812
+ /** Creation timestamp (UTC) */
813
+ created?: string;
814
+ /** Last update timestamp (UTC) */
815
+ updated?: string;
816
+ /** Pagination cursor */
817
+ cursor?: string;
818
+ }
819
+
820
+ /** Serialized swap returned by the API, one per `swap` call */
821
+ export interface ApiSwap {
822
+ /** Record type */
823
+ type: 'swap';
824
+ /** Swap ID */
825
+ id: string;
826
+ /** Trader address */
827
+ trader: string;
828
+ /** Sold asset contract id */
829
+ soldAsset: string;
830
+ /** Bought asset contract id */
831
+ boughtAsset: string;
832
+ /** Sold tokens amount */
833
+ sold: string;
834
+ /** Bought tokens amount */
835
+ bought: string;
836
+ /** Approximate swap price */
837
+ price: string;
838
+ /** Pagination cursor */
839
+ cursor: string;
840
+ /** Swap timestamp (UTC) */
841
+ timestamp: string;
842
+ }
843
+
844
+ /** Serialized trade returned by the API */
845
+ export interface ApiTrade {
846
+ /** Record type */
847
+ type: 'trade';
848
+ /** Trade ID */
849
+ id: string;
850
+ /** Matched order ID */
851
+ order: string;
852
+ /** Taker account address */
853
+ taker: string;
854
+ /** Maker account address */
855
+ maker: string;
856
+ /** Sold asset contract id */
857
+ soldAsset: string;
858
+ /** Bought asset contract id */
859
+ boughtAsset: string;
860
+ /** Sold tokens amount */
861
+ sold: string;
862
+ /** Bought tokens amount */
863
+ bought: string;
864
+ /** Order amount left after the fill */
865
+ left?: string;
866
+ /**
867
+ * The fill of a `crossfill` taker order: `taker` is the caller, paid the surplus, and the amounts mirror the makers'
868
+ * fills of the same call (left out of candles and volume)
869
+ */
870
+ crossfill?: boolean;
871
+ /** Approximate trade price */
872
+ price: string;
873
+ /** Pagination cursor */
874
+ cursor?: string;
875
+ /** Trade timestamp (UTC) */
876
+ timestamp: string;
877
+ }
878
+
879
+ export interface FailuresParams {
880
+ /** Caller of the failed transaction, or a party of the failed transfer */
881
+ account?: string;
882
+ /** Contract function (`trade`, `swap`, `crossfill`, `update`, ...) */
883
+ fn?: string;
884
+ /** `cursor` of the last record received */
885
+ cursor?: string | bigint;
886
+ /** Max records to return (20 by default, at most 500) */
887
+ limit?: number | string;
888
+ }
889
+
890
+ /**
891
+ * Failed AXIS call (made by the transaction or through another contract, the transaction failed
892
+ * or a calling contract caught the failure). It changes no state and blames no party:
893
+ * a token error on a settlement transfer does not tell the payer who could not pay from the recipient who could not be
894
+ * credited (e.g. a full trustline), and in a `crossfill` the makers are paid by the taker order owner, not the caller
895
+ */
896
+ export interface ApiFailure {
897
+ /** Record type */
898
+ type: 'failure';
899
+ /** Record id (position of the transaction plus the index of the failed call) */
900
+ id: string;
901
+ /** Transaction hash */
902
+ txHash: string;
903
+ /** Ledger sequence */
904
+ ledger: number;
905
+ /** Ledger close time (UTC) */
906
+ timestamp: string;
907
+ /** Contract function called */
908
+ fn: string;
909
+ /** The `trader` or `sponsor` argument, the transaction source for other functions */
910
+ caller: string;
911
+ /** Maker order ids listed by the call */
912
+ orders: string[];
913
+ /** Taker order id of a `crossfill` */
914
+ takerOrder?: string;
915
+ /** Operation result code */
916
+ result: string;
917
+ /** The transaction succeeded: a calling contract caught the failed AXIS call */
918
+ caught?: boolean;
919
+ /**
920
+ * `contract`: a contract error (`error`), `transfer`: a token transfer failed (`transfer`, either side may be at
921
+ * fault), `resources`: a resource limit, the refundable fee or an archived entry, `auth`: an authorization failure,
922
+ * `unknown`: no diagnostic events
923
+ */
924
+ reason: 'contract' | 'transfer' | 'resources' | 'auth' | 'unknown';
925
+ /** Contract error that failed the call */
926
+ error?: {contract: string | null, code: number, name?: string};
927
+ /** Token transfer that failed */
928
+ transfer?: {token: string, fn: string, from: string, to: string, amount: string};
929
+ /** Pagination cursor */
930
+ cursor: string;
931
+ }
932
+
933
+ /** HTTP client for the AXIS REST API */
934
+ export declare class AxisApiClient {
935
+ /** @param serverUrl - Base URL of the AXIS API server */
936
+ constructor(serverUrl: string);
937
+
938
+ /** Base URL of the AXIS API server */
939
+ readonly serverUrl: string;
940
+
941
+ /**
942
+ * Price quote and candidate trade routes for selling a fixed amount of the source asset
943
+ * @param params - Quote request parameters
944
+ * @returns Best routes ranked by profitability
945
+ * @throws {AxisApiError} 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough
946
+ * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`
947
+ */
948
+ quoteSell(params: QuoteParams): Promise<QuoteResult>;
949
+
950
+ /**
951
+ * Price quote and candidate trade routes for buying a fixed amount of the destination asset
952
+ * @param params - Quote request parameters
953
+ * @returns Best routes ranked by profitability
954
+ * @throws {AxisApiError} 409 if the server is not ready or routing fails, 400 on invalid parameters. Not enough
955
+ * liquidity resolves with `status: 'unfeasible'`, a frozen contract with `status: 'rejected'`
956
+ */
957
+ quoteBuy(params: QuoteParams): Promise<QuoteResult>;
958
+
959
+ /**
960
+ * Order book depth around the mid price, aggregated into price levels on multiples of `step` (bids rounded down,
961
+ * asks up, so a level price crosses every order in it)
962
+ * @param params - Depth request parameters
963
+ * @returns Aggregated bids and asks
964
+ */
965
+ getDepth(params: DepthParams): Promise<OrderbookDepth>;
966
+
967
+ /**
968
+ * OHLCVT candlestick data (open, high, low, close, base volume, quote volume, trade count)
969
+ * @param params - Candles request parameters
970
+ * @returns Time-bucketed candles, max 200 per response
971
+ */
972
+ getCandles(params: CandlesParams): Promise<Candle[]>;
973
+
974
+ /**
975
+ * 24-hour ticker statistics for every available market
976
+ * @returns Aggregated 24h stats per market
977
+ */
978
+ getTicker24h(): Promise<Ticker24hResult>;
979
+
980
+ /**
981
+ * List all active markets with pagination
982
+ * @param params - Pagination parameters
983
+ * @returns Active markets
984
+ */
985
+ getMarkets(params?: MarketsParams): Promise<MarketInfo[]>;
986
+
987
+ /**
988
+ * Contract state tracked by the indexer: frozen switch, configuration and active markets
989
+ * @returns Contract state
990
+ */
991
+ getContract(): Promise<ContractInfo>;
992
+
993
+ /**
994
+ * Retrieve active orders, filterable by owner or asset
995
+ * @param params - Filter parameters
996
+ * @returns Active orders matching the filter
997
+ */
998
+ getOrders(params?: OrdersParams): Promise<ApiOrder[]>;
999
+
1000
+ /**
1001
+ * Account state tracked by the indexer: every live order of the trader (not paginated) and their backing in each
1002
+ * asset they trade
1003
+ * @param address - Trader address
1004
+ */
1005
+ getAccount(address: string): Promise<ApiAccount>;
1006
+
1007
+ /**
1008
+ * Retrieve a single order by ID
1009
+ * @param id - Order ID
1010
+ * @returns Order (throws AxisApiError with status 404 if not found)
1011
+ */
1012
+ getOrder(id: bigint | string | number): Promise<ApiOrder>;
1013
+
1014
+ /**
1015
+ * Retrieve archived/historical orders
1016
+ * @param params - Filter parameters
1017
+ * @returns Archived orders matching the filter
1018
+ */
1019
+ getOrderHistory(params?: OrderHistoryParams): Promise<ApiOrder[]>;
1020
+
1021
+ /**
1022
+ * Retrieve recent trades and swaps, newest first
1023
+ * @param params - Filter parameters
1024
+ * @returns Recent trades and swaps matching the filter (told apart by `type`)
1025
+ */
1026
+ getTrades(params?: TradesParams): Promise<Array<ApiTrade | ApiSwap>>;
1027
+
1028
+ /**
1029
+ * Failed AXIS calls, newest first (diagnostics: a failure changes no state, and a record never blames a party, see
1030
+ * {@link ApiFailure})
1031
+ * @param params - Filter parameters
1032
+ */
1033
+ getFailures(params?: FailuresParams): Promise<ApiFailure[]>;
1034
+ }
1035
+
1036
+ /** Price scale of the contract (18 decimals) */
1037
+ export declare const PRICE_SCALE: bigint;
1038
+
1039
+ /**
1040
+ * Compare two assets in the contract canonical order
1041
+ * @param a - Token contract address
1042
+ * @param b - Token contract address
1043
+ * @returns Negative if `a` first, positive if `b` first, 0 if equal
1044
+ */
1045
+ export declare function compareAssets(a: string, b: string): number;
1046
+
1047
+ /**
1048
+ * Reorder an asset pair the way the contract stores markets
1049
+ * @param x - Token contract address
1050
+ * @param y - Token contract address
1051
+ * @returns `[a, b]`: `a` is the base, `b` the quote of the canonical market symbol
1052
+ */
1053
+ export declare function canonicalPair(x: string, y: string): [string, string];
1054
+
1055
+ /**
1056
+ * Canonical market key `a/b`
1057
+ * @param a - Token contract address
1058
+ * @param b - Token contract address
1059
+ */
1060
+ export declare function pairKey(a: string, b: string): string;
1061
+
1062
+ /**
1063
+ * Calculate inverted price, rounded down: `floor(10^36 / price)`
1064
+ * @param price - Price in the contract scale
1065
+ */
1066
+ export declare function invertPrice(price: bigint): bigint;
1067
+
1068
+ /**
1069
+ * 24h ticker entry of the market seen in the inverted orientation (`b/a`)
1070
+ * @param entry - Standard ticker entry
1071
+ */
1072
+ export declare function invertTicker(entry: TickerEntry): TickerEntry;
1073
+
1074
+ /**
1075
+ * Parse an AXIS API timestamp (`YYYY-MM-DD HH:mm:ss` UTC)
1076
+ * @returns UNIX milliseconds, 0 when missing or invalid
1077
+ */
1078
+ export declare function parseApiDate(value: string | number | undefined): number;
1079
+
1080
+ /** Allowance lifetime granted with a trade, in ledgers: ~30 days at 5s per ledger (the maximum entry TTL ~180 days) */
1081
+ export declare const APPROVAL_TTL_LEDGERS: number;
1082
+ /** An allowance expiring within this number of ledgers is renewed with the next trade (~1 day) */
1083
+ export declare const APPROVAL_RENEW_LEDGERS: number;
1084
+
1085
+ export interface ApprovalPlanParams {
1086
+ /** Max amount of the selling asset the call may spend */
1087
+ required: bigint;
1088
+ /** Remaining amount of orders in the book selling the asset */
1089
+ committed: bigint;
1090
+ /** Current allowance (0 once expired) */
1091
+ allowance: bigint;
1092
+ /** Current ledger sequence */
1093
+ ledger: number;
1094
+ /** Ledger the current allowance lives until (0 or omitted when unknown) */
1095
+ liveUntil?: number;
1096
+ }
1097
+
1098
+ /**
1099
+ * Decide whether a call needs an in-call approval and adjust it. The approval amount is absolute and one allowance
1100
+ * backs every order selling the token across all markets, so it has to cover this call plus every order selling the
1101
+ * same asset
1102
+ * @returns Approval to pass with the call, undefined when the current allowance already covers it
1103
+ */
1104
+ export declare function planApproval(params: ApprovalPlanParams): {amount: bigint, liveUntil: number} | undefined;
1105
+
1106
+ /**
1107
+ * Max amount of `selling` tokens a buy trade may cost: `ceil(amount × price / 10^18)`
1108
+ * @param amount - Amount of `buying` tokens to acquire
1109
+ * @param price - Limit price (`selling` per 1 `buying`, with AXIS standard price decimals)
1110
+ */
1111
+ export declare function maxQuoteSpend(amount: bigint, price: bigint): bigint;
1112
+
1113
+ /** Minimal event emitter that works in browsers and Node */
1114
+ export declare class Emitter {
1115
+ /**
1116
+ * Subscribe to an event
1117
+ * @returns Unsubscribe function
1118
+ */
1119
+ on(event: string, listener: (...args: any[]) => void): () => void;
1120
+ /**
1121
+ * Subscribe to the next occurrence of an event
1122
+ * @returns Unsubscribe function
1123
+ */
1124
+ once(event: string, listener: (...args: any[]) => void): () => void;
1125
+ /** Unsubscribe from an event */
1126
+ off(event: string, listener: (...args: any[]) => void): void;
1127
+ }
1128
+
1129
+ /** Server message; `type` names the payload, `topic` the subscription it belongs to */
1130
+ export interface StreamMessage {
1131
+ type: string;
1132
+ topic?: string;
1133
+ id?: number;
1134
+ [key: string]: any;
1135
+ }
1136
+
1137
+ export interface StreamClientOptions {
1138
+ /** WebSocket implementation (the global one by default) */
1139
+ WebSocket?: typeof WebSocket;
1140
+ /** Application-level ping period, in milliseconds (20 s by default) */
1141
+ pingInterval?: number;
1142
+ /** First reconnect delay, doubled after each failure (1 s by default) */
1143
+ minReconnectDelay?: number;
1144
+ /** Reconnect delay cap (30 s by default) */
1145
+ maxReconnectDelay?: number;
1146
+ }
1147
+
1148
+ /**
1149
+ * WebSocket client of the AXIS API push channel
1150
+ *
1151
+ * Emits `open`, `close` and `error` (server errors not tied to a subscription).
1152
+ */
1153
+ export declare class AxisStreamClient extends Emitter {
1154
+ /** @param url - WebSocket endpoint, e.g. `wss://demo-api.axis.markets/ws` (testnet) */
1155
+ constructor(url: string, options?: StreamClientOptions);
1156
+
1157
+ /** WebSocket endpoint */
1158
+ readonly url: string;
1159
+ /** Whether the connection is open */
1160
+ readonly connected: boolean;
1161
+
1162
+ /**
1163
+ * Subscribe to a channel; connects on the first subscription
1164
+ * @param params -
1165
+ * Channel parameters
1166
+ * @param handler - Receives the snapshot (again after every reconnect), the
1167
+ * changes, and `{type: 'error'}` if the server rejects the subscription
1168
+ * @returns Unsubscribe function
1169
+ */
1170
+ subscribe(channel: 'contract' | 'ticker' | 'account' | 'trades' | 'depth' | 'candles', params: {address?: string, market?: string, depth?: number, step?: string, resolution?: number | string, limit?: number}, handler: (message: StreamMessage) => void): () => void;
1171
+
1172
+ /** Close the connection and drop every subscription */
1173
+ close(): void;
1174
+ }
1175
+
1176
+ /** Token state for allowance calculation, token balances, and current ledger */
1177
+ export declare class TokenBalance {
1178
+ /** @param options - `spender` is the AXIS contract */
1179
+ constructor(options: {rpcUrl: string, networkPassphrase: string, spender: string, server?: rpc.Server});
1180
+
1181
+ /**
1182
+ * Allowance `owner` granted to the AXIS contract on a token, 0 when expired
1183
+ * @param token - Token contract address
1184
+ * @param owner - Token holder address
1185
+ * @throws If the simulation fails
1186
+ */
1187
+ getAllowance(token: string, owner: string): Promise<bigint>;
1188
+ /**
1189
+ * Token balance of an account
1190
+ * @param token - Token contract address
1191
+ * @param owner - Token holder address
1192
+ * @returns 0 if the account holds no balance entry
1193
+ */
1194
+ getBalance(token: string, owner: string): Promise<bigint>;
1195
+ /** Latest closed ledger sequence */
1196
+ getLatestLedger(): Promise<number>;
1197
+ }
1198
+
1199
+ /** Account signing contract calls */
1200
+ export interface Signer {
1201
+ /** Transaction source account */
1202
+ publicKey: string;
1203
+ signTransaction: SignTransactionCallback;
1204
+ }
1205
+
1206
+ export interface AxisOptions {
1207
+ /** AXIS REST API URL */
1208
+ apiUrl: string;
1209
+ /** AXIS contract address */
1210
+ contractId: string;
1211
+ /** AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default) */
1212
+ wsUrl?: string;
1213
+ /** Stellar RPC URL */
1214
+ rpcUrl?: string;
1215
+ /** Network passphrase (Pubnet by default) */
1216
+ networkPassphrase?: string;
1217
+ /** Transaction fee */
1218
+ fee?: string;
1219
+ /** Default signer settings for contract operations */
1220
+ signer?: Signer;
1221
+ /** REST polling period while the push connection is down, in milliseconds */
1222
+ fallbackPollInterval?: number;
1223
+ /** WebSocket implementation */
1224
+ WebSocket?: typeof WebSocket;
1225
+ }
1226
+
1227
+ /**
1228
+ * High-level AXIS DEX state
1229
+ *
1230
+ * Emits:
1231
+ * - `change` - anything in the contract state changed
1232
+ * - `frozen` `boolean` - the frozen state toggled
1233
+ * - `config` {ContractInfoConfig} - contract configuration changed
1234
+ * - `market` `{market: AxisMarket, created: boolean}` - a market was opened or updated
1235
+ * - `connection` `boolean` - WebSocket push connection opened or dropped
1236
+ * - `ledger` `number` - new ledger processed by the indexer
1237
+ */
1238
+ export declare class Axis extends Emitter {
1239
+ constructor(options: AxisOptions);
1240
+
1241
+ /** AXIS REST API client */
1242
+ readonly api: AxisApiClient;
1243
+ /** AXIS API WebSocket client */
1244
+ readonly stream: AxisStreamClient;
1245
+ /** Token balance wrappers */
1246
+ readonly tokenBalances: TokenBalance | undefined;
1247
+ /** Contract address of the native XLM token */
1248
+ readonly nativeAsset: string;
1249
+ /** Last known ledger */
1250
+ readonly ledger: number;
1251
+ /** Last updated UNIX milliseconds */
1252
+ readonly ledgerTime: number;
1253
+ /** Whether trading is suspended */
1254
+ readonly frozen: boolean;
1255
+ /** Contract configuration */
1256
+ readonly config: ContractInfoConfig | undefined;
1257
+ /** Available AXIS markets */
1258
+ readonly markets: Map<string, AxisMarket>;
1259
+ /** 24h ticker entries */
1260
+ readonly tickers: Map<string, TickerEntry>;
1261
+ /** Whether the contract state loaded */
1262
+ readonly loaded: boolean;
1263
+
1264
+ /** Load the contract state and track its changes */
1265
+ connect(): Promise<Axis>;
1266
+ /** Current ledger sequence */
1267
+ getLedger(): Promise<number>;
1268
+ /**
1269
+ * Get market of the asset pair
1270
+ * @param asset1 - Token contract address
1271
+ * @param asset2 - Token contract address
1272
+ */
1273
+ getMarket(asset1: string, asset2: string): AxisMarket | undefined;
1274
+ /**
1275
+ * Get live order by id
1276
+ * @param id - Order id
1277
+ * @returns Undefined if not found (filled, removed, expired)
1278
+ */
1279
+ getOrder(id: bigint | string): Promise<AccountOrder | undefined>;
1280
+ /**
1281
+ * Trader wrapper tracking the orders and allowances for an account (one instance per account address)
1282
+ * @param address - Trader address
1283
+ * @param options - Transaction signing callback
1284
+ */
1285
+ account(address: string, options?: {signTransaction?: SignTransactionCallback}): AxisAccount;
1286
+ /**
1287
+ * Stream the 24h ticker of every market
1288
+ * Sends a full snapshot, then updates caused by trades
1289
+ * @returns Unsubscribe function
1290
+ */
1291
+ subscribeTicker(callback?: (ticker: Ticker24hResult) => void): () => void;
1292
+ /**
1293
+ * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring them first if archived
1294
+ * @param params - Lifetime in days (30 by default) and the transaction source (the default signer by default)
1295
+ * @returns Ledger sequence both entries live until, at least
1296
+ */
1297
+ keepalive(params?: {days?: number; signer?: Signer}): Promise<number>;
1298
+ /** Stop following the contract state and tracked accounts */
1299
+ close(): void;
1300
+ }
1301
+
1302
+ /** Derive the push API endpoint from the REST API URL */
1303
+ export declare function toWsUrl(apiUrl: string): string;
1304
+
1305
+ /** DEX Market */
1306
+ export declare class AxisMarket {
1307
+ /** Base asset, the first of the pair in the contract canonical order */
1308
+ readonly base: string;
1309
+ /** Quote asset, the second of the pair in the contract canonical order */
1310
+ readonly quote: string;
1311
+ /** Canonical market key `base/quote` */
1312
+ readonly key: string;
1313
+ /** Creation timestamp (first oracle check) (UNIX milliseconds) */
1314
+ readonly created: number;
1315
+ /** Last oracle check (UNIX milliseconds) */
1316
+ readonly refreshed: number;
1317
+ /** Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs */
1318
+ readonly ticker: TickerEntry | undefined;
1319
+
1320
+ /** Check whether the asset is one of the market assets */
1321
+ has(asset: string): boolean;
1322
+ /**
1323
+ * The other market asset
1324
+ * @param asset - One of the market assets
1325
+ */
1326
+ counter(asset: string): string;
1327
+ /**
1328
+ * Re-check both market assets against the price oracle and cache oracle prices
1329
+ * @param signer - Transaction source, the {@link Axis} signer by default
1330
+ */
1331
+ requote(signer?: Signer): Promise<Market | undefined>;
1332
+ /**
1333
+ * Extend oracle price feeds access for the market
1334
+ * @param params - `amount` of fee tokens to burn
1335
+ * @returns New access expiration UNIX timestamps (in seconds) for each oracle-listed asset
1336
+ */
1337
+ subsidize(params: {amount: bigint, sponsor?: string, signer?: Signer}): Promise<bigint[]>;
1338
+ /**
1339
+ * Orderbook depth data with given precision
1340
+ * @param params - `base` is the base asset, `step` the price step (automatic by default)
1341
+ */
1342
+ getDepth(params?: {base?: string, depth?: number, step?: string, limit?: number}): Promise<OrderbookDepth>;
1343
+ /**
1344
+ * Stream the orderbook depth
1345
+ * Returns a snapshot, then updates on book changes
1346
+ * @returns Unsubscribe function
1347
+ */
1348
+ subscribeDepth(params: {base?: string, depth?: number, step?: string, limit?: number}, callback: (depth: OrderbookDepth) => void): () => void;
1349
+ /**
1350
+ * Stream the market trades
1351
+ * Returns a snapshot, then updates on trades
1352
+ * @param callback - Trades and whether they are the snapshot
1353
+ * @returns Unsubscribe function
1354
+ */
1355
+ subscribeTrades(callback: (trades: ApiTrade[], snapshot: boolean) => void): () => void;
1356
+ /**
1357
+ * Stream the market candles
1358
+ * Returns a snapshot, then updates on trades
1359
+ * @param params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)
1360
+ * @param callback - Candles
1361
+ * @returns Unsubscribe function
1362
+ */
1363
+ subscribeCandles(params: {base?: string, resolution: number | string, limit?: number}, callback: (candles: Candle[], snapshot: boolean) => void): () => void;
1364
+ }
1365
+
1366
+ /** Open order of a tracked account */
1367
+ export interface AccountOrder {
1368
+ /** Order id (decimal u128) */
1369
+ id: string;
1370
+ /** Maker address */
1371
+ owner: string;
1372
+ /** Sold token */
1373
+ selling: string;
1374
+ /** Bought token */
1375
+ buying: string;
1376
+ /** Market key */
1377
+ market: string;
1378
+ /** Current status */
1379
+ status: 'ACTIVE' | 'FILLED' | 'CANCELED' | 'EXPIRED';
1380
+ /** `buying` per 1 `selling`, contract scale (18 decimals) */
1381
+ price: bigint;
1382
+ /** Amount of `selling` left */
1383
+ amount: bigint;
1384
+ /** Amount of `selling` at creation */
1385
+ quote: bigint;
1386
+ /** Expiration UNIX timestamp in seconds, 0 = none */
1387
+ expires: number;
1388
+ /** Creation time, UNIX milliseconds */
1389
+ created: number;
1390
+ /** Last change, UNIX milliseconds */
1391
+ updated: number;
1392
+ /** Paging cursor (undefined for unconfirmed local orders) */
1393
+ cursor?: bigint;
1394
+ /** Share of the account budget in `selling` that backs the order */
1395
+ backed: bigint | null;
1396
+ /** `backed / amount` (0..1), null when unknown */
1397
+ backedPct: number | null;
1398
+ /** The backing is not confirmed yet */
1399
+ backingPending: boolean;
1400
+ /** Filled share of the initial amount (0..1) */
1401
+ filledPct: number;
1402
+ /** Created by this client, not reported by the indexer yet */
1403
+ pending: boolean;
1404
+ }
1405
+
1406
+ /** Balance and allowance of the account in a token, as tracked by the indexer */
1407
+ export interface AccountBacking {
1408
+ asset: string;
1409
+ /** Spendable amount (balance minus reserve and liabilities) */
1410
+ balance: bigint;
1411
+ /** Allowance granted to the AXIS contract */
1412
+ allowance: bigint;
1413
+ /** Ledger sequence the allowance lives until */
1414
+ liveUntil: number;
1415
+ /** Whether the account can send and receive the token */
1416
+ authorized: boolean;
1417
+ /** min(balance, allowance), 0 when unauthorized or expired */
1418
+ budget: bigint;
1419
+ /** Last load, UNIX milliseconds (0 = not loaded) */
1420
+ updated: number;
1421
+ /** Last skipped fill of an order selling the token, UNIX milliseconds (0 = none) */
1422
+ skipped: number;
1423
+ /** A reload confirming the latest change is due */
1424
+ pending: boolean;
1425
+ }
1426
+
1427
+ export interface AccountAllowance {
1428
+ asset: string;
1429
+ /** Whether the backing is tracked and loaded */
1430
+ known: boolean;
1431
+ balance?: bigint;
1432
+ allowance?: bigint;
1433
+ liveUntil?: number;
1434
+ authorized?: boolean;
1435
+ pending?: boolean;
1436
+ /** min(balance, allowance) */
1437
+ available?: bigint;
1438
+ /** Remaining amount of the open orders selling the token */
1439
+ committed: bigint;
1440
+ }
1441
+
1442
+ export interface AccountFill {
1443
+ /** Order after the fill */
1444
+ order: AccountOrder;
1445
+ /** Amount of `selling` delivered */
1446
+ sold: bigint;
1447
+ /** Amount of `buying` received */
1448
+ bought: bigint;
1449
+ /** Taker address */
1450
+ taker: string;
1451
+ /** Trade id */
1452
+ trade: string;
1453
+ /** Trade time, UNIX milliseconds */
1454
+ ts: number;
1455
+ /** Whether the order is still open */
1456
+ partial: boolean;
1457
+ }
1458
+
1459
+ export interface AccountTradeParams {
1460
+ /** Token sent */
1461
+ selling: string;
1462
+ /** Token received */
1463
+ buying: string;
1464
+ /** `selling` amount of a sell, `buying` amount of a buy (raw units) */
1465
+ amount: bigint | string;
1466
+ /** Limit price, contract scale; omitted for a market order */
1467
+ price?: bigint | string;
1468
+ /** {@link OrderKind}: `Limit` by default, `Fill` for a market order */
1469
+ kind?: OrderKind;
1470
+ /** Expiration UNIX timestamp (seconds) of the resting remainder */
1471
+ expires?: number;
1472
+ /** Counter orders to cross, looked up automatically when omitted */
1473
+ orders?: Array<bigint | string>;
1474
+ /** Explicit approval (`null` for none) */
1475
+ approve?: Approval | null;
1476
+ }
1477
+
1478
+ export interface AccountTradeResult {
1479
+ /** Amount of `selling` sent */
1480
+ sold: bigint;
1481
+ /** Amount of `buying` received */
1482
+ bought: bigint;
1483
+ /** ID of the order created for a limit remainder */
1484
+ orderId?: string;
1485
+ /** The created order (unconfirmed until the indexer reports it) */
1486
+ order?: AccountOrder;
1487
+ /** Approval granted with the trade */
1488
+ approve?: Approval;
1489
+ }
1490
+
1491
+ export interface AccountSwapParams {
1492
+ /** Token sent */
1493
+ selling: string;
1494
+ /** Token received */
1495
+ buying: string;
1496
+ /** `selling` amount of a sell, `buying` amount of a buy (raw units) */
1497
+ amount: bigint | string;
1498
+ /** {@link TradeDirection}, `Sell` by default */
1499
+ direction?: TradeDirection;
1500
+ /** Price tolerance as a fraction (0.005 = 0.5%), 0 by default */
1501
+ slippage?: number;
1502
+ }
1503
+
1504
+ /** Market filter: a market key `x/y`, an {@link AxisMarket} or a pair of assets, in any order */
1505
+ export type AccountMarketFilter = string | {base: string, quote: string} | string[];
1506
+
1507
+ /**
1508
+ * Trader wrapper that tracks every open order of an account across all markets and the account backing.
1509
+ * Create it with {@link import('./axis.js').Axis#account}.
1510
+ *
1511
+ * Emits:
1512
+ * - `ready` - the account state was loaded
1513
+ * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
1514
+ * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
1515
+ * - `fill` {@link AccountFill} - an order was partially filled
1516
+ * - `filled` {@link AccountFill} - an order was filled in full
1517
+ * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
1518
+ * - `cancel` {@link AccountOrder} - an order was removed by the owner
1519
+ * - `expire` {@link AccountOrder} - an order expired
1520
+ * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
1521
+ * - `order` `{action, order, fill?}` - any order change
1522
+ * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
1523
+ * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
1524
+ * - `trade` {ApiTrade} - the account performed a trade
1525
+ * - `swap` {ApiSwap} - the account performed a swap
1526
+ * - `change` - the open orders or the backing changed
1527
+ * - `error` `Error` - the push API rejected the account subscription
1528
+ */
1529
+ export declare class AxisAccount extends Emitter {
1530
+ /** Trader address */
1531
+ readonly address: string;
1532
+ /** Wallet signing callback, required to trade */
1533
+ signTransaction?: SignTransactionCallback;
1534
+ /** Open orders by id */
1535
+ readonly orders: Map<string, AccountOrder>;
1536
+ /** Account backing by token contract id */
1537
+ readonly backing: Map<string, AccountBacking>;
1538
+ /** Resolves once the account state has been loaded */
1539
+ readonly ready: Promise<void>;
1540
+ /** Whether the account state has been loaded */
1541
+ readonly loaded: boolean;
1542
+ /** Get spendable balances in every tracked token by token contract id */
1543
+ readonly balances: Map<string, bigint>;
1544
+ /** Whether the account exists on the ledger */
1545
+ readonly funded: boolean | undefined;
1546
+
1547
+ /**
1548
+ * Get spendable balance of the account in a token
1549
+ * @param asset - Token contract id
1550
+ * @returns Undefined if not tracked
1551
+ */
1552
+ getBalance(asset: string): bigint | undefined;
1553
+ /**
1554
+ * Retrieve open orders, newest first
1555
+ * @param filter - `market` is an {AxisMarket} or a pair of assets in any order
1556
+ */
1557
+ getOrders(filter?: {market?: AccountMarketFilter, selling?: string, buying?: string}): AccountOrder[];
1558
+ /** Get open order by id */
1559
+ getOrder(id: bigint | string): AccountOrder | undefined;
1560
+ /**
1561
+ * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must
1562
+ * cover)
1563
+ * @param asset - Token contract id
1564
+ */
1565
+ committed(asset: string): bigint;
1566
+ /**
1567
+ * Get balance, allowance and commitments of the account in a token
1568
+ * @param asset - Token contract id
1569
+ */
1570
+ getAllowance(asset: string): AccountAllowance;
1571
+ /**
1572
+ * Sell tokens creating a limit remainder order if not executed in full
1573
+ * @param params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
1574
+ */
1575
+ sell(params: AccountTradeParams): Promise<AccountTradeResult>;
1576
+ /**
1577
+ * Buy tokens creating a limit remainder order if not executed in full
1578
+ * @param params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
1579
+ */
1580
+ buy(params: AccountTradeParams): Promise<AccountTradeResult>;
1581
+ /**
1582
+ * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it
1583
+ * @param params - Same as `sell`
1584
+ * @returns Network fee and expected result
1585
+ */
1586
+ estimateSell(params: AccountTradeParams): Promise<TradeEstimate>;
1587
+ /**
1588
+ * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
1589
+ * @param params - Same as `buy`
1590
+ * @returns Network fee and expected result
1591
+ */
1592
+ estimateBuy(params: AccountTradeParams): Promise<TradeEstimate>;
1593
+ /**
1594
+ * Change the amount, price or expiration of open orders (omitted fields keep their current values)
1595
+ * @returns Updated order ids
1596
+ */
1597
+ update(updates: Array<{id: bigint | string, amount?: bigint, price?: bigint, expires?: number}>): Promise<bigint[]>;
1598
+ /** Cancel open orders */
1599
+ cancel(ids: Array<bigint | string>): Promise<void>;
1600
+ /**
1601
+ * Cancel all open orders
1602
+ * @returns Canceled order ids
1603
+ */
1604
+ cancelAll(filter?: {market?: AccountMarketFilter}): Promise<string[]>;
1605
+ /**
1606
+ * Fill an open order against the book while keeping profits from price inefficiencies
1607
+ * @param takerOrderId - Order acting as the taker
1608
+ * @param orders - Counter orders, looked up automatically when omitted
1609
+ */
1610
+ crossfill(takerOrderId: bigint | string, orders?: Array<bigint | string>): Promise<{sold: bigint, bought: bigint, surplus: bigint}>;
1611
+ /** Swap across one or several markets along the best route found by the AXIS API */
1612
+ swap(params: AccountSwapParams): Promise<{sold: bigint, bought: bigint, approve?: Approval}>;
1613
+ /**
1614
+ * Compute approval for a call
1615
+ * @param asset - Token contract id
1616
+ * @param required - Max amount the call may spend
1617
+ */
1618
+ planApproval(asset: string, required: bigint): Promise<{amount: bigint, liveUntil: number} | undefined>;
1619
+ /** Reload current account state from the REST API */
1620
+ refresh(): Promise<void>;
1621
+ /** Stop tracking this account */
1622
+ close(): void;
1623
+ }
1624
+
1625
+ /** Convert an API order to the client form (bigint amounts and prices, numeric timestamps) */
1626
+ export declare function parseApiOrder(raw: ApiOrder): AccountOrder;