@axis-markets/client 0.8.1 → 0.8.2

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,1009 +1,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} 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
- return this.client().estimateSell(payload)
276
- }
277
-
278
- /**
279
- * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
280
- * @param {TradeParams} params - Same as `buy`
281
- * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
282
- */
283
- async estimateBuy(params) {
284
- const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
285
- return this.client().estimateBuy(payload)
286
- }
287
-
288
- /**
289
- * Change the amount, price or expiration of open orders (omitted fields keep their current values)
290
- * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
291
- * @return {Promise<bigint[]>} - Updated order ids
292
- */
293
- async update(updates) {
294
- await this.whenReady()
295
- const normalized = updates.map(update => {
296
- const current = this.getOrder(update.id)
297
- if (!current && (update.amount === undefined || update.price === undefined))
298
- throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
299
- return {
300
- current,
301
- update: {
302
- id: BigInt(update.id),
303
- amount: update.amount ?? current.amount,
304
- price: update.price ?? current.price,
305
- expires: update.expires ?? current?.expires ?? 0
306
- }
307
- }
308
- })
309
- //extra commitment per sold token
310
- const growth = new Map()
311
- for (const {current, update} of normalized) {
312
- if (!current)
313
- continue
314
- growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)
315
- }
316
- const approvals = []
317
- for (const [asset, delta] of growth) {
318
- if (delta <= 0n)
319
- continue
320
- const approve = await this.planApproval(asset, delta)
321
- if (approve) {
322
- this.emit('approve', {asset, ...approve})
323
- approvals.push({asset, ...approve})
324
- }
325
- }
326
- const client = this.client()
327
- const res = []
328
- for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
329
- const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
330
- //approvals travel with the first batch, before its backing check
331
- const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})
332
- res.push(...ids)
333
- }
334
- return res
335
- }
336
-
337
- /**
338
- * Cancel open orders
339
- * @param {Array<bigint|string>} ids
340
- * @return {Promise<void>}
341
- */
342
- async cancel(ids) {
343
- const client = this.client()
344
- const all = ids.map(id => BigInt(id))
345
- for (let i = 0; i < all.length; i += UPDATE_BATCH) {
346
- await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
347
- }
348
- for (const id of all) {
349
- this.local.delete(id.toString())
350
- }
351
- }
352
-
353
- /**
354
- * Cancel all open orders
355
- * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
356
- * @return {Promise<string[]>} - Canceled order ids
357
- */
358
- async cancelAll({market} = {}) {
359
- await this.whenReady()
360
- const ids = this.getOrders({market}).map(order => order.id)
361
- if (ids.length) {
362
- await this.cancel(ids)
363
- }
364
- return ids
365
- }
366
-
367
- /**
368
- * Fill an open order against the book while keeping profits from price inefficiencies
369
- * @param {bigint|string} takerOrderId - Order acting as the taker
370
- * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted
371
- * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
372
- */
373
- async crossfill(takerOrderId, orders) {
374
- if (!orders) {
375
- const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
376
- if (!taker)
377
- throw new Error(`Order ${takerOrderId} not found`)
378
- orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
379
- }
380
- const [sold, bought, surplus] = await this.client().crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
381
- return {sold, bought, surplus}
382
- }
383
-
384
- /**
385
- * Swap across one or several markets along the best route found by the AXIS API
386
- * @param {SwapParams} params
387
- * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
388
- */
389
- async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
390
- await this.whenReady()
391
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
392
- const quote = direction === TradeDirection.Buy ?
393
- await this.axis.api.quoteBuy(params) :
394
- await this.axis.api.quoteSell(params)
395
- const best = quote.paths?.[0]
396
- if (quote.status !== 'success' || !best?.path?.length)
397
- throw new Error(quote.error || 'No route available')
398
- const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))
399
- const tolerance = BigInt(Math.round(slippage * 10_000))
400
- let sellingAmount = BigInt(best.sold)
401
- let buyingAmount = BigInt(best.bought)
402
- if (direction === TradeDirection.Buy) {
403
- sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n
404
- } else {
405
- buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n
406
- }
407
- //`sellingAmount` is the exact spend of a sell and the most a buy may spend
408
- const approve = await this.planApproval(selling, sellingAmount)
409
- if (approve) {
410
- this.emit('approve', {asset: selling, ...approve})
411
- }
412
- const [sold, bought] = await this.client().swap({
413
- direction,
414
- trader: this.address,
415
- selling,
416
- sellingAmount,
417
- buyingAmount,
418
- path,
419
- approve
420
- })
421
- this.spent.set(selling, Date.now())
422
- return {sold, bought, approve}
423
- }
424
-
425
- /**
426
- * Compute approval for a call
427
- * @param {string} asset - Token contract id
428
- * @param {bigint} required - Max amount the call may spend
429
- * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}
430
- */
431
- async planApproval(asset, required) {
432
- await this.whenReady()
433
- const backing = this.backing.get(asset)
434
- let allowance
435
- if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {
436
- allowance = backing.allowance
437
- } else {
438
- const {tokenBalances} = this.axis
439
- if (!tokenBalances)
440
- throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
441
- allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
442
- }
443
- return planApproval({
444
- required,
445
- committed: this.committed(asset),
446
- allowance,
447
- liveUntil: backing?.liveUntil ?? 0,
448
- ledger: await this.axis.getLedger()
449
- })
450
- }
451
-
452
- /**
453
- * Check whether the pushed allowance of a token can be used as is
454
- * @param {string} asset - Token contract id
455
- * @return {boolean}
456
- * @private
457
- */
458
- isAllowanceCurrent(asset) {
459
- const backing = this.backing.get(asset)
460
- if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
461
- return false
462
- const spent = this.spent.get(asset)
463
- if (spent === undefined)
464
- return true
465
- if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives
466
- return false //TODO: try to read allowance change from tx result meta changes
467
- this.spent.delete(asset)
468
- return true
469
- }
470
-
471
- /**
472
- * @param {number} direction
473
- * @param {TradeParams} params
474
- * @return {Promise<TradeResult>}
475
- * @private
476
- */
477
- async trade(direction, params) {
478
- const {payload, planned} = await this.prepareTrade(direction, params)
479
- const {selling, buying, amount, price, expires, approve} = payload
480
- if (planned && approve) {
481
- this.emit('approve', {asset: selling, ...approve})
482
- }
483
- const client = this.client()
484
- const [sold, bought, createdId] = direction === TradeDirection.Buy ?
485
- await client.buy(payload) :
486
- await client.sell(payload)
487
- this.spent.set(selling, Date.now())
488
- let order
489
- if (createdId) {
490
- order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})
491
- }
492
- return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}
493
- }
494
-
495
- /**
496
- * Resolve the crossing orders, the price of a market order and the approval of a trade
497
- * @param {number} direction
498
- * @param {TradeParams} params
499
- * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,
500
- * `planned` if the approval was planned by the account rather than supplied
501
- * @private
502
- */
503
- async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {
504
- await this.whenReady()
505
- amount = BigInt(amount)
506
- const market = price === undefined || price === null
507
- if (kind === undefined) {
508
- kind = market ? OrderKind.Fill : OrderKind.Limit
509
- }
510
- let crossing
511
- if (!orders || market) {
512
- //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the
513
- //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well
514
- const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))
515
- crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)
516
- }
517
- if (market) {
518
- //cross everything the quote found: the limit is the worst maker price (makers price `selling` per
519
- //`buying` of a buyer; seen from a seller, invert it)
520
- if (!crossing.worstPrice)
521
- throw new Error('Not enough liquidity for a market order')
522
- price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)
523
- }
524
- price = BigInt(price)
525
- const planned = approve === undefined
526
- if (planned) {
527
- const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount
528
- approve = await this.planApproval(selling, required)
529
- }
530
- const payload = {
531
- kind,
532
- trader: this.address,
533
- amount,
534
- selling,
535
- buying,
536
- price,
537
- orders: (orders ?? crossing.orders).map(id => BigInt(id)),
538
- expires,
539
- approve: approve || undefined
540
- }
541
- return {payload, planned}
542
- }
543
-
544
- /**
545
- * Count an order this client created as committed until the indexer reports it
546
- * @param {bigint} id
547
- * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read
548
- * @return {Promise<AccountOrder|undefined>}
549
- * @private
550
- */
551
- async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {
552
- const key = id.toString()
553
- if (this.orders.has(key))
554
- return this.orders.get(key) //already reported
555
- let stored
556
- try {
557
- stored = await this.client().order(id)
558
- } catch (e) {
559
- //estimate below
560
- }
561
- if (this.orders.has(key))
562
- return this.orders.get(key)
563
- let orderAmount
564
- let orderPrice
565
- if (stored) {
566
- orderAmount = stored.amount
567
- orderPrice = stored.price
568
- } else if (direction === TradeDirection.Sell) {
569
- orderAmount = amount - sold
570
- orderPrice = price
571
- } else {
572
- //the remainder of a buy sells `selling` for the rest of `buying` at the limit
573
- orderAmount = maxQuoteSpend(amount - bought, price)
574
- orderPrice = invertPrice(price)
575
- }
576
- const now = Date.now()
577
- /** @type {AccountOrder} */
578
- const order = {
579
- id: key,
580
- owner: this.address,
581
- selling,
582
- buying,
583
- market: pairKey(selling, buying),
584
- status: 'ACTIVE',
585
- price: orderPrice,
586
- amount: orderAmount,
587
- quote: orderAmount,
588
- expires: Number(stored?.expires ?? expires ?? 0),
589
- created: now,
590
- updated: now,
591
- cursor: undefined,
592
- backed: null,
593
- backedPct: null,
594
- backingPending: true,
595
- filledPct: 0,
596
- pending: true
597
- }
598
- this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})
599
- this.emit('pending', order)
600
- this.emit('change')
601
- return order
602
- }
603
-
604
- /**
605
- * Crossing orders of a direct-market trade and the worst price among them
606
- * @param {number} direction
607
- * @param {string} selling
608
- * @param {string} buying
609
- * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy
610
- * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order
611
- * @return {Promise<{orders: string[], worstPrice: bigint|null}>}
612
- * @private
613
- */
614
- async findQuote(direction, selling, buying, amount, maxPrice) {
615
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}
616
- try {
617
- const quote = direction === TradeDirection.Buy ?
618
- await this.axis.api.quoteBuy(params) :
619
- await this.axis.api.quoteSell(params)
620
- const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null
621
- if (hop)
622
- return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}
623
- } catch (e) {
624
- //nothing to cross: a limit order simply rests
625
- }
626
- return {orders: [], worstPrice: null}
627
- }
628
-
629
- /**
630
- * @return {AxisContractClient}
631
- * @private
632
- */
633
- client() {
634
- if (!this.signTransaction)
635
- throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
636
- return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
637
- }
638
-
639
- /**
640
- * @param {number} [timeout]
641
- * @return {Promise<void>}
642
- * @private
643
- */
644
- async whenReady(timeout = READY_TIMEOUT) {
645
- if (this.loaded)
646
- return
647
- let timer
648
- try {
649
- await Promise.race([
650
- this.ready,
651
- new Promise((resolve, reject) => {
652
- timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)
653
- })
654
- ])
655
- } finally {
656
- clearTimeout(timer)
657
- }
658
- }
659
-
660
- /**
661
- * @param {StreamMessage} message
662
- * @private
663
- */
664
- handle(message) {
665
- switch (message.type) {
666
- case 'account':
667
- this.live = true
668
- return this.applySnapshot(message)
669
- case 'order':
670
- return this.applyOrder(message)
671
- case 'backing':
672
- return this.applyBacking(message)
673
- case 'trade':
674
- return this.emit('trade', message.trade)
675
- case 'swap':
676
- return this.emit('swap', message.swap)
677
- case 'error':
678
- return this.emit('error', new Error(message.error))
679
- }
680
- }
681
-
682
- /**
683
- * Replace the state with a snapshot
684
- * @param {ApiAccount} state
685
- * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot
686
- * @private
687
- */
688
- applySnapshot(state, mergeBacking = false) {
689
- const previous = this.orders
690
- const next = new Map()
691
- for (const raw of state.orders || []) {
692
- const order = parseApiOrder(raw)
693
- next.set(order.id, order)
694
- this.local.delete(order.id)
695
- }
696
- this.orders = next
697
- const backing = mergeBacking ? new Map(this.backing) : new Map()
698
- for (const [asset, raw] of Object.entries(state.backing || {})) {
699
- backing.set(asset, parseBacking(asset, raw))
700
- }
701
- this.backing = backing
702
- if (this.loaded) {
703
- for (const [id, order] of previous) {
704
- if (!next.has(id)) {
705
- this.emit('remove', order)
706
- }
707
- }
708
- for (const [id, order] of next) {
709
- if (!previous.has(id)) {
710
- this.emit('new', order)
711
- }
712
- }
713
- }
714
- if (!this.loaded) {
715
- this.loaded = true
716
- this.resolveReady()
717
- this.emit('ready')
718
- }
719
- this.emit('change')
720
- }
721
-
722
- /**
723
- * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message
724
- * @private
725
- */
726
- applyOrder({action, order: raw, fill: rawFill}) {
727
- const order = parseApiOrder(raw)
728
- this.local.delete(order.id)
729
- const previous = this.orders.get(order.id)
730
- const removed = action === 'filled' || action === 'cancel' || action === 'expire'
731
- if (removed) {
732
- this.orders.delete(order.id)
733
- } else {
734
- if (previous && order.backed === null) {
735
- //the event serialization may lack the split; keep the last known one until the backing update
736
- order.backed = previous.backed
737
- order.backedPct = previous.backedPct
738
- order.backingPending = previous.backingPending
739
- }
740
- this.orders.set(order.id, order)
741
- }
742
- const fill = rawFill && {
743
- order,
744
- sold: BigInt(rawFill.sold),
745
- bought: BigInt(rawFill.bought),
746
- taker: rawFill.taker,
747
- trade: rawFill.trade?.toString(),
748
- ts: Number(rawFill.ts) * 1000,
749
- partial: action === 'fill'
750
- }
751
- this.emit(action, fill || order)
752
- if (removed) {
753
- this.emit('remove', order)
754
- }
755
- this.emit('order', {action, order, fill})
756
- this.emit('change')
757
- }
758
-
759
- /**
760
- * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message
761
- * @private
762
- */
763
- applyBacking({asset, backing: raw, backed}) {
764
- const backing = raw ? parseBacking(asset, raw) : undefined
765
- if (backing) {
766
- this.backing.set(asset, backing)
767
- } else {
768
- this.backing.delete(asset)
769
- }
770
- for (const [id, amount] of Object.entries(backed || {})) {
771
- const order = this.orders.get(id)
772
- if (!order)
773
- continue
774
- order.backed = BigInt(amount)
775
- order.backedPct = share(order.backed, order.amount)
776
- order.backingPending = !backing || backing.pending || !backing.updated
777
- }
778
- this.emit('backing', {asset, backing})
779
- this.emit('change')
780
- }
781
-
782
- /**
783
- * @return {Iterable<AccountOrder>}
784
- * @private
785
- */
786
- * allOrders() {
787
- yield* this.orders.values()
788
- yield* this.localOrders()
789
- }
790
-
791
- /**
792
- * Get local orders that haven't expired
793
- * @return {AccountOrder[]}
794
- * @private
795
- */
796
- localOrders() {
797
- const now = Date.now()
798
- const res = []
799
- for (const [id, {order, expires}] of this.local) {
800
- if (expires < now || this.orders.has(id)) {
801
- this.local.delete(id)
802
- } else {
803
- res.push(order)
804
- }
805
- }
806
- return res
807
- }
808
-
809
- /**
810
- * @private
811
- */
812
- startFallback() {
813
- if (this.fallbackTimer)
814
- return
815
- this.fallbackTimer = setInterval(() => {
816
- this.refresh().catch(() => {
817
- //retried on the next tick
818
- })
819
- }, this.axis.fallbackPollInterval)
820
- }
821
-
822
- /**
823
- * @private
824
- */
825
- stopFallback() {
826
- clearInterval(this.fallbackTimer)
827
- this.fallbackTimer = undefined
828
- }
829
- }
830
-
831
- /**
832
- * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)
833
- * @param {ApiOrder} raw
834
- * @return {AccountOrder}
835
- */
836
- export function parseApiOrder(raw) {
837
- const amount = BigInt(raw.amount)
838
- const quote = BigInt(raw.quote ?? raw.amount)
839
- //unconfirmed until loaded, and while a reload confirming the latest event is due
840
- const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending
841
- const backed = raw.backed !== undefined ? BigInt(raw.backed) : null
842
- return {
843
- id: raw.id,
844
- owner: raw.owner,
845
- selling: raw.selling,
846
- buying: raw.buying,
847
- market: pairKey(raw.selling, raw.buying),
848
- status: raw.status,
849
- price: BigInt(raw.price),
850
- amount,
851
- quote,
852
- expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,
853
- created: parseApiDate(raw.created),
854
- updated: parseApiDate(raw.updated),
855
- cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,
856
- backed,
857
- backedPct: backed === null ? null : share(backed, amount),
858
- backingPending: !confirmed,
859
- filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,
860
- pending: false
861
- }
862
- }
863
-
864
- /**
865
- * @param {string} asset
866
- * @param {ApiBacking} raw
867
- * @return {AccountBacking}
868
- */
869
- function parseBacking(asset, raw) {
870
- return {
871
- asset,
872
- balance: BigInt(raw.balance),
873
- allowance: BigInt(raw.allowance),
874
- liveUntil: raw.liveUntil || 0,
875
- authorized: raw.authorized !== false,
876
- budget: BigInt(raw.budget ?? 0),
877
- updated: parseApiDate(raw.updated),
878
- skipped: parseApiDate(raw.skipped),
879
- pending: raw.pending === true
880
- }
881
- }
882
-
883
- /**
884
- * @param {bigint} part
885
- * @param {bigint} total
886
- * @return {number} - 0..1
887
- */
888
- function share(part, total) {
889
- if (total <= 0n)
890
- return 1
891
- return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
892
- }
893
-
894
- /**
895
- * @param {string|{base: string, quote: string}|string[]|undefined} market
896
- * @return {string|undefined}
897
- */
898
- function toMarketKey(market) {
899
- if (!market)
900
- return undefined
901
- if (typeof market === 'string') {
902
- const [x, y] = market.split('/')
903
- return pairKey(x, y)
904
- }
905
- if (Array.isArray(market))
906
- return pairKey(market[0], market[1])
907
- return pairKey(market.base, market.quote)
908
- }
909
-
910
- /**
911
- * Newest first: unconfirmed local orders, then by creation position
912
- * @param {AccountOrder} x
913
- * @param {AccountOrder} y
914
- * @return {number}
915
- */
916
- function newestFirst(x, y) {
917
- if (x.cursor === undefined || y.cursor === undefined)
918
- return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created
919
- return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0
920
- }
921
-
922
- /**
923
- * @typedef {{}} AccountOrder - Open order of a tracked account
924
- * @property {string} id - Order id (decimal u128)
925
- * @property {string} owner - Maker address
926
- * @property {string} selling - Sold token
927
- * @property {string} buying - Bought token
928
- * @property {string} market - Market key
929
- * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status
930
- * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)
931
- * @property {bigint} amount - Amount of `selling` left
932
- * @property {bigint} quote - Amount of `selling` at creation
933
- * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none
934
- * @property {number} created - Creation time, UNIX milliseconds
935
- * @property {number} updated - Last change, UNIX milliseconds
936
- * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)
937
- * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order
938
- * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown
939
- * @property {boolean} backingPending - The backing is not confirmed yet
940
- * @property {number} filledPct - Filled share of the initial amount (0..1)
941
- * @property {boolean} pending - Created by this client, not reported by the indexer yet
942
- */
943
-
944
- /**
945
- * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer
946
- * @property {string} asset
947
- * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)
948
- * @property {bigint} allowance - Allowance granted to the AXIS contract
949
- * @property {number} liveUntil - Ledger sequence the allowance lives until
950
- * @property {boolean} authorized - Whether the account can send and receive the token
951
- * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired
952
- * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)
953
- * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)
954
- * @property {boolean} pending - A reload confirming the latest change is due
955
- */
956
-
957
- /**
958
- * @typedef {{}} AccountAllowance
959
- * @property {string} asset
960
- * @property {boolean} known - Whether the backing is tracked and loaded
961
- * @property {bigint} [balance]
962
- * @property {bigint} [allowance]
963
- * @property {number} [liveUntil]
964
- * @property {boolean} [authorized]
965
- * @property {boolean} [pending]
966
- * @property {bigint} [available] - min(balance, allowance)
967
- * @property {bigint} committed - Remaining amount of the open orders selling the token
968
- */
969
-
970
- /**
971
- * @typedef {{}} AccountFill
972
- * @property {AccountOrder} order - Order after the fill
973
- * @property {bigint} sold - Amount of `selling` delivered
974
- * @property {bigint} bought - Amount of `buying` received
975
- * @property {string} taker - Taker address
976
- * @property {string} trade - Trade id
977
- * @property {number} ts - Trade time, UNIX milliseconds
978
- * @property {boolean} partial - Whether the order is still open
979
- */
980
-
981
- /**
982
- * @typedef {{}} TradeParams
983
- * @property {string} selling - Token sent
984
- * @property {string} buying - Token received
985
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
986
- * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order
987
- * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order
988
- * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder
989
- * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted
990
- * @property {Approval|null} [approve] - Explicit approval (`null` for none)
991
- */
992
-
993
- /**
994
- * @typedef {{}} TradeResult
995
- * @property {bigint} sold - Amount of `selling` sent
996
- * @property {bigint} bought - Amount of `buying` received
997
- * @property {string} [orderId] - ID of the order created for a limit remainder
998
- * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)
999
- * @property {Approval} [approve] - Approval granted with the trade
1000
- */
1001
-
1002
- /**
1003
- * @typedef {{}} SwapParams
1004
- * @property {string} selling - Token sent
1005
- * @property {string} buying - Token received
1006
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1007
- * @property {number} [direction] - {@link TradeDirection}, `Sell` by default
1008
- * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default
1009
- */
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
+ */