@axis-markets/client 0.8.2 → 0.8.3

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.
@@ -1,1015 +1,1022 @@
1
- import {Emitter} from './emitter.js'
2
- import {pairKey, invertPrice} from './asset-pair.js'
3
- import {parseApiDate} from './api-dates.js'
4
- import {planApproval, maxQuoteSpend} from './allowance.js'
5
- import {OrderKind, TradeDirection} from './constants.js'
6
-
7
- /** Orders per `update` transaction */
8
- const UPDATE_BATCH = 90
9
- /** Time to wait for the account state before trading, in milliseconds */
10
- const READY_TIMEOUT = 15_000
11
- /** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */
12
- const LOCAL_ORDER_TTL = 120_000
13
-
14
- /**
15
- * Trader wrapper that tracks every open order of an account across all markets and the account backing.
16
- * Create it with {@link import('./axis.js').Axis#account}.
17
- *
18
- * Emits:
19
- * - `ready` - the account state was loaded
20
- * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
21
- * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
22
- * - `fill` {@link AccountFill} - an order was partially filled
23
- * - `filled` {@link AccountFill} - an order was filled in full
24
- * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
25
- * - `cancel` {@link AccountOrder} - an order was removed by the owner
26
- * - `expire` {@link AccountOrder} - an order expired
27
- * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
28
- * - `order` `{action, order, fill?}` - any order change
29
- * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
30
- * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
31
- * - `trade` {ApiTrade} - the account performed a trade
32
- * - `swap` {ApiSwap} - the account performed a swap
33
- * - `change` - the open orders or the backing changed
34
- * - `error` `Error` - the push API rejected the account subscription
35
- */
36
- export class AxisAccount extends Emitter {
37
- /**
38
- * @param {Axis} axis
39
- * @param {string} address - Trader address
40
- * @param {{signTransaction?: SignTransactionCallback}} [options]
41
- */
42
- constructor(axis, address, {signTransaction} = {}) {
43
- super()
44
- this.axis = axis
45
- this.address = address
46
- this.signTransaction = signTransaction
47
- this.ready = new Promise(resolve => this.resolveReady = resolve)
48
- }
49
-
50
- /**
51
- * Trader address
52
- * @type {string}
53
- * @readonly
54
- */
55
- address
56
- /**
57
- * Wallet signing callback, required to trade
58
- * @type {SignTransactionCallback|undefined}
59
- */
60
- signTransaction
61
- /**
62
- * Open orders by id
63
- * @type {Map<string, AccountOrder>}
64
- * @readonly
65
- */
66
- orders = new Map()
67
- /**
68
- * Account backing by token contract id
69
- * @type {Map<string, AccountBacking>}
70
- * @readonly
71
- */
72
- backing = new Map()
73
- /**
74
- * Resolves once the account state has been loaded
75
- * @type {Promise<void>}
76
- * @readonly
77
- */
78
- ready
79
- /**
80
- * Whether the account state has been loaded
81
- * @type {boolean}
82
- */
83
- loaded = false
84
- /**
85
- * Orders created by this client that the indexer has not reported yet
86
- * @type {Map<string, {order: AccountOrder, expires: number}>}
87
- * @private
88
- */
89
- local = new Map()
90
- /**
91
- * Whether the backing in memory get updated from the push API
92
- * @type {boolean}
93
- * @private
94
- */
95
- live = false
96
- /**
97
- * Last taker spend of this client by token, UNIX milliseconds
98
- * @type {Map<string, number>}
99
- * @private
100
- */
101
- spent = new Map() //TODO: drop this
102
- /**
103
- * @type {function(): void}
104
- * @private
105
- */
106
- resolveReady
107
-
108
- /**
109
- * Start tracking this account
110
- * @internal
111
- */
112
- start() {
113
- const {stream} = this.axis
114
- this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))
115
- this.offOpen = stream.on('open', () => this.stopFallback())
116
- this.offClose = stream.on('close', () => {
117
- this.live = false //changes are missed until the next snapshot
118
- this.startFallback()
119
- })
120
- //load over REST if the push API does not deliver the snapshot soon
121
- this.initTimer = setTimeout(() => {
122
- if (!this.loaded) {
123
- this.refresh().catch(() => this.startFallback())
124
- }
125
- }, 3_000)
126
- }
127
-
128
- /**
129
- * Stop tracking this account
130
- */
131
- close() {
132
- clearTimeout(this.initTimer)
133
- this.stopFallback()
134
- this.unsubscribe?.()
135
- this.offOpen?.()
136
- this.offClose?.()
137
- this.axis.releaseAccount(this)
138
- }
139
-
140
- /**
141
- * Reload current account state from the REST API
142
- * @return {Promise<void>}
143
- */
144
- async refresh() {
145
- //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances
146
- this.applySnapshot(await this.axis.api.getAccount(this.address), true)
147
- }
148
-
149
- /**
150
- * Retrieve open orders, newest first
151
- * @param {{market?: string|{base: string, quote: string}|string[], selling?: string, buying?: string}} [filter] - `market` is an {AxisMarket} or a pair of assets in any order
152
- * @return {AccountOrder[]}
153
- */
154
- getOrders({market, selling, buying} = {}) { //TODO: simplify market argument
155
- const key = toMarketKey(market)
156
- const res = []
157
- for (const order of this.allOrders()) {
158
- if (key && order.market !== key)
159
- continue
160
- if (selling && order.selling !== selling)
161
- continue
162
- if (buying && order.buying !== buying)
163
- continue
164
- res.push(order)
165
- }
166
- return res.sort(newestFirst)
167
- }
168
-
169
- /**
170
- * Get open order by id
171
- * @param {bigint|string} id
172
- * @return {AccountOrder|undefined}
173
- */
174
- getOrder(id) {
175
- const key = id.toString()
176
- return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)
177
- }
178
-
179
- /**
180
- * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)
181
- * @param {string} asset - Token contract id
182
- * @return {bigint}
183
- */
184
- committed(asset) {
185
- let sum = 0n
186
- for (const order of this.allOrders()) {
187
- if (order.selling === asset) {
188
- sum += order.amount
189
- }
190
- }
191
- return sum
192
- }
193
-
194
- /**
195
- * Get spendable balance of the account in a token
196
- * @param {string} asset - Token contract id
197
- * @return {bigint|undefined} - Undefined if not tracked
198
- */
199
- getBalance(asset) {
200
- const backing = this.backing.get(asset)
201
- return backing?.updated ? backing.balance : undefined
202
- }
203
-
204
- /**
205
- * Get spendable balances in every tracked token by token contract id
206
- * @return {Map<string, bigint>}
207
- */
208
- get balances() {
209
- const res = new Map()
210
- for (const [asset, backing] of this.backing) {
211
- if (backing.updated) {
212
- res.set(asset, backing.balance)
213
- }
214
- }
215
- return res
216
- }
217
-
218
- /**
219
- * Whether the account exists on the ledger
220
- * @return {boolean|undefined}
221
- */
222
- get funded() {
223
- const backing = this.backing.get(this.axis.nativeAsset)
224
- return backing?.updated ? backing.authorized : undefined
225
- }
226
-
227
- /**
228
- * Get balance, allowance and commitments of the account in a token
229
- * @param {string} asset - Token contract id
230
- * @return {AccountAllowance}
231
- */
232
- getAllowance(asset) {
233
- const backing = this.backing.get(asset)
234
- const committed = this.committed(asset)
235
- if (!backing?.updated)
236
- return {asset, known: false, committed}
237
- return {
238
- asset,
239
- known: true,
240
- balance: backing.balance,
241
- allowance: backing.allowance,
242
- liveUntil: backing.liveUntil,
243
- authorized: backing.authorized,
244
- pending: backing.pending,
245
- available: backing.budget,
246
- committed
247
- }
248
- }
249
-
250
- /**
251
- * Sell tokens creating a limit remainder order if not executed in full
252
- * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
253
- * @return {Promise<TradeResult>}
254
- */
255
- async sell(params) {
256
- return this.trade(TradeDirection.Sell, params)
257
- }
258
-
259
- /**
260
- * Buy tokens creating a limit remainder order if not executed in full
261
- * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
262
- * @return {Promise<TradeResult>}
263
- */
264
- async buy(params) {
265
- return this.trade(TradeDirection.Buy, params)
266
- }
267
-
268
- /**
269
- * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it
270
- * @param {TradeParams} params - Same as `sell`
271
- * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
272
- */
273
- async estimateSell(params) {
274
- const {payload} = await this.prepareTrade(TradeDirection.Sell, params)
275
- const client = await this.client()
276
- return client.estimateSell(payload)
277
- }
278
-
279
- /**
280
- * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
281
- * @param {TradeParams} params - Same as `buy`
282
- * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
283
- */
284
- async estimateBuy(params) {
285
- const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
286
- const client = await this.client()
287
- return client.estimateBuy(payload)
288
- }
289
-
290
- /**
291
- * Change the amount, price or expiration of open orders (omitted fields keep their current values)
292
- * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
293
- * @return {Promise<bigint[]>} - Updated order ids
294
- */
295
- async update(updates) {
296
- await this.whenReady()
297
- const normalized = updates.map(update => {
298
- const current = this.getOrder(update.id)
299
- if (!current && (update.amount === undefined || update.price === undefined))
300
- throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
301
- return {
302
- current,
303
- update: {
304
- id: BigInt(update.id),
305
- amount: update.amount ?? current.amount,
306
- price: update.price ?? current.price,
307
- expires: update.expires ?? current?.expires ?? 0
308
- }
309
- }
310
- })
311
- //extra commitment per sold token
312
- const growth = new Map()
313
- for (const {current, update} of normalized) {
314
- if (!current)
315
- continue
316
- growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)
317
- }
318
- const approvals = []
319
- for (const [asset, delta] of growth) {
320
- if (delta <= 0n)
321
- continue
322
- const approve = await this.planApproval(asset, delta)
323
- if (approve) {
324
- this.emit('approve', {asset, ...approve})
325
- approvals.push({asset, ...approve})
326
- }
327
- }
328
- const client = await this.client()
329
- const res = []
330
- for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
331
- const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
332
- //approvals travel with the first batch, before its backing check
333
- const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})
334
- res.push(...ids)
335
- }
336
- return res
337
- }
338
-
339
- /**
340
- * Cancel open orders
341
- * @param {Array<bigint|string>} ids
342
- * @return {Promise<void>}
343
- */
344
- async cancel(ids) {
345
- const client = await this.client()
346
- const all = ids.map(id => BigInt(id))
347
- for (let i = 0; i < all.length; i += UPDATE_BATCH) {
348
- await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
349
- }
350
- for (const id of all) {
351
- this.local.delete(id.toString())
352
- }
353
- }
354
-
355
- /**
356
- * Cancel all open orders
357
- * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
358
- * @return {Promise<string[]>} - Canceled order ids
359
- */
360
- async cancelAll({market} = {}) {
361
- await this.whenReady()
362
- const ids = this.getOrders({market}).map(order => order.id)
363
- if (ids.length) {
364
- await this.cancel(ids)
365
- }
366
- return ids
367
- }
368
-
369
- /**
370
- * Fill an open order against the book while keeping profits from price inefficiencies
371
- * @param {bigint|string} takerOrderId - Order acting as the taker
372
- * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted
373
- * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
374
- */
375
- async crossfill(takerOrderId, orders) {
376
- if (!orders) {
377
- const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
378
- if (!taker)
379
- throw new Error(`Order ${takerOrderId} not found`)
380
- orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
381
- }
382
- const client = await this.client()
383
- const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
384
- return {sold, bought, surplus}
385
- }
386
-
387
- /**
388
- * Swap across one or several markets along the best route found by the AXIS API
389
- * @param {SwapParams} params
390
- * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
391
- */
392
- async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
393
- await this.whenReady()
394
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
395
- const quote = direction === TradeDirection.Buy ?
396
- await this.axis.api.quoteBuy(params) :
397
- await this.axis.api.quoteSell(params)
398
- const best = quote.paths?.[0]
399
- if (quote.status !== 'success' || !best?.path?.length)
400
- throw new Error(quote.error || 'No route available')
401
- const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))
402
- const tolerance = BigInt(Math.round(slippage * 10_000))
403
- let sellingAmount = BigInt(best.sold)
404
- let buyingAmount = BigInt(best.bought)
405
- if (direction === TradeDirection.Buy) {
406
- sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n
407
- } else {
408
- buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n
409
- }
410
- //`sellingAmount` is the exact spend of a sell and the most a buy may spend
411
- const approve = await this.planApproval(selling, sellingAmount)
412
- if (approve) {
413
- this.emit('approve', {asset: selling, ...approve})
414
- }
415
- const client = await this.client()
416
- const [sold, bought] = await client.swap({
417
- direction,
418
- trader: this.address,
419
- selling,
420
- sellingAmount,
421
- buyingAmount,
422
- path,
423
- approve
424
- })
425
- this.spent.set(selling, Date.now())
426
- return {sold, bought, approve}
427
- }
428
-
429
- /**
430
- * Compute approval for a call
431
- * @param {string} asset - Token contract id
432
- * @param {bigint} required - Max amount the call may spend
433
- * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}
434
- */
435
- async planApproval(asset, required) {
436
- await this.whenReady()
437
- const backing = this.backing.get(asset)
438
- let allowance
439
- if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {
440
- allowance = backing.allowance
441
- } else {
442
- const {tokenBalances} = this.axis
443
- if (!tokenBalances)
444
- throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
445
- await this.axis.getContractId() //the allowance spender
446
- allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
447
- }
448
- return planApproval({
449
- required,
450
- committed: this.committed(asset),
451
- allowance,
452
- liveUntil: backing?.liveUntil ?? 0,
453
- ledger: await this.axis.getLedger()
454
- })
455
- }
456
-
457
- /**
458
- * Check whether the pushed allowance of a token can be used as is
459
- * @param {string} asset - Token contract id
460
- * @return {boolean}
461
- * @private
462
- */
463
- isAllowanceCurrent(asset) {
464
- const backing = this.backing.get(asset)
465
- if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
466
- return false
467
- const spent = this.spent.get(asset)
468
- if (spent === undefined)
469
- return true
470
- if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives
471
- return false //TODO: try to read allowance change from tx result meta changes
472
- this.spent.delete(asset)
473
- return true
474
- }
475
-
476
- /**
477
- * @param {number} direction
478
- * @param {TradeParams} params
479
- * @return {Promise<TradeResult>}
480
- * @private
481
- */
482
- async trade(direction, params) {
483
- const {payload, planned} = await this.prepareTrade(direction, params)
484
- const {selling, buying, amount, price, expires, approve} = payload
485
- if (planned && approve) {
486
- this.emit('approve', {asset: selling, ...approve})
487
- }
488
- const client = await this.client()
489
- const [sold, bought, createdId] = direction === TradeDirection.Buy ?
490
- await client.buy(payload) :
491
- await client.sell(payload)
492
- this.spent.set(selling, Date.now())
493
- let order
494
- if (createdId) {
495
- order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})
496
- }
497
- return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}
498
- }
499
-
500
- /**
501
- * Resolve the crossing orders, the price of a market order and the approval of a trade
502
- * @param {number} direction
503
- * @param {TradeParams} params
504
- * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,
505
- * `planned` if the approval was planned by the account rather than supplied
506
- * @private
507
- */
508
- async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {
509
- await this.whenReady()
510
- amount = BigInt(amount)
511
- const market = price === undefined || price === null
512
- if (kind === undefined) {
513
- kind = market ? OrderKind.Fill : OrderKind.Limit
514
- }
515
- let crossing
516
- if (!orders || market) {
517
- //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the
518
- //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well
519
- const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))
520
- crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)
521
- }
522
- if (market) {
523
- //cross everything the quote found: the limit is the worst maker price (makers price `selling` per
524
- //`buying` of a buyer; seen from a seller, invert it)
525
- if (!crossing.worstPrice)
526
- throw new Error('Not enough liquidity for a market order')
527
- price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)
528
- }
529
- price = BigInt(price)
530
- const planned = approve === undefined
531
- if (planned) {
532
- const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount
533
- approve = await this.planApproval(selling, required)
534
- }
535
- const payload = {
536
- kind,
537
- trader: this.address,
538
- amount,
539
- selling,
540
- buying,
541
- price,
542
- orders: (orders ?? crossing.orders).map(id => BigInt(id)),
543
- expires,
544
- approve: approve || undefined
545
- }
546
- return {payload, planned}
547
- }
548
-
549
- /**
550
- * Count an order this client created as committed until the indexer reports it
551
- * @param {bigint} id
552
- * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read
553
- * @return {Promise<AccountOrder|undefined>}
554
- * @private
555
- */
556
- async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {
557
- const key = id.toString()
558
- if (this.orders.has(key))
559
- return this.orders.get(key) //already reported
560
- let stored
561
- try {
562
- const client = await this.client()
563
- stored = await client.order(id)
564
- } catch (e) {
565
- //estimate below
566
- }
567
- if (this.orders.has(key))
568
- return this.orders.get(key)
569
- let orderAmount
570
- let orderPrice
571
- if (stored) {
572
- orderAmount = stored.amount
573
- orderPrice = stored.price
574
- } else if (direction === TradeDirection.Sell) {
575
- orderAmount = amount - sold
576
- orderPrice = price
577
- } else {
578
- //the remainder of a buy sells `selling` for the rest of `buying` at the limit
579
- orderAmount = maxQuoteSpend(amount - bought, price)
580
- orderPrice = invertPrice(price)
581
- }
582
- const now = Date.now()
583
- /** @type {AccountOrder} */
584
- const order = {
585
- id: key,
586
- owner: this.address,
587
- selling,
588
- buying,
589
- market: pairKey(selling, buying),
590
- status: 'ACTIVE',
591
- price: orderPrice,
592
- amount: orderAmount,
593
- quote: orderAmount,
594
- expires: Number(stored?.expires ?? expires ?? 0),
595
- created: now,
596
- updated: now,
597
- cursor: undefined,
598
- backed: null,
599
- backedPct: null,
600
- backingPending: true,
601
- filledPct: 0,
602
- pending: true
603
- }
604
- this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})
605
- this.emit('pending', order)
606
- this.emit('change')
607
- return order
608
- }
609
-
610
- /**
611
- * Crossing orders of a direct-market trade and the worst price among them
612
- * @param {number} direction
613
- * @param {string} selling
614
- * @param {string} buying
615
- * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy
616
- * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order
617
- * @return {Promise<{orders: string[], worstPrice: bigint|null}>}
618
- * @private
619
- */
620
- async findQuote(direction, selling, buying, amount, maxPrice) {
621
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}
622
- try {
623
- const quote = direction === TradeDirection.Buy ?
624
- await this.axis.api.quoteBuy(params) :
625
- await this.axis.api.quoteSell(params)
626
- const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null
627
- if (hop)
628
- return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}
629
- } catch (e) {
630
- //nothing to cross: a limit order simply rests
631
- }
632
- return {orders: [], worstPrice: null}
633
- }
634
-
635
- /**
636
- * @return {Promise<AxisContractClient>}
637
- * @private
638
- */
639
- async client() {
640
- if (!this.signTransaction)
641
- throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
642
- return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
643
- }
644
-
645
- /**
646
- * @param {number} [timeout]
647
- * @return {Promise<void>}
648
- * @private
649
- */
650
- async whenReady(timeout = READY_TIMEOUT) {
651
- if (this.loaded)
652
- return
653
- let timer
654
- try {
655
- await Promise.race([
656
- this.ready,
657
- new Promise((resolve, reject) => {
658
- timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)
659
- })
660
- ])
661
- } finally {
662
- clearTimeout(timer)
663
- }
664
- }
665
-
666
- /**
667
- * @param {StreamMessage} message
668
- * @private
669
- */
670
- handle(message) {
671
- switch (message.type) {
672
- case 'account':
673
- this.live = true
674
- return this.applySnapshot(message)
675
- case 'order':
676
- return this.applyOrder(message)
677
- case 'backing':
678
- return this.applyBacking(message)
679
- case 'trade':
680
- return this.emit('trade', message.trade)
681
- case 'swap':
682
- return this.emit('swap', message.swap)
683
- case 'error':
684
- return this.emit('error', new Error(message.error))
685
- }
686
- }
687
-
688
- /**
689
- * Replace the state with a snapshot
690
- * @param {ApiAccount} state
691
- * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot
692
- * @private
693
- */
694
- applySnapshot(state, mergeBacking = false) {
695
- const previous = this.orders
696
- const next = new Map()
697
- for (const raw of state.orders || []) {
698
- const order = parseApiOrder(raw)
699
- next.set(order.id, order)
700
- this.local.delete(order.id)
701
- }
702
- this.orders = next
703
- const backing = mergeBacking ? new Map(this.backing) : new Map()
704
- for (const [asset, raw] of Object.entries(state.backing || {})) {
705
- backing.set(asset, parseBacking(asset, raw))
706
- }
707
- this.backing = backing
708
- if (this.loaded) {
709
- for (const [id, order] of previous) {
710
- if (!next.has(id)) {
711
- this.emit('remove', order)
712
- }
713
- }
714
- for (const [id, order] of next) {
715
- if (!previous.has(id)) {
716
- this.emit('new', order)
717
- }
718
- }
719
- }
720
- if (!this.loaded) {
721
- this.loaded = true
722
- this.resolveReady()
723
- this.emit('ready')
724
- }
725
- this.emit('change')
726
- }
727
-
728
- /**
729
- * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message
730
- * @private
731
- */
732
- applyOrder({action, order: raw, fill: rawFill}) {
733
- const order = parseApiOrder(raw)
734
- this.local.delete(order.id)
735
- const previous = this.orders.get(order.id)
736
- const removed = action === 'filled' || action === 'cancel' || action === 'expire'
737
- if (removed) {
738
- this.orders.delete(order.id)
739
- } else {
740
- if (previous && order.backed === null) {
741
- //the event serialization may lack the split; keep the last known one until the backing update
742
- order.backed = previous.backed
743
- order.backedPct = previous.backedPct
744
- order.backingPending = previous.backingPending
745
- }
746
- this.orders.set(order.id, order)
747
- }
748
- const fill = rawFill && {
749
- order,
750
- sold: BigInt(rawFill.sold),
751
- bought: BigInt(rawFill.bought),
752
- taker: rawFill.taker,
753
- trade: rawFill.trade?.toString(),
754
- ts: Number(rawFill.ts) * 1000,
755
- partial: action === 'fill'
756
- }
757
- this.emit(action, fill || order)
758
- if (removed) {
759
- this.emit('remove', order)
760
- }
761
- this.emit('order', {action, order, fill})
762
- this.emit('change')
763
- }
764
-
765
- /**
766
- * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message
767
- * @private
768
- */
769
- applyBacking({asset, backing: raw, backed}) {
770
- const backing = raw ? parseBacking(asset, raw) : undefined
771
- if (backing) {
772
- this.backing.set(asset, backing)
773
- } else {
774
- this.backing.delete(asset)
775
- }
776
- for (const [id, amount] of Object.entries(backed || {})) {
777
- const order = this.orders.get(id)
778
- if (!order)
779
- continue
780
- order.backed = BigInt(amount)
781
- order.backedPct = share(order.backed, order.amount)
782
- order.backingPending = !backing || backing.pending || !backing.updated
783
- }
784
- this.emit('backing', {asset, backing})
785
- this.emit('change')
786
- }
787
-
788
- /**
789
- * @return {Iterable<AccountOrder>}
790
- * @private
791
- */
792
- * allOrders() {
793
- yield* this.orders.values()
794
- yield* this.localOrders()
795
- }
796
-
797
- /**
798
- * Get local orders that haven't expired
799
- * @return {AccountOrder[]}
800
- * @private
801
- */
802
- localOrders() {
803
- const now = Date.now()
804
- const res = []
805
- for (const [id, {order, expires}] of this.local) {
806
- if (expires < now || this.orders.has(id)) {
807
- this.local.delete(id)
808
- } else {
809
- res.push(order)
810
- }
811
- }
812
- return res
813
- }
814
-
815
- /**
816
- * @private
817
- */
818
- startFallback() {
819
- if (this.fallbackTimer)
820
- return
821
- this.fallbackTimer = setInterval(() => {
822
- this.refresh().catch(() => {
823
- //retried on the next tick
824
- })
825
- }, this.axis.fallbackPollInterval)
826
- }
827
-
828
- /**
829
- * @private
830
- */
831
- stopFallback() {
832
- clearInterval(this.fallbackTimer)
833
- this.fallbackTimer = undefined
834
- }
835
- }
836
-
837
- /**
838
- * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)
839
- * @param {ApiOrder} raw
840
- * @return {AccountOrder}
841
- */
842
- export function parseApiOrder(raw) {
843
- const amount = BigInt(raw.amount)
844
- const quote = BigInt(raw.quote ?? raw.amount)
845
- //unconfirmed until loaded, and while a reload confirming the latest event is due
846
- const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending
847
- const backed = raw.backed !== undefined ? BigInt(raw.backed) : null
848
- return {
849
- id: raw.id,
850
- owner: raw.owner,
851
- selling: raw.selling,
852
- buying: raw.buying,
853
- market: pairKey(raw.selling, raw.buying),
854
- status: raw.status,
855
- price: BigInt(raw.price),
856
- amount,
857
- quote,
858
- expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,
859
- created: parseApiDate(raw.created),
860
- updated: parseApiDate(raw.updated),
861
- cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,
862
- backed,
863
- backedPct: backed === null ? null : share(backed, amount),
864
- backingPending: !confirmed,
865
- filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,
866
- pending: false
867
- }
868
- }
869
-
870
- /**
871
- * @param {string} asset
872
- * @param {ApiBacking} raw
873
- * @return {AccountBacking}
874
- */
875
- function parseBacking(asset, raw) {
876
- return {
877
- asset,
878
- balance: BigInt(raw.balance),
879
- allowance: BigInt(raw.allowance),
880
- liveUntil: raw.liveUntil || 0,
881
- authorized: raw.authorized !== false,
882
- budget: BigInt(raw.budget ?? 0),
883
- updated: parseApiDate(raw.updated),
884
- skipped: parseApiDate(raw.skipped),
885
- pending: raw.pending === true
886
- }
887
- }
888
-
889
- /**
890
- * @param {bigint} part
891
- * @param {bigint} total
892
- * @return {number} - 0..1
893
- */
894
- function share(part, total) {
895
- if (total <= 0n)
896
- return 1
897
- return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
898
- }
899
-
900
- /**
901
- * @param {string|{base: string, quote: string}|string[]|undefined} market
902
- * @return {string|undefined}
903
- */
904
- function toMarketKey(market) {
905
- if (!market)
906
- return undefined
907
- if (typeof market === 'string') {
908
- const [x, y] = market.split('/')
909
- return pairKey(x, y)
910
- }
911
- if (Array.isArray(market))
912
- return pairKey(market[0], market[1])
913
- return pairKey(market.base, market.quote)
914
- }
915
-
916
- /**
917
- * Newest first: unconfirmed local orders, then by creation position
918
- * @param {AccountOrder} x
919
- * @param {AccountOrder} y
920
- * @return {number}
921
- */
922
- function newestFirst(x, y) {
923
- if (x.cursor === undefined || y.cursor === undefined)
924
- return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created
925
- return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0
926
- }
927
-
928
- /**
929
- * @typedef {{}} AccountOrder - Open order of a tracked account
930
- * @property {string} id - Order id (decimal u128)
931
- * @property {string} owner - Maker address
932
- * @property {string} selling - Sold token
933
- * @property {string} buying - Bought token
934
- * @property {string} market - Market key
935
- * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status
936
- * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)
937
- * @property {bigint} amount - Amount of `selling` left
938
- * @property {bigint} quote - Amount of `selling` at creation
939
- * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none
940
- * @property {number} created - Creation time, UNIX milliseconds
941
- * @property {number} updated - Last change, UNIX milliseconds
942
- * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)
943
- * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order
944
- * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown
945
- * @property {boolean} backingPending - The backing is not confirmed yet
946
- * @property {number} filledPct - Filled share of the initial amount (0..1)
947
- * @property {boolean} pending - Created by this client, not reported by the indexer yet
948
- */
949
-
950
- /**
951
- * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer
952
- * @property {string} asset
953
- * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)
954
- * @property {bigint} allowance - Allowance granted to the AXIS contract
955
- * @property {number} liveUntil - Ledger sequence the allowance lives until
956
- * @property {boolean} authorized - Whether the account can send and receive the token
957
- * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired
958
- * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)
959
- * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)
960
- * @property {boolean} pending - A reload confirming the latest change is due
961
- */
962
-
963
- /**
964
- * @typedef {{}} AccountAllowance
965
- * @property {string} asset
966
- * @property {boolean} known - Whether the backing is tracked and loaded
967
- * @property {bigint} [balance]
968
- * @property {bigint} [allowance]
969
- * @property {number} [liveUntil]
970
- * @property {boolean} [authorized]
971
- * @property {boolean} [pending]
972
- * @property {bigint} [available] - min(balance, allowance)
973
- * @property {bigint} committed - Remaining amount of the open orders selling the token
974
- */
975
-
976
- /**
977
- * @typedef {{}} AccountFill
978
- * @property {AccountOrder} order - Order after the fill
979
- * @property {bigint} sold - Amount of `selling` delivered
980
- * @property {bigint} bought - Amount of `buying` received
981
- * @property {string} taker - Taker address
982
- * @property {string} trade - Trade id
983
- * @property {number} ts - Trade time, UNIX milliseconds
984
- * @property {boolean} partial - Whether the order is still open
985
- */
986
-
987
- /**
988
- * @typedef {{}} TradeParams
989
- * @property {string} selling - Token sent
990
- * @property {string} buying - Token received
991
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
992
- * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order
993
- * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order
994
- * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder
995
- * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted
996
- * @property {Approval|null} [approve] - Explicit approval (`null` for none)
997
- */
998
-
999
- /**
1000
- * @typedef {{}} TradeResult
1001
- * @property {bigint} sold - Amount of `selling` sent
1002
- * @property {bigint} bought - Amount of `buying` received
1003
- * @property {string} [orderId] - ID of the order created for a limit remainder
1004
- * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)
1005
- * @property {Approval} [approve] - Approval granted with the trade
1006
- */
1007
-
1008
- /**
1009
- * @typedef {{}} SwapParams
1010
- * @property {string} selling - Token sent
1011
- * @property {string} buying - Token received
1012
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1013
- * @property {number} [direction] - {@link TradeDirection}, `Sell` by default
1014
- * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default
1015
- */
1
+ import {Emitter} from './emitter.js'
2
+ import {pairKey, invertPrice} from './asset-pair.js'
3
+ import {parseApiDate} from './api-dates.js'
4
+ import {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'
5
+ import {OrderKind, TradeDirection} from './constants.js'
6
+
7
+ /** Orders per `update` transaction */
8
+ const UPDATE_BATCH = 90
9
+ /** Time to wait for the account state before trading, in milliseconds */
10
+ const READY_TIMEOUT = 15_000
11
+ /** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */
12
+ const LOCAL_ORDER_TTL = 120_000
13
+
14
+ /**
15
+ * Trader wrapper that tracks every open order of an account across all markets and the account backing.
16
+ * Create it with {@link import('./axis.js').Axis#account}.
17
+ *
18
+ * Emits:
19
+ * - `ready` - the account state was loaded
20
+ * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
21
+ * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
22
+ * - `fill` {@link AccountFill} - an order was partially filled
23
+ * - `filled` {@link AccountFill} - an order was filled in full
24
+ * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
25
+ * - `cancel` {@link AccountOrder} - an order was removed by the owner
26
+ * - `expire` {@link AccountOrder} - an order expired
27
+ * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
28
+ * - `order` `{action, order, fill?}` - any order change
29
+ * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
30
+ * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
31
+ * - `trade` {ApiTrade} - the account performed a trade
32
+ * - `swap` {ApiSwap} - the account performed a swap
33
+ * - `change` - the open orders or the backing changed
34
+ * - `error` `Error` - the push API rejected the account subscription
35
+ */
36
+ export class AxisAccount extends Emitter {
37
+ /**
38
+ * @param {Axis} axis
39
+ * @param {string} address - Trader address
40
+ * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options]
41
+ */
42
+ constructor(axis, address, {signTransaction, approvalTtl} = {}) {
43
+ super()
44
+ this.axis = axis
45
+ this.address = address
46
+ this.signTransaction = signTransaction
47
+ this.approvalTtl = approvalTtl || APPROVAL_TTL_LEDGERS
48
+ this.ready = new Promise(resolve => this.resolveReady = resolve)
49
+ }
50
+
51
+ /**
52
+ * Trader address
53
+ * @type {string}
54
+ * @readonly
55
+ */
56
+ address
57
+ /**
58
+ * Wallet signing callback, required to trade
59
+ * @type {SignTransactionCallback|undefined}
60
+ */
61
+ signTransaction
62
+ /**
63
+ * Lifetime of the allowances granted by trading calls, in ledgers
64
+ * @type {number}
65
+ */
66
+ approvalTtl
67
+ /**
68
+ * Open orders by id
69
+ * @type {Map<string, AccountOrder>}
70
+ * @readonly
71
+ */
72
+ orders = new Map()
73
+ /**
74
+ * Account backing by token contract id
75
+ * @type {Map<string, AccountBacking>}
76
+ * @readonly
77
+ */
78
+ backing = new Map()
79
+ /**
80
+ * Resolves once the account state has been loaded
81
+ * @type {Promise<void>}
82
+ * @readonly
83
+ */
84
+ ready
85
+ /**
86
+ * Whether the account state has been loaded
87
+ * @type {boolean}
88
+ */
89
+ loaded = false
90
+ /**
91
+ * Orders created by this client that the indexer has not reported yet
92
+ * @type {Map<string, {order: AccountOrder, expires: number}>}
93
+ * @private
94
+ */
95
+ local = new Map()
96
+ /**
97
+ * Whether the backing in memory get updated from the push API
98
+ * @type {boolean}
99
+ * @private
100
+ */
101
+ live = false
102
+ /**
103
+ * Last taker spend of this client by token, UNIX milliseconds
104
+ * @type {Map<string, number>}
105
+ * @private
106
+ */
107
+ spent = new Map() //TODO: drop this
108
+ /**
109
+ * @type {function(): void}
110
+ * @private
111
+ */
112
+ resolveReady
113
+
114
+ /**
115
+ * Start tracking this account
116
+ * @internal
117
+ */
118
+ start() {
119
+ const {stream} = this.axis
120
+ this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))
121
+ this.offOpen = stream.on('open', () => this.stopFallback())
122
+ this.offClose = stream.on('close', () => {
123
+ this.live = false //changes are missed until the next snapshot
124
+ this.startFallback()
125
+ })
126
+ //load over REST if the push API does not deliver the snapshot soon
127
+ this.initTimer = setTimeout(() => {
128
+ if (!this.loaded) {
129
+ this.refresh().catch(() => this.startFallback())
130
+ }
131
+ }, 3_000)
132
+ }
133
+
134
+ /**
135
+ * Stop tracking this account
136
+ */
137
+ close() {
138
+ clearTimeout(this.initTimer)
139
+ this.stopFallback()
140
+ this.unsubscribe?.()
141
+ this.offOpen?.()
142
+ this.offClose?.()
143
+ this.axis.releaseAccount(this)
144
+ }
145
+
146
+ /**
147
+ * Reload current account state from the REST API
148
+ * @return {Promise<void>}
149
+ */
150
+ async refresh() {
151
+ //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances
152
+ this.applySnapshot(await this.axis.api.getAccount(this.address), true)
153
+ }
154
+
155
+ /**
156
+ * Retrieve open orders, newest first
157
+ * @param {{market?: string|{base: string, quote: string}|string[], selling?: string, buying?: string}} [filter] - `market` is an {AxisMarket} or a pair of assets in any order
158
+ * @return {AccountOrder[]}
159
+ */
160
+ getOrders({market, selling, buying} = {}) { //TODO: simplify market argument
161
+ const key = toMarketKey(market)
162
+ const res = []
163
+ for (const order of this.allOrders()) {
164
+ if (key && order.market !== key)
165
+ continue
166
+ if (selling && order.selling !== selling)
167
+ continue
168
+ if (buying && order.buying !== buying)
169
+ continue
170
+ res.push(order)
171
+ }
172
+ return res.sort(newestFirst)
173
+ }
174
+
175
+ /**
176
+ * Get open order by id
177
+ * @param {bigint|string} id
178
+ * @return {AccountOrder|undefined}
179
+ */
180
+ getOrder(id) {
181
+ const key = id.toString()
182
+ return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)
183
+ }
184
+
185
+ /**
186
+ * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)
187
+ * @param {string} asset - Token contract id
188
+ * @return {bigint}
189
+ */
190
+ committed(asset) {
191
+ let sum = 0n
192
+ for (const order of this.allOrders()) {
193
+ if (order.selling === asset) {
194
+ sum += order.amount
195
+ }
196
+ }
197
+ return sum
198
+ }
199
+
200
+ /**
201
+ * Get spendable balance of the account in a token
202
+ * @param {string} asset - Token contract id
203
+ * @return {bigint|undefined} - Undefined if not tracked
204
+ */
205
+ getBalance(asset) {
206
+ const backing = this.backing.get(asset)
207
+ return backing?.updated ? backing.balance : undefined
208
+ }
209
+
210
+ /**
211
+ * Get spendable balances in every tracked token by token contract id
212
+ * @return {Map<string, bigint>}
213
+ */
214
+ get balances() {
215
+ const res = new Map()
216
+ for (const [asset, backing] of this.backing) {
217
+ if (backing.updated) {
218
+ res.set(asset, backing.balance)
219
+ }
220
+ }
221
+ return res
222
+ }
223
+
224
+ /**
225
+ * Whether the account exists on the ledger
226
+ * @return {boolean|undefined}
227
+ */
228
+ get funded() {
229
+ const backing = this.backing.get(this.axis.nativeAsset)
230
+ return backing?.updated ? backing.authorized : undefined
231
+ }
232
+
233
+ /**
234
+ * Get balance, allowance and commitments of the account in a token
235
+ * @param {string} asset - Token contract id
236
+ * @return {AccountAllowance}
237
+ */
238
+ getAllowance(asset) {
239
+ const backing = this.backing.get(asset)
240
+ const committed = this.committed(asset)
241
+ if (!backing?.updated)
242
+ return {asset, known: false, committed}
243
+ return {
244
+ asset,
245
+ known: true,
246
+ balance: backing.balance,
247
+ allowance: backing.allowance,
248
+ liveUntil: backing.liveUntil,
249
+ authorized: backing.authorized,
250
+ pending: backing.pending,
251
+ available: backing.budget,
252
+ committed
253
+ }
254
+ }
255
+
256
+ /**
257
+ * Sell tokens creating a limit remainder order if not executed in full
258
+ * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
259
+ * @return {Promise<TradeResult>}
260
+ */
261
+ async sell(params) {
262
+ return this.trade(TradeDirection.Sell, params)
263
+ }
264
+
265
+ /**
266
+ * Buy tokens creating a limit remainder order if not executed in full
267
+ * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
268
+ * @return {Promise<TradeResult>}
269
+ */
270
+ async buy(params) {
271
+ return this.trade(TradeDirection.Buy, params)
272
+ }
273
+
274
+ /**
275
+ * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it
276
+ * @param {TradeParams} params - Same as `sell`
277
+ * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
278
+ */
279
+ async estimateSell(params) {
280
+ const {payload} = await this.prepareTrade(TradeDirection.Sell, params)
281
+ const client = await this.client()
282
+ return client.estimateSell(payload)
283
+ }
284
+
285
+ /**
286
+ * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
287
+ * @param {TradeParams} params - Same as `buy`
288
+ * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
289
+ */
290
+ async estimateBuy(params) {
291
+ const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
292
+ const client = await this.client()
293
+ return client.estimateBuy(payload)
294
+ }
295
+
296
+ /**
297
+ * Change the amount, price or expiration of open orders (omitted fields keep their current values)
298
+ * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
299
+ * @return {Promise<bigint[]>} - Updated order ids
300
+ */
301
+ async update(updates) {
302
+ await this.whenReady()
303
+ const normalized = updates.map(update => {
304
+ const current = this.getOrder(update.id)
305
+ if (!current && (update.amount === undefined || update.price === undefined))
306
+ throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
307
+ return {
308
+ current,
309
+ update: {
310
+ id: BigInt(update.id),
311
+ amount: update.amount ?? current.amount,
312
+ price: update.price ?? current.price,
313
+ expires: update.expires ?? current?.expires ?? 0
314
+ }
315
+ }
316
+ })
317
+ //extra commitment per sold token
318
+ const growth = new Map()
319
+ for (const {current, update} of normalized) {
320
+ if (!current)
321
+ continue
322
+ growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)
323
+ }
324
+ const approvals = []
325
+ for (const [asset, delta] of growth) {
326
+ if (delta <= 0n)
327
+ continue
328
+ const approve = await this.planApproval(asset, delta)
329
+ if (approve) {
330
+ this.emit('approve', {asset, ...approve})
331
+ approvals.push({asset, ...approve})
332
+ }
333
+ }
334
+ const client = await this.client()
335
+ const res = []
336
+ for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
337
+ const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
338
+ //approvals travel with the first batch, before its backing check
339
+ const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})
340
+ res.push(...ids)
341
+ }
342
+ return res
343
+ }
344
+
345
+ /**
346
+ * Cancel open orders
347
+ * @param {Array<bigint|string>} ids
348
+ * @return {Promise<void>}
349
+ */
350
+ async cancel(ids) {
351
+ const client = await this.client()
352
+ const all = ids.map(id => BigInt(id))
353
+ for (let i = 0; i < all.length; i += UPDATE_BATCH) {
354
+ await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
355
+ }
356
+ for (const id of all) {
357
+ this.local.delete(id.toString())
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Cancel all open orders
363
+ * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
364
+ * @return {Promise<string[]>} - Canceled order ids
365
+ */
366
+ async cancelAll({market} = {}) {
367
+ await this.whenReady()
368
+ const ids = this.getOrders({market}).map(order => order.id)
369
+ if (ids.length) {
370
+ await this.cancel(ids)
371
+ }
372
+ return ids
373
+ }
374
+
375
+ /**
376
+ * Fill an open order against the book while keeping profits from price inefficiencies
377
+ * @param {bigint|string} takerOrderId - Order acting as the taker
378
+ * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted
379
+ * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
380
+ */
381
+ async crossfill(takerOrderId, orders) {
382
+ if (!orders) {
383
+ const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
384
+ if (!taker)
385
+ throw new Error(`Order ${takerOrderId} not found`)
386
+ orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
387
+ }
388
+ const client = await this.client()
389
+ const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
390
+ return {sold, bought, surplus}
391
+ }
392
+
393
+ /**
394
+ * Swap across one or several markets along the best route found by the AXIS API
395
+ * @param {SwapParams} params
396
+ * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
397
+ */
398
+ async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
399
+ await this.whenReady()
400
+ const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
401
+ const quote = direction === TradeDirection.Buy ?
402
+ await this.axis.api.quoteBuy(params) :
403
+ await this.axis.api.quoteSell(params)
404
+ const best = quote.paths?.[0]
405
+ if (quote.status !== 'success' || !best?.path?.length)
406
+ throw new Error(quote.error || 'No route available')
407
+ const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))
408
+ const tolerance = BigInt(Math.round(slippage * 10_000))
409
+ let sellingAmount = BigInt(best.sold)
410
+ let buyingAmount = BigInt(best.bought)
411
+ if (direction === TradeDirection.Buy) {
412
+ sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n
413
+ } else {
414
+ buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n
415
+ }
416
+ //`sellingAmount` is the exact spend of a sell and the most a buy may spend
417
+ const approve = await this.planApproval(selling, sellingAmount)
418
+ if (approve) {
419
+ this.emit('approve', {asset: selling, ...approve})
420
+ }
421
+ const client = await this.client()
422
+ const [sold, bought] = await client.swap({
423
+ direction,
424
+ trader: this.address,
425
+ selling,
426
+ sellingAmount,
427
+ buyingAmount,
428
+ path,
429
+ approve
430
+ })
431
+ this.spent.set(selling, Date.now())
432
+ return {sold, bought, approve}
433
+ }
434
+
435
+ /**
436
+ * Compute approval for a call
437
+ * @param {string} asset - Token contract id
438
+ * @param {bigint} required - Max amount the call may spend
439
+ * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}
440
+ */
441
+ async planApproval(asset, required) {
442
+ await this.whenReady()
443
+ const backing = this.backing.get(asset)
444
+ let allowance
445
+ if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {
446
+ allowance = backing.allowance
447
+ } else {
448
+ const {tokenBalances} = this.axis
449
+ if (!tokenBalances)
450
+ throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
451
+ await this.axis.getContractId() //the allowance spender
452
+ allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
453
+ }
454
+ return planApproval({
455
+ required,
456
+ committed: this.committed(asset),
457
+ allowance,
458
+ liveUntil: backing?.liveUntil ?? 0,
459
+ ledger: await this.axis.getLedger(),
460
+ ttl: this.approvalTtl
461
+ })
462
+ }
463
+
464
+ /**
465
+ * Check whether the pushed allowance of a token can be used as is
466
+ * @param {string} asset - Token contract id
467
+ * @return {boolean}
468
+ * @private
469
+ */
470
+ isAllowanceCurrent(asset) {
471
+ const backing = this.backing.get(asset)
472
+ if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
473
+ return false
474
+ const spent = this.spent.get(asset)
475
+ if (spent === undefined)
476
+ return true
477
+ if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives
478
+ return false //TODO: try to read allowance change from tx result meta changes
479
+ this.spent.delete(asset)
480
+ return true
481
+ }
482
+
483
+ /**
484
+ * @param {number} direction
485
+ * @param {TradeParams} params
486
+ * @return {Promise<TradeResult>}
487
+ * @private
488
+ */
489
+ async trade(direction, params) {
490
+ const {payload, planned} = await this.prepareTrade(direction, params)
491
+ const {selling, buying, amount, price, expires, approve} = payload
492
+ if (planned && approve) {
493
+ this.emit('approve', {asset: selling, ...approve})
494
+ }
495
+ const client = await this.client()
496
+ const [sold, bought, createdId] = direction === TradeDirection.Buy ?
497
+ await client.buy(payload) :
498
+ await client.sell(payload)
499
+ this.spent.set(selling, Date.now())
500
+ let order
501
+ if (createdId) {
502
+ order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})
503
+ }
504
+ return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}
505
+ }
506
+
507
+ /**
508
+ * Resolve the crossing orders, the price of a market order and the approval of a trade
509
+ * @param {number} direction
510
+ * @param {TradeParams} params
511
+ * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,
512
+ * `planned` if the approval was planned by the account rather than supplied
513
+ * @private
514
+ */
515
+ async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {
516
+ await this.whenReady()
517
+ amount = BigInt(amount)
518
+ const market = price === undefined || price === null
519
+ if (kind === undefined) {
520
+ kind = market ? OrderKind.Fill : OrderKind.Limit
521
+ }
522
+ let crossing
523
+ if (!orders || market) {
524
+ //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the
525
+ //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well
526
+ const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))
527
+ crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)
528
+ }
529
+ if (market) {
530
+ //cross everything the quote found: the limit is the worst maker price (makers price `selling` per
531
+ //`buying` of a buyer; seen from a seller, invert it)
532
+ if (!crossing.worstPrice)
533
+ throw new Error('Not enough liquidity for a market order')
534
+ price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)
535
+ }
536
+ price = BigInt(price)
537
+ const planned = approve === undefined
538
+ if (planned) {
539
+ const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount
540
+ approve = await this.planApproval(selling, required)
541
+ }
542
+ const payload = {
543
+ kind,
544
+ trader: this.address,
545
+ amount,
546
+ selling,
547
+ buying,
548
+ price,
549
+ orders: (orders ?? crossing.orders).map(id => BigInt(id)),
550
+ expires,
551
+ approve: approve || undefined
552
+ }
553
+ return {payload, planned}
554
+ }
555
+
556
+ /**
557
+ * Count an order this client created as committed until the indexer reports it
558
+ * @param {bigint} id
559
+ * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read
560
+ * @return {Promise<AccountOrder|undefined>}
561
+ * @private
562
+ */
563
+ async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {
564
+ const key = id.toString()
565
+ if (this.orders.has(key))
566
+ return this.orders.get(key) //already reported
567
+ let stored
568
+ try {
569
+ const client = await this.client()
570
+ stored = await client.order(id)
571
+ } catch (e) {
572
+ //estimate below
573
+ }
574
+ if (this.orders.has(key))
575
+ return this.orders.get(key)
576
+ let orderAmount
577
+ let orderPrice
578
+ if (stored) {
579
+ orderAmount = stored.amount
580
+ orderPrice = stored.price
581
+ } else if (direction === TradeDirection.Sell) {
582
+ orderAmount = amount - sold
583
+ orderPrice = price
584
+ } else {
585
+ //the remainder of a buy sells `selling` for the rest of `buying` at the limit
586
+ orderAmount = maxQuoteSpend(amount - bought, price)
587
+ orderPrice = invertPrice(price)
588
+ }
589
+ const now = Date.now()
590
+ /** @type {AccountOrder} */
591
+ const order = {
592
+ id: key,
593
+ owner: this.address,
594
+ selling,
595
+ buying,
596
+ market: pairKey(selling, buying),
597
+ status: 'ACTIVE',
598
+ price: orderPrice,
599
+ amount: orderAmount,
600
+ quote: orderAmount,
601
+ expires: Number(stored?.expires ?? expires ?? 0),
602
+ created: now,
603
+ updated: now,
604
+ cursor: undefined,
605
+ backed: null,
606
+ backedPct: null,
607
+ backingPending: true,
608
+ filledPct: 0,
609
+ pending: true
610
+ }
611
+ this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})
612
+ this.emit('pending', order)
613
+ this.emit('change')
614
+ return order
615
+ }
616
+
617
+ /**
618
+ * Crossing orders of a direct-market trade and the worst price among them
619
+ * @param {number} direction
620
+ * @param {string} selling
621
+ * @param {string} buying
622
+ * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy
623
+ * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order
624
+ * @return {Promise<{orders: string[], worstPrice: bigint|null}>}
625
+ * @private
626
+ */
627
+ async findQuote(direction, selling, buying, amount, maxPrice) {
628
+ const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}
629
+ try {
630
+ const quote = direction === TradeDirection.Buy ?
631
+ await this.axis.api.quoteBuy(params) :
632
+ await this.axis.api.quoteSell(params)
633
+ const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null
634
+ if (hop)
635
+ return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}
636
+ } catch (e) {
637
+ //nothing to cross: a limit order simply rests
638
+ }
639
+ return {orders: [], worstPrice: null}
640
+ }
641
+
642
+ /**
643
+ * @return {Promise<AxisContractClient>}
644
+ * @private
645
+ */
646
+ async client() {
647
+ if (!this.signTransaction)
648
+ throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
649
+ return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
650
+ }
651
+
652
+ /**
653
+ * @param {number} [timeout]
654
+ * @return {Promise<void>}
655
+ * @private
656
+ */
657
+ async whenReady(timeout = READY_TIMEOUT) {
658
+ if (this.loaded)
659
+ return
660
+ let timer
661
+ try {
662
+ await Promise.race([
663
+ this.ready,
664
+ new Promise((resolve, reject) => {
665
+ timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)
666
+ })
667
+ ])
668
+ } finally {
669
+ clearTimeout(timer)
670
+ }
671
+ }
672
+
673
+ /**
674
+ * @param {StreamMessage} message
675
+ * @private
676
+ */
677
+ handle(message) {
678
+ switch (message.type) {
679
+ case 'account':
680
+ this.live = true
681
+ return this.applySnapshot(message)
682
+ case 'order':
683
+ return this.applyOrder(message)
684
+ case 'backing':
685
+ return this.applyBacking(message)
686
+ case 'trade':
687
+ return this.emit('trade', message.trade)
688
+ case 'swap':
689
+ return this.emit('swap', message.swap)
690
+ case 'error':
691
+ return this.emit('error', new Error(message.error))
692
+ }
693
+ }
694
+
695
+ /**
696
+ * Replace the state with a snapshot
697
+ * @param {ApiAccount} state
698
+ * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot
699
+ * @private
700
+ */
701
+ applySnapshot(state, mergeBacking = false) {
702
+ const previous = this.orders
703
+ const next = new Map()
704
+ for (const raw of state.orders || []) {
705
+ const order = parseApiOrder(raw)
706
+ next.set(order.id, order)
707
+ this.local.delete(order.id)
708
+ }
709
+ this.orders = next
710
+ const backing = mergeBacking ? new Map(this.backing) : new Map()
711
+ for (const [asset, raw] of Object.entries(state.backing || {})) {
712
+ backing.set(asset, parseBacking(asset, raw))
713
+ }
714
+ this.backing = backing
715
+ if (this.loaded) {
716
+ for (const [id, order] of previous) {
717
+ if (!next.has(id)) {
718
+ this.emit('remove', order)
719
+ }
720
+ }
721
+ for (const [id, order] of next) {
722
+ if (!previous.has(id)) {
723
+ this.emit('new', order)
724
+ }
725
+ }
726
+ }
727
+ if (!this.loaded) {
728
+ this.loaded = true
729
+ this.resolveReady()
730
+ this.emit('ready')
731
+ }
732
+ this.emit('change')
733
+ }
734
+
735
+ /**
736
+ * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message
737
+ * @private
738
+ */
739
+ applyOrder({action, order: raw, fill: rawFill}) {
740
+ const order = parseApiOrder(raw)
741
+ this.local.delete(order.id)
742
+ const previous = this.orders.get(order.id)
743
+ const removed = action === 'filled' || action === 'cancel' || action === 'expire'
744
+ if (removed) {
745
+ this.orders.delete(order.id)
746
+ } else {
747
+ if (previous && order.backed === null) {
748
+ //the event serialization may lack the split; keep the last known one until the backing update
749
+ order.backed = previous.backed
750
+ order.backedPct = previous.backedPct
751
+ order.backingPending = previous.backingPending
752
+ }
753
+ this.orders.set(order.id, order)
754
+ }
755
+ const fill = rawFill && {
756
+ order,
757
+ sold: BigInt(rawFill.sold),
758
+ bought: BigInt(rawFill.bought),
759
+ taker: rawFill.taker,
760
+ trade: rawFill.trade?.toString(),
761
+ ts: Number(rawFill.ts) * 1000,
762
+ partial: action === 'fill'
763
+ }
764
+ this.emit(action, fill || order)
765
+ if (removed) {
766
+ this.emit('remove', order)
767
+ }
768
+ this.emit('order', {action, order, fill})
769
+ this.emit('change')
770
+ }
771
+
772
+ /**
773
+ * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message
774
+ * @private
775
+ */
776
+ applyBacking({asset, backing: raw, backed}) {
777
+ const backing = raw ? parseBacking(asset, raw) : undefined
778
+ if (backing) {
779
+ this.backing.set(asset, backing)
780
+ } else {
781
+ this.backing.delete(asset)
782
+ }
783
+ for (const [id, amount] of Object.entries(backed || {})) {
784
+ const order = this.orders.get(id)
785
+ if (!order)
786
+ continue
787
+ order.backed = BigInt(amount)
788
+ order.backedPct = share(order.backed, order.amount)
789
+ order.backingPending = !backing || backing.pending || !backing.updated
790
+ }
791
+ this.emit('backing', {asset, backing})
792
+ this.emit('change')
793
+ }
794
+
795
+ /**
796
+ * @return {Iterable<AccountOrder>}
797
+ * @private
798
+ */
799
+ * allOrders() {
800
+ yield* this.orders.values()
801
+ yield* this.localOrders()
802
+ }
803
+
804
+ /**
805
+ * Get local orders that haven't expired
806
+ * @return {AccountOrder[]}
807
+ * @private
808
+ */
809
+ localOrders() {
810
+ const now = Date.now()
811
+ const res = []
812
+ for (const [id, {order, expires}] of this.local) {
813
+ if (expires < now || this.orders.has(id)) {
814
+ this.local.delete(id)
815
+ } else {
816
+ res.push(order)
817
+ }
818
+ }
819
+ return res
820
+ }
821
+
822
+ /**
823
+ * @private
824
+ */
825
+ startFallback() {
826
+ if (this.fallbackTimer)
827
+ return
828
+ this.fallbackTimer = setInterval(() => {
829
+ this.refresh().catch(() => {
830
+ //retried on the next tick
831
+ })
832
+ }, this.axis.fallbackPollInterval)
833
+ }
834
+
835
+ /**
836
+ * @private
837
+ */
838
+ stopFallback() {
839
+ clearInterval(this.fallbackTimer)
840
+ this.fallbackTimer = undefined
841
+ }
842
+ }
843
+
844
+ /**
845
+ * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)
846
+ * @param {ApiOrder} raw
847
+ * @return {AccountOrder}
848
+ */
849
+ export function parseApiOrder(raw) {
850
+ const amount = BigInt(raw.amount)
851
+ const quote = BigInt(raw.quote ?? raw.amount)
852
+ //unconfirmed until loaded, and while a reload confirming the latest event is due
853
+ const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending
854
+ const backed = raw.backed !== undefined ? BigInt(raw.backed) : null
855
+ return {
856
+ id: raw.id,
857
+ owner: raw.owner,
858
+ selling: raw.selling,
859
+ buying: raw.buying,
860
+ market: pairKey(raw.selling, raw.buying),
861
+ status: raw.status,
862
+ price: BigInt(raw.price),
863
+ amount,
864
+ quote,
865
+ expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,
866
+ created: parseApiDate(raw.created),
867
+ updated: parseApiDate(raw.updated),
868
+ cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,
869
+ backed,
870
+ backedPct: backed === null ? null : share(backed, amount),
871
+ backingPending: !confirmed,
872
+ filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,
873
+ pending: false
874
+ }
875
+ }
876
+
877
+ /**
878
+ * @param {string} asset
879
+ * @param {ApiBacking} raw
880
+ * @return {AccountBacking}
881
+ */
882
+ function parseBacking(asset, raw) {
883
+ return {
884
+ asset,
885
+ balance: BigInt(raw.balance),
886
+ allowance: BigInt(raw.allowance),
887
+ liveUntil: raw.liveUntil || 0,
888
+ authorized: raw.authorized !== false,
889
+ budget: BigInt(raw.budget ?? 0),
890
+ updated: parseApiDate(raw.updated),
891
+ skipped: parseApiDate(raw.skipped),
892
+ pending: raw.pending === true
893
+ }
894
+ }
895
+
896
+ /**
897
+ * @param {bigint} part
898
+ * @param {bigint} total
899
+ * @return {number} - 0..1
900
+ */
901
+ function share(part, total) {
902
+ if (total <= 0n)
903
+ return 1
904
+ return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
905
+ }
906
+
907
+ /**
908
+ * @param {string|{base: string, quote: string}|string[]|undefined} market
909
+ * @return {string|undefined}
910
+ */
911
+ function toMarketKey(market) {
912
+ if (!market)
913
+ return undefined
914
+ if (typeof market === 'string') {
915
+ const [x, y] = market.split('/')
916
+ return pairKey(x, y)
917
+ }
918
+ if (Array.isArray(market))
919
+ return pairKey(market[0], market[1])
920
+ return pairKey(market.base, market.quote)
921
+ }
922
+
923
+ /**
924
+ * Newest first: unconfirmed local orders, then by creation position
925
+ * @param {AccountOrder} x
926
+ * @param {AccountOrder} y
927
+ * @return {number}
928
+ */
929
+ function newestFirst(x, y) {
930
+ if (x.cursor === undefined || y.cursor === undefined)
931
+ return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created
932
+ return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0
933
+ }
934
+
935
+ /**
936
+ * @typedef {{}} AccountOrder - Open order of a tracked account
937
+ * @property {string} id - Order id (decimal u128)
938
+ * @property {string} owner - Maker address
939
+ * @property {string} selling - Sold token
940
+ * @property {string} buying - Bought token
941
+ * @property {string} market - Market key
942
+ * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status
943
+ * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)
944
+ * @property {bigint} amount - Amount of `selling` left
945
+ * @property {bigint} quote - Amount of `selling` at creation
946
+ * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none
947
+ * @property {number} created - Creation time, UNIX milliseconds
948
+ * @property {number} updated - Last change, UNIX milliseconds
949
+ * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)
950
+ * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order
951
+ * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown
952
+ * @property {boolean} backingPending - The backing is not confirmed yet
953
+ * @property {number} filledPct - Filled share of the initial amount (0..1)
954
+ * @property {boolean} pending - Created by this client, not reported by the indexer yet
955
+ */
956
+
957
+ /**
958
+ * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer
959
+ * @property {string} asset
960
+ * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)
961
+ * @property {bigint} allowance - Allowance granted to the AXIS contract
962
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
963
+ * @property {boolean} authorized - Whether the account can send and receive the token
964
+ * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired
965
+ * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)
966
+ * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)
967
+ * @property {boolean} pending - A reload confirming the latest change is due
968
+ */
969
+
970
+ /**
971
+ * @typedef {{}} AccountAllowance
972
+ * @property {string} asset
973
+ * @property {boolean} known - Whether the backing is tracked and loaded
974
+ * @property {bigint} [balance]
975
+ * @property {bigint} [allowance]
976
+ * @property {number} [liveUntil]
977
+ * @property {boolean} [authorized]
978
+ * @property {boolean} [pending]
979
+ * @property {bigint} [available] - min(balance, allowance)
980
+ * @property {bigint} committed - Remaining amount of the open orders selling the token
981
+ */
982
+
983
+ /**
984
+ * @typedef {{}} AccountFill
985
+ * @property {AccountOrder} order - Order after the fill
986
+ * @property {bigint} sold - Amount of `selling` delivered
987
+ * @property {bigint} bought - Amount of `buying` received
988
+ * @property {string} taker - Taker address
989
+ * @property {string} trade - Trade id
990
+ * @property {number} ts - Trade time, UNIX milliseconds
991
+ * @property {boolean} partial - Whether the order is still open
992
+ */
993
+
994
+ /**
995
+ * @typedef {{}} TradeParams
996
+ * @property {string} selling - Token sent
997
+ * @property {string} buying - Token received
998
+ * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
999
+ * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order
1000
+ * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order
1001
+ * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder
1002
+ * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted
1003
+ * @property {Approval|null} [approve] - Explicit approval (`null` for none)
1004
+ */
1005
+
1006
+ /**
1007
+ * @typedef {{}} TradeResult
1008
+ * @property {bigint} sold - Amount of `selling` sent
1009
+ * @property {bigint} bought - Amount of `buying` received
1010
+ * @property {string} [orderId] - ID of the order created for a limit remainder
1011
+ * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)
1012
+ * @property {Approval} [approve] - Approval granted with the trade
1013
+ */
1014
+
1015
+ /**
1016
+ * @typedef {{}} SwapParams
1017
+ * @property {string} selling - Token sent
1018
+ * @property {string} buying - Token received
1019
+ * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1020
+ * @property {number} [direction] - {@link TradeDirection}, `Sell` by default
1021
+ * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default
1022
+ */