@axis-markets/client 0.4.0 → 0.7.0

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