@axis-markets/client 0.8.2 → 0.9.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.
@@ -1,1015 +1,1376 @@
1
- import {Emitter} from './emitter.js'
2
- import {pairKey, invertPrice} from './asset-pair.js'
3
- import {parseApiDate} from './api-dates.js'
4
- import {planApproval, maxQuoteSpend} from './allowance.js'
5
- import {OrderKind, TradeDirection} from './constants.js'
6
-
7
- /** Orders per `update` transaction */
8
- const UPDATE_BATCH = 90
9
- /** Time to wait for the account state before trading, in milliseconds */
10
- const READY_TIMEOUT = 15_000
11
- /** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */
12
- const LOCAL_ORDER_TTL = 120_000
13
-
14
- /**
15
- * Trader wrapper that tracks every open order of an account across all markets and the account backing.
16
- * Create it with {@link import('./axis.js').Axis#account}.
17
- *
18
- * Emits:
19
- * - `ready` - the account state was loaded
20
- * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
21
- * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
22
- * - `fill` {@link AccountFill} - an order was partially filled
23
- * - `filled` {@link AccountFill} - an order was filled in full
24
- * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
25
- * - `cancel` {@link AccountOrder} - an order was removed by the owner
26
- * - `expire` {@link AccountOrder} - an order expired
27
- * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
28
- * - `order` `{action, order, fill?}` - any order change
29
- * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
30
- * - `approve` `{asset, amount, liveUntil}` - a trading call is about to grant an allowance
31
- * - `trade` {ApiTrade} - the account performed a trade
32
- * - `swap` {ApiSwap} - the account performed a swap
33
- * - `change` - the open orders or the backing changed
34
- * - `error` `Error` - the push API rejected the account subscription
35
- */
36
- export class AxisAccount extends Emitter {
37
- /**
38
- * @param {Axis} axis
39
- * @param {string} address - Trader address
40
- * @param {{signTransaction?: SignTransactionCallback}} [options]
41
- */
42
- constructor(axis, address, {signTransaction} = {}) {
43
- super()
44
- this.axis = axis
45
- this.address = address
46
- this.signTransaction = signTransaction
47
- this.ready = new Promise(resolve => this.resolveReady = resolve)
48
- }
49
-
50
- /**
51
- * Trader address
52
- * @type {string}
53
- * @readonly
54
- */
55
- address
56
- /**
57
- * Wallet signing callback, required to trade
58
- * @type {SignTransactionCallback|undefined}
59
- */
60
- signTransaction
61
- /**
62
- * Open orders by id
63
- * @type {Map<string, AccountOrder>}
64
- * @readonly
65
- */
66
- orders = new Map()
67
- /**
68
- * Account backing by token contract id
69
- * @type {Map<string, AccountBacking>}
70
- * @readonly
71
- */
72
- backing = new Map()
73
- /**
74
- * Resolves once the account state has been loaded
75
- * @type {Promise<void>}
76
- * @readonly
77
- */
78
- ready
79
- /**
80
- * Whether the account state has been loaded
81
- * @type {boolean}
82
- */
83
- loaded = false
84
- /**
85
- * Orders created by this client that the indexer has not reported yet
86
- * @type {Map<string, {order: AccountOrder, expires: number}>}
87
- * @private
88
- */
89
- local = new Map()
90
- /**
91
- * Whether the backing in memory get updated from the push API
92
- * @type {boolean}
93
- * @private
94
- */
95
- live = false
96
- /**
97
- * Last taker spend of this client by token, UNIX milliseconds
98
- * @type {Map<string, number>}
99
- * @private
100
- */
101
- spent = new Map() //TODO: drop this
102
- /**
103
- * @type {function(): void}
104
- * @private
105
- */
106
- resolveReady
107
-
108
- /**
109
- * Start tracking this account
110
- * @internal
111
- */
112
- start() {
113
- const {stream} = this.axis
114
- this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))
115
- this.offOpen = stream.on('open', () => this.stopFallback())
116
- this.offClose = stream.on('close', () => {
117
- this.live = false //changes are missed until the next snapshot
118
- this.startFallback()
119
- })
120
- //load over REST if the push API does not deliver the snapshot soon
121
- this.initTimer = setTimeout(() => {
122
- if (!this.loaded) {
123
- this.refresh().catch(() => this.startFallback())
124
- }
125
- }, 3_000)
126
- }
127
-
128
- /**
129
- * Stop tracking this account
130
- */
131
- close() {
132
- clearTimeout(this.initTimer)
133
- this.stopFallback()
134
- this.unsubscribe?.()
135
- this.offOpen?.()
136
- this.offClose?.()
137
- this.axis.releaseAccount(this)
138
- }
139
-
140
- /**
141
- * Reload current account state from the REST API
142
- * @return {Promise<void>}
143
- */
144
- async refresh() {
145
- //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances
146
- this.applySnapshot(await this.axis.api.getAccount(this.address), true)
147
- }
148
-
149
- /**
150
- * Retrieve open orders, newest first
151
- * @param {{market?: string|{base: string, quote: string}|string[], selling?: string, buying?: string}} [filter] - `market` is an {AxisMarket} or a pair of assets in any order
152
- * @return {AccountOrder[]}
153
- */
154
- getOrders({market, selling, buying} = {}) { //TODO: simplify market argument
155
- const key = toMarketKey(market)
156
- const res = []
157
- for (const order of this.allOrders()) {
158
- if (key && order.market !== key)
159
- continue
160
- if (selling && order.selling !== selling)
161
- continue
162
- if (buying && order.buying !== buying)
163
- continue
164
- res.push(order)
165
- }
166
- return res.sort(newestFirst)
167
- }
168
-
169
- /**
170
- * Get open order by id
171
- * @param {bigint|string} id
172
- * @return {AccountOrder|undefined}
173
- */
174
- getOrder(id) {
175
- const key = id.toString()
176
- return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)
177
- }
178
-
179
- /**
180
- * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)
181
- * @param {string} asset - Token contract id
182
- * @return {bigint}
183
- */
184
- committed(asset) {
185
- let sum = 0n
186
- for (const order of this.allOrders()) {
187
- if (order.selling === asset) {
188
- sum += order.amount
189
- }
190
- }
191
- return sum
192
- }
193
-
194
- /**
195
- * Get spendable balance of the account in a token
196
- * @param {string} asset - Token contract id
197
- * @return {bigint|undefined} - Undefined if not tracked
198
- */
199
- getBalance(asset) {
200
- const backing = this.backing.get(asset)
201
- return backing?.updated ? backing.balance : undefined
202
- }
203
-
204
- /**
205
- * Get spendable balances in every tracked token by token contract id
206
- * @return {Map<string, bigint>}
207
- */
208
- get balances() {
209
- const res = new Map()
210
- for (const [asset, backing] of this.backing) {
211
- if (backing.updated) {
212
- res.set(asset, backing.balance)
213
- }
214
- }
215
- return res
216
- }
217
-
218
- /**
219
- * Whether the account exists on the ledger
220
- * @return {boolean|undefined}
221
- */
222
- get funded() {
223
- const backing = this.backing.get(this.axis.nativeAsset)
224
- return backing?.updated ? backing.authorized : undefined
225
- }
226
-
227
- /**
228
- * Get balance, allowance and commitments of the account in a token
229
- * @param {string} asset - Token contract id
230
- * @return {AccountAllowance}
231
- */
232
- getAllowance(asset) {
233
- const backing = this.backing.get(asset)
234
- const committed = this.committed(asset)
235
- if (!backing?.updated)
236
- return {asset, known: false, committed}
237
- return {
238
- asset,
239
- known: true,
240
- balance: backing.balance,
241
- allowance: backing.allowance,
242
- liveUntil: backing.liveUntil,
243
- authorized: backing.authorized,
244
- pending: backing.pending,
245
- available: backing.budget,
246
- committed
247
- }
248
- }
249
-
250
- /**
251
- * Sell tokens creating a limit remainder order if not executed in full
252
- * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
253
- * @return {Promise<TradeResult>}
254
- */
255
- async sell(params) {
256
- return this.trade(TradeDirection.Sell, params)
257
- }
258
-
259
- /**
260
- * Buy tokens creating a limit remainder order if not executed in full
261
- * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
262
- * @return {Promise<TradeResult>}
263
- */
264
- async buy(params) {
265
- return this.trade(TradeDirection.Buy, params)
266
- }
267
-
268
- /**
269
- * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it
270
- * @param {TradeParams} params - Same as `sell`
271
- * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
272
- */
273
- async estimateSell(params) {
274
- const {payload} = await this.prepareTrade(TradeDirection.Sell, params)
275
- const client = await this.client()
276
- return client.estimateSell(payload)
277
- }
278
-
279
- /**
280
- * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
281
- * @param {TradeParams} params - Same as `buy`
282
- * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
283
- */
284
- async estimateBuy(params) {
285
- const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
286
- const client = await this.client()
287
- return client.estimateBuy(payload)
288
- }
289
-
290
- /**
291
- * Change the amount, price or expiration of open orders (omitted fields keep their current values)
292
- * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
293
- * @return {Promise<bigint[]>} - Updated order ids
294
- */
295
- async update(updates) {
296
- await this.whenReady()
297
- const normalized = updates.map(update => {
298
- const current = this.getOrder(update.id)
299
- if (!current && (update.amount === undefined || update.price === undefined))
300
- throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
301
- return {
302
- current,
303
- update: {
304
- id: BigInt(update.id),
305
- amount: update.amount ?? current.amount,
306
- price: update.price ?? current.price,
307
- expires: update.expires ?? current?.expires ?? 0
308
- }
309
- }
310
- })
311
- //extra commitment per sold token
312
- const growth = new Map()
313
- for (const {current, update} of normalized) {
314
- if (!current)
315
- continue
316
- growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)
317
- }
318
- const approvals = []
319
- for (const [asset, delta] of growth) {
320
- if (delta <= 0n)
321
- continue
322
- const approve = await this.planApproval(asset, delta)
323
- if (approve) {
324
- this.emit('approve', {asset, ...approve})
325
- approvals.push({asset, ...approve})
326
- }
327
- }
328
- const client = await this.client()
329
- const res = []
330
- for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
331
- const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
332
- //approvals travel with the first batch, before its backing check
333
- const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})
334
- res.push(...ids)
335
- }
336
- return res
337
- }
338
-
339
- /**
340
- * Cancel open orders
341
- * @param {Array<bigint|string>} ids
342
- * @return {Promise<void>}
343
- */
344
- async cancel(ids) {
345
- const client = await this.client()
346
- const all = ids.map(id => BigInt(id))
347
- for (let i = 0; i < all.length; i += UPDATE_BATCH) {
348
- await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
349
- }
350
- for (const id of all) {
351
- this.local.delete(id.toString())
352
- }
353
- }
354
-
355
- /**
356
- * Cancel all open orders
357
- * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
358
- * @return {Promise<string[]>} - Canceled order ids
359
- */
360
- async cancelAll({market} = {}) {
361
- await this.whenReady()
362
- const ids = this.getOrders({market}).map(order => order.id)
363
- if (ids.length) {
364
- await this.cancel(ids)
365
- }
366
- return ids
367
- }
368
-
369
- /**
370
- * Fill an open order against the book while keeping profits from price inefficiencies
371
- * @param {bigint|string} takerOrderId - Order acting as the taker
372
- * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted
373
- * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
374
- */
375
- async crossfill(takerOrderId, orders) {
376
- if (!orders) {
377
- const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
378
- if (!taker)
379
- throw new Error(`Order ${takerOrderId} not found`)
380
- orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
381
- }
382
- const client = await this.client()
383
- const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
384
- return {sold, bought, surplus}
385
- }
386
-
387
- /**
388
- * Swap across one or several markets along the best route found by the AXIS API
389
- * @param {SwapParams} params
390
- * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
391
- */
392
- async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
393
- await this.whenReady()
394
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
395
- const quote = direction === TradeDirection.Buy ?
396
- await this.axis.api.quoteBuy(params) :
397
- await this.axis.api.quoteSell(params)
398
- const best = quote.paths?.[0]
399
- if (quote.status !== 'success' || !best?.path?.length)
400
- throw new Error(quote.error || 'No route available')
401
- const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))
402
- const tolerance = BigInt(Math.round(slippage * 10_000))
403
- let sellingAmount = BigInt(best.sold)
404
- let buyingAmount = BigInt(best.bought)
405
- if (direction === TradeDirection.Buy) {
406
- sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n
407
- } else {
408
- buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n
409
- }
410
- //`sellingAmount` is the exact spend of a sell and the most a buy may spend
411
- const approve = await this.planApproval(selling, sellingAmount)
412
- if (approve) {
413
- this.emit('approve', {asset: selling, ...approve})
414
- }
415
- const client = await this.client()
416
- const [sold, bought] = await client.swap({
417
- direction,
418
- trader: this.address,
419
- selling,
420
- sellingAmount,
421
- buyingAmount,
422
- path,
423
- approve
424
- })
425
- this.spent.set(selling, Date.now())
426
- return {sold, bought, approve}
427
- }
428
-
429
- /**
430
- * Compute approval for a call
431
- * @param {string} asset - Token contract id
432
- * @param {bigint} required - Max amount the call may spend
433
- * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}
434
- */
435
- async planApproval(asset, required) {
436
- await this.whenReady()
437
- const backing = this.backing.get(asset)
438
- let allowance
439
- if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {
440
- allowance = backing.allowance
441
- } else {
442
- const {tokenBalances} = this.axis
443
- if (!tokenBalances)
444
- throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
445
- await this.axis.getContractId() //the allowance spender
446
- allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
447
- }
448
- return planApproval({
449
- required,
450
- committed: this.committed(asset),
451
- allowance,
452
- liveUntil: backing?.liveUntil ?? 0,
453
- ledger: await this.axis.getLedger()
454
- })
455
- }
456
-
457
- /**
458
- * Check whether the pushed allowance of a token can be used as is
459
- * @param {string} asset - Token contract id
460
- * @return {boolean}
461
- * @private
462
- */
463
- isAllowanceCurrent(asset) {
464
- const backing = this.backing.get(asset)
465
- if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
466
- return false
467
- const spent = this.spent.get(asset)
468
- if (spent === undefined)
469
- return true
470
- if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives
471
- return false //TODO: try to read allowance change from tx result meta changes
472
- this.spent.delete(asset)
473
- return true
474
- }
475
-
476
- /**
477
- * @param {number} direction
478
- * @param {TradeParams} params
479
- * @return {Promise<TradeResult>}
480
- * @private
481
- */
482
- async trade(direction, params) {
483
- const {payload, planned} = await this.prepareTrade(direction, params)
484
- const {selling, buying, amount, price, expires, approve} = payload
485
- if (planned && approve) {
486
- this.emit('approve', {asset: selling, ...approve})
487
- }
488
- const client = await this.client()
489
- const [sold, bought, createdId] = direction === TradeDirection.Buy ?
490
- await client.buy(payload) :
491
- await client.sell(payload)
492
- this.spent.set(selling, Date.now())
493
- let order
494
- if (createdId) {
495
- order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})
496
- }
497
- return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}
498
- }
499
-
500
- /**
501
- * Resolve the crossing orders, the price of a market order and the approval of a trade
502
- * @param {number} direction
503
- * @param {TradeParams} params
504
- * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,
505
- * `planned` if the approval was planned by the account rather than supplied
506
- * @private
507
- */
508
- async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {
509
- await this.whenReady()
510
- amount = BigInt(amount)
511
- const market = price === undefined || price === null
512
- if (kind === undefined) {
513
- kind = market ? OrderKind.Fill : OrderKind.Limit
514
- }
515
- let crossing
516
- if (!orders || market) {
517
- //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the
518
- //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well
519
- const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))
520
- crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)
521
- }
522
- if (market) {
523
- //cross everything the quote found: the limit is the worst maker price (makers price `selling` per
524
- //`buying` of a buyer; seen from a seller, invert it)
525
- if (!crossing.worstPrice)
526
- throw new Error('Not enough liquidity for a market order')
527
- price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)
528
- }
529
- price = BigInt(price)
530
- const planned = approve === undefined
531
- if (planned) {
532
- const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount
533
- approve = await this.planApproval(selling, required)
534
- }
535
- const payload = {
536
- kind,
537
- trader: this.address,
538
- amount,
539
- selling,
540
- buying,
541
- price,
542
- orders: (orders ?? crossing.orders).map(id => BigInt(id)),
543
- expires,
544
- approve: approve || undefined
545
- }
546
- return {payload, planned}
547
- }
548
-
549
- /**
550
- * Count an order this client created as committed until the indexer reports it
551
- * @param {bigint} id
552
- * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read
553
- * @return {Promise<AccountOrder|undefined>}
554
- * @private
555
- */
556
- async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {
557
- const key = id.toString()
558
- if (this.orders.has(key))
559
- return this.orders.get(key) //already reported
560
- let stored
561
- try {
562
- const client = await this.client()
563
- stored = await client.order(id)
564
- } catch (e) {
565
- //estimate below
566
- }
567
- if (this.orders.has(key))
568
- return this.orders.get(key)
569
- let orderAmount
570
- let orderPrice
571
- if (stored) {
572
- orderAmount = stored.amount
573
- orderPrice = stored.price
574
- } else if (direction === TradeDirection.Sell) {
575
- orderAmount = amount - sold
576
- orderPrice = price
577
- } else {
578
- //the remainder of a buy sells `selling` for the rest of `buying` at the limit
579
- orderAmount = maxQuoteSpend(amount - bought, price)
580
- orderPrice = invertPrice(price)
581
- }
582
- const now = Date.now()
583
- /** @type {AccountOrder} */
584
- const order = {
585
- id: key,
586
- owner: this.address,
587
- selling,
588
- buying,
589
- market: pairKey(selling, buying),
590
- status: 'ACTIVE',
591
- price: orderPrice,
592
- amount: orderAmount,
593
- quote: orderAmount,
594
- expires: Number(stored?.expires ?? expires ?? 0),
595
- created: now,
596
- updated: now,
597
- cursor: undefined,
598
- backed: null,
599
- backedPct: null,
600
- backingPending: true,
601
- filledPct: 0,
602
- pending: true
603
- }
604
- this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})
605
- this.emit('pending', order)
606
- this.emit('change')
607
- return order
608
- }
609
-
610
- /**
611
- * Crossing orders of a direct-market trade and the worst price among them
612
- * @param {number} direction
613
- * @param {string} selling
614
- * @param {string} buying
615
- * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy
616
- * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order
617
- * @return {Promise<{orders: string[], worstPrice: bigint|null}>}
618
- * @private
619
- */
620
- async findQuote(direction, selling, buying, amount, maxPrice) {
621
- const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}
622
- try {
623
- const quote = direction === TradeDirection.Buy ?
624
- await this.axis.api.quoteBuy(params) :
625
- await this.axis.api.quoteSell(params)
626
- const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null
627
- if (hop)
628
- return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}
629
- } catch (e) {
630
- //nothing to cross: a limit order simply rests
631
- }
632
- return {orders: [], worstPrice: null}
633
- }
634
-
635
- /**
636
- * @return {Promise<AxisContractClient>}
637
- * @private
638
- */
639
- async client() {
640
- if (!this.signTransaction)
641
- throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
642
- return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
643
- }
644
-
645
- /**
646
- * @param {number} [timeout]
647
- * @return {Promise<void>}
648
- * @private
649
- */
650
- async whenReady(timeout = READY_TIMEOUT) {
651
- if (this.loaded)
652
- return
653
- let timer
654
- try {
655
- await Promise.race([
656
- this.ready,
657
- new Promise((resolve, reject) => {
658
- timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)
659
- })
660
- ])
661
- } finally {
662
- clearTimeout(timer)
663
- }
664
- }
665
-
666
- /**
667
- * @param {StreamMessage} message
668
- * @private
669
- */
670
- handle(message) {
671
- switch (message.type) {
672
- case 'account':
673
- this.live = true
674
- return this.applySnapshot(message)
675
- case 'order':
676
- return this.applyOrder(message)
677
- case 'backing':
678
- return this.applyBacking(message)
679
- case 'trade':
680
- return this.emit('trade', message.trade)
681
- case 'swap':
682
- return this.emit('swap', message.swap)
683
- case 'error':
684
- return this.emit('error', new Error(message.error))
685
- }
686
- }
687
-
688
- /**
689
- * Replace the state with a snapshot
690
- * @param {ApiAccount} state
691
- * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot
692
- * @private
693
- */
694
- applySnapshot(state, mergeBacking = false) {
695
- const previous = this.orders
696
- const next = new Map()
697
- for (const raw of state.orders || []) {
698
- const order = parseApiOrder(raw)
699
- next.set(order.id, order)
700
- this.local.delete(order.id)
701
- }
702
- this.orders = next
703
- const backing = mergeBacking ? new Map(this.backing) : new Map()
704
- for (const [asset, raw] of Object.entries(state.backing || {})) {
705
- backing.set(asset, parseBacking(asset, raw))
706
- }
707
- this.backing = backing
708
- if (this.loaded) {
709
- for (const [id, order] of previous) {
710
- if (!next.has(id)) {
711
- this.emit('remove', order)
712
- }
713
- }
714
- for (const [id, order] of next) {
715
- if (!previous.has(id)) {
716
- this.emit('new', order)
717
- }
718
- }
719
- }
720
- if (!this.loaded) {
721
- this.loaded = true
722
- this.resolveReady()
723
- this.emit('ready')
724
- }
725
- this.emit('change')
726
- }
727
-
728
- /**
729
- * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message
730
- * @private
731
- */
732
- applyOrder({action, order: raw, fill: rawFill}) {
733
- const order = parseApiOrder(raw)
734
- this.local.delete(order.id)
735
- const previous = this.orders.get(order.id)
736
- const removed = action === 'filled' || action === 'cancel' || action === 'expire'
737
- if (removed) {
738
- this.orders.delete(order.id)
739
- } else {
740
- if (previous && order.backed === null) {
741
- //the event serialization may lack the split; keep the last known one until the backing update
742
- order.backed = previous.backed
743
- order.backedPct = previous.backedPct
744
- order.backingPending = previous.backingPending
745
- }
746
- this.orders.set(order.id, order)
747
- }
748
- const fill = rawFill && {
749
- order,
750
- sold: BigInt(rawFill.sold),
751
- bought: BigInt(rawFill.bought),
752
- taker: rawFill.taker,
753
- trade: rawFill.trade?.toString(),
754
- ts: Number(rawFill.ts) * 1000,
755
- partial: action === 'fill'
756
- }
757
- this.emit(action, fill || order)
758
- if (removed) {
759
- this.emit('remove', order)
760
- }
761
- this.emit('order', {action, order, fill})
762
- this.emit('change')
763
- }
764
-
765
- /**
766
- * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message
767
- * @private
768
- */
769
- applyBacking({asset, backing: raw, backed}) {
770
- const backing = raw ? parseBacking(asset, raw) : undefined
771
- if (backing) {
772
- this.backing.set(asset, backing)
773
- } else {
774
- this.backing.delete(asset)
775
- }
776
- for (const [id, amount] of Object.entries(backed || {})) {
777
- const order = this.orders.get(id)
778
- if (!order)
779
- continue
780
- order.backed = BigInt(amount)
781
- order.backedPct = share(order.backed, order.amount)
782
- order.backingPending = !backing || backing.pending || !backing.updated
783
- }
784
- this.emit('backing', {asset, backing})
785
- this.emit('change')
786
- }
787
-
788
- /**
789
- * @return {Iterable<AccountOrder>}
790
- * @private
791
- */
792
- * allOrders() {
793
- yield* this.orders.values()
794
- yield* this.localOrders()
795
- }
796
-
797
- /**
798
- * Get local orders that haven't expired
799
- * @return {AccountOrder[]}
800
- * @private
801
- */
802
- localOrders() {
803
- const now = Date.now()
804
- const res = []
805
- for (const [id, {order, expires}] of this.local) {
806
- if (expires < now || this.orders.has(id)) {
807
- this.local.delete(id)
808
- } else {
809
- res.push(order)
810
- }
811
- }
812
- return res
813
- }
814
-
815
- /**
816
- * @private
817
- */
818
- startFallback() {
819
- if (this.fallbackTimer)
820
- return
821
- this.fallbackTimer = setInterval(() => {
822
- this.refresh().catch(() => {
823
- //retried on the next tick
824
- })
825
- }, this.axis.fallbackPollInterval)
826
- }
827
-
828
- /**
829
- * @private
830
- */
831
- stopFallback() {
832
- clearInterval(this.fallbackTimer)
833
- this.fallbackTimer = undefined
834
- }
835
- }
836
-
837
- /**
838
- * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)
839
- * @param {ApiOrder} raw
840
- * @return {AccountOrder}
841
- */
842
- export function parseApiOrder(raw) {
843
- const amount = BigInt(raw.amount)
844
- const quote = BigInt(raw.quote ?? raw.amount)
845
- //unconfirmed until loaded, and while a reload confirming the latest event is due
846
- const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending
847
- const backed = raw.backed !== undefined ? BigInt(raw.backed) : null
848
- return {
849
- id: raw.id,
850
- owner: raw.owner,
851
- selling: raw.selling,
852
- buying: raw.buying,
853
- market: pairKey(raw.selling, raw.buying),
854
- status: raw.status,
855
- price: BigInt(raw.price),
856
- amount,
857
- quote,
858
- expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,
859
- created: parseApiDate(raw.created),
860
- updated: parseApiDate(raw.updated),
861
- cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,
862
- backed,
863
- backedPct: backed === null ? null : share(backed, amount),
864
- backingPending: !confirmed,
865
- filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,
866
- pending: false
867
- }
868
- }
869
-
870
- /**
871
- * @param {string} asset
872
- * @param {ApiBacking} raw
873
- * @return {AccountBacking}
874
- */
875
- function parseBacking(asset, raw) {
876
- return {
877
- asset,
878
- balance: BigInt(raw.balance),
879
- allowance: BigInt(raw.allowance),
880
- liveUntil: raw.liveUntil || 0,
881
- authorized: raw.authorized !== false,
882
- budget: BigInt(raw.budget ?? 0),
883
- updated: parseApiDate(raw.updated),
884
- skipped: parseApiDate(raw.skipped),
885
- pending: raw.pending === true
886
- }
887
- }
888
-
889
- /**
890
- * @param {bigint} part
891
- * @param {bigint} total
892
- * @return {number} - 0..1
893
- */
894
- function share(part, total) {
895
- if (total <= 0n)
896
- return 1
897
- return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
898
- }
899
-
900
- /**
901
- * @param {string|{base: string, quote: string}|string[]|undefined} market
902
- * @return {string|undefined}
903
- */
904
- function toMarketKey(market) {
905
- if (!market)
906
- return undefined
907
- if (typeof market === 'string') {
908
- const [x, y] = market.split('/')
909
- return pairKey(x, y)
910
- }
911
- if (Array.isArray(market))
912
- return pairKey(market[0], market[1])
913
- return pairKey(market.base, market.quote)
914
- }
915
-
916
- /**
917
- * Newest first: unconfirmed local orders, then by creation position
918
- * @param {AccountOrder} x
919
- * @param {AccountOrder} y
920
- * @return {number}
921
- */
922
- function newestFirst(x, y) {
923
- if (x.cursor === undefined || y.cursor === undefined)
924
- return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created
925
- return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0
926
- }
927
-
928
- /**
929
- * @typedef {{}} AccountOrder - Open order of a tracked account
930
- * @property {string} id - Order id (decimal u128)
931
- * @property {string} owner - Maker address
932
- * @property {string} selling - Sold token
933
- * @property {string} buying - Bought token
934
- * @property {string} market - Market key
935
- * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status
936
- * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)
937
- * @property {bigint} amount - Amount of `selling` left
938
- * @property {bigint} quote - Amount of `selling` at creation
939
- * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none
940
- * @property {number} created - Creation time, UNIX milliseconds
941
- * @property {number} updated - Last change, UNIX milliseconds
942
- * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)
943
- * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order
944
- * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown
945
- * @property {boolean} backingPending - The backing is not confirmed yet
946
- * @property {number} filledPct - Filled share of the initial amount (0..1)
947
- * @property {boolean} pending - Created by this client, not reported by the indexer yet
948
- */
949
-
950
- /**
951
- * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer
952
- * @property {string} asset
953
- * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)
954
- * @property {bigint} allowance - Allowance granted to the AXIS contract
955
- * @property {number} liveUntil - Ledger sequence the allowance lives until
956
- * @property {boolean} authorized - Whether the account can send and receive the token
957
- * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired
958
- * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)
959
- * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)
960
- * @property {boolean} pending - A reload confirming the latest change is due
961
- */
962
-
963
- /**
964
- * @typedef {{}} AccountAllowance
965
- * @property {string} asset
966
- * @property {boolean} known - Whether the backing is tracked and loaded
967
- * @property {bigint} [balance]
968
- * @property {bigint} [allowance]
969
- * @property {number} [liveUntil]
970
- * @property {boolean} [authorized]
971
- * @property {boolean} [pending]
972
- * @property {bigint} [available] - min(balance, allowance)
973
- * @property {bigint} committed - Remaining amount of the open orders selling the token
974
- */
975
-
976
- /**
977
- * @typedef {{}} AccountFill
978
- * @property {AccountOrder} order - Order after the fill
979
- * @property {bigint} sold - Amount of `selling` delivered
980
- * @property {bigint} bought - Amount of `buying` received
981
- * @property {string} taker - Taker address
982
- * @property {string} trade - Trade id
983
- * @property {number} ts - Trade time, UNIX milliseconds
984
- * @property {boolean} partial - Whether the order is still open
985
- */
986
-
987
- /**
988
- * @typedef {{}} TradeParams
989
- * @property {string} selling - Token sent
990
- * @property {string} buying - Token received
991
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
992
- * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order
993
- * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order
994
- * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder
995
- * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted
996
- * @property {Approval|null} [approve] - Explicit approval (`null` for none)
997
- */
998
-
999
- /**
1000
- * @typedef {{}} TradeResult
1001
- * @property {bigint} sold - Amount of `selling` sent
1002
- * @property {bigint} bought - Amount of `buying` received
1003
- * @property {string} [orderId] - ID of the order created for a limit remainder
1004
- * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)
1005
- * @property {Approval} [approve] - Approval granted with the trade
1006
- */
1007
-
1008
- /**
1009
- * @typedef {{}} SwapParams
1010
- * @property {string} selling - Token sent
1011
- * @property {string} buying - Token received
1012
- * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1013
- * @property {number} [direction] - {@link TradeDirection}, `Sell` by default
1014
- * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default
1015
- */
1
+ import {Emitter} from './emitter.js'
2
+ import {pairKey, invertPrice} from './asset-pair.js'
3
+ import {parseApiDate} from './api-dates.js'
4
+ import {planApproval, planReduction, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'
5
+ import {OrderKind, TradeDirection} from './constants.js'
6
+
7
+ /** Orders per `update` transaction */
8
+ const UPDATE_BATCH = 90
9
+ /** Orders an approval takes the place of in an `update` batch: the token `approve` event is about twice the size of the
10
+ * `mod` event of a removal, within the 16 KB of events a transaction may emit */
11
+ const APPROVAL_BATCH_WEIGHT = 2
12
+ /** Time to wait for the account state before trading, in milliseconds */
13
+ const READY_TIMEOUT = 15_000
14
+ /** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */
15
+ const LOCAL_ORDER_TTL = 120_000
16
+ /** How long an allowance set by this client overrides pushed records still showing the allowance it replaced, in
17
+ * milliseconds: the indexer may reload an allowance only with its periodic sweep */
18
+ const APPROVAL_CONFIRM_TIMEOUT = 360_000
19
+
20
+ /**
21
+ * Trader wrapper that tracks every open order of an account across all markets and the account backing.
22
+ * Create it with {@link import('./axis.js').Axis#account}.
23
+ *
24
+ * Emits:
25
+ * - `ready` - the account state was loaded
26
+ * - `new` {@link AccountOrder} - an order was created (confirmed by the indexer)
27
+ * - `pending` {@link AccountOrder} - an order created by this client, not reported by the indexer yet
28
+ * - `fill` {@link AccountFill} - an order was partially filled
29
+ * - `filled` {@link AccountFill} - an order was filled in full
30
+ * - `update` {@link AccountOrder} - an order changed (amount, price, expiration, revived)
31
+ * - `cancel` {@link AccountOrder} - an order was removed by the owner
32
+ * - `expire` {@link AccountOrder} - an order expired
33
+ * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
34
+ * - `order` `{action, order, fill?}` - any order change
35
+ * - `backing` `{asset, backing}` - the balance, allowance or the backing split of the orders selling a token changed
36
+ * - `approve` `{asset, amount, liveUntil}` - a call is about to set an allowance (grant, renew, lower or revoke it)
37
+ * - `trade` {ApiTrade} - the account performed a trade
38
+ * - `swap` {ApiSwap} - the account performed a swap
39
+ * - `change` - the open orders or the backing changed
40
+ * - `error` `Error` - the push API rejected the account subscription
41
+ */
42
+ export class AxisAccount extends Emitter {
43
+ /**
44
+ * @param {Axis} axis
45
+ * @param {string} address - Trader address
46
+ * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options]
47
+ */
48
+ constructor(axis, address, {signTransaction, approvalTtl} = {}) {
49
+ super()
50
+ this.axis = axis
51
+ this.address = address
52
+ this.signTransaction = signTransaction
53
+ this.approvalTtl = approvalTtl || APPROVAL_TTL_LEDGERS
54
+ this.ready = new Promise(resolve => this.resolveReady = resolve)
55
+ }
56
+
57
+ /**
58
+ * Trader address
59
+ * @type {string}
60
+ * @readonly
61
+ */
62
+ address
63
+ /**
64
+ * Wallet signing callback, required to trade
65
+ * @type {SignTransactionCallback|undefined}
66
+ */
67
+ signTransaction
68
+ /**
69
+ * Lifetime of the allowances granted by trading calls, in ledgers
70
+ * @type {number}
71
+ */
72
+ approvalTtl
73
+ /**
74
+ * Open orders by id
75
+ * @type {Map<string, AccountOrder>}
76
+ * @readonly
77
+ */
78
+ orders = new Map()
79
+ /**
80
+ * Account backing by token contract id
81
+ * @type {Map<string, AccountBacking>}
82
+ * @readonly
83
+ */
84
+ backing = new Map()
85
+ /**
86
+ * Resolves once the account state has been loaded
87
+ * @type {Promise<void>}
88
+ * @readonly
89
+ */
90
+ ready
91
+ /**
92
+ * Whether the account state has been loaded
93
+ * @type {boolean}
94
+ */
95
+ loaded = false
96
+ /**
97
+ * Orders created by this client that the indexer has not reported yet
98
+ * @type {Map<string, {order: AccountOrder, expires: number}>}
99
+ * @private
100
+ */
101
+ local = new Map()
102
+ /**
103
+ * Whether the backing in memory get updated from the push API
104
+ * @type {boolean}
105
+ * @private
106
+ */
107
+ live = false
108
+ /**
109
+ * Last taker spend of this client by token, UNIX milliseconds
110
+ * @type {Map<string, number>}
111
+ * @private
112
+ */
113
+ spent = new Map() //TODO: drop this
114
+ /**
115
+ * Calls submitting transactions, run one at a time
116
+ * @type {Promise<void>}
117
+ * @private
118
+ */
119
+ queue = Promise.resolve()
120
+ /**
121
+ * Orders removed by this client that the indexer has not reported yet: expiration by order id, UNIX milliseconds
122
+ * @type {Map<string, number>}
123
+ * @private
124
+ */
125
+ removed = new Map()
126
+ /**
127
+ * Allowances set by this client that the pushed state may not reflect yet, by token contract id
128
+ * @type {Map<string, {amount: bigint, liveUntil: number, replaced?: {allowance: bigint, liveUntil: number}, until: number}>}
129
+ * @private
130
+ */
131
+ approved = new Map()
132
+ /**
133
+ * @type {function(): void}
134
+ * @private
135
+ */
136
+ resolveReady
137
+
138
+ /**
139
+ * Start tracking this account
140
+ * @internal
141
+ */
142
+ start() {
143
+ const {stream} = this.axis
144
+ this.unsubscribe = stream.subscribe('account', {address: this.address}, message => this.handle(message))
145
+ this.offOpen = stream.on('open', () => this.stopFallback())
146
+ this.offClose = stream.on('close', () => {
147
+ this.live = false //changes are missed until the next snapshot
148
+ this.startFallback()
149
+ })
150
+ //load over REST if the push API does not deliver the snapshot soon
151
+ this.initTimer = setTimeout(() => {
152
+ if (!this.loaded) {
153
+ this.refresh().catch(() => this.startFallback())
154
+ }
155
+ }, 3_000)
156
+ }
157
+
158
+ /**
159
+ * Stop tracking this account
160
+ */
161
+ close() {
162
+ clearTimeout(this.initTimer)
163
+ this.stopFallback()
164
+ this.unsubscribe?.()
165
+ this.offOpen?.()
166
+ this.offClose?.()
167
+ this.axis.releaseAccount(this)
168
+ }
169
+
170
+ /**
171
+ * Reload current account state from the REST API
172
+ * @return {Promise<void>}
173
+ */
174
+ async refresh() {
175
+ //the REST state lists only the tokens of the orders once nobody subscribes: keep the other balances
176
+ this.applySnapshot(await this.axis.api.getAccount(this.address), true)
177
+ }
178
+
179
+ /**
180
+ * Retrieve open orders, newest first
181
+ * @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
182
+ * @return {AccountOrder[]}
183
+ */
184
+ getOrders({market, selling, buying} = {}) { //TODO: simplify market argument
185
+ const key = toMarketKey(market)
186
+ const res = []
187
+ for (const order of this.allOrders()) {
188
+ if (key && order.market !== key)
189
+ continue
190
+ if (selling && order.selling !== selling)
191
+ continue
192
+ if (buying && order.buying !== buying)
193
+ continue
194
+ res.push(order)
195
+ }
196
+ return res.sort(newestFirst)
197
+ }
198
+
199
+ /**
200
+ * Get open order by id
201
+ * @param {bigint|string} id
202
+ * @return {AccountOrder|undefined}
203
+ */
204
+ getOrder(id) {
205
+ const key = id.toString()
206
+ if (this.isRemoved(key))
207
+ return undefined
208
+ return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)
209
+ }
210
+
211
+ /**
212
+ * Calculate the remaining amount of the open orders selling the token across every market (what the allowance must cover)
213
+ * @param {string} asset - Token contract id
214
+ * @return {bigint}
215
+ */
216
+ committed(asset) {
217
+ let sum = 0n
218
+ for (const order of this.allOrders()) {
219
+ if (order.selling === asset) {
220
+ sum += order.amount
221
+ }
222
+ }
223
+ return sum
224
+ }
225
+
226
+ /**
227
+ * Get spendable balance of the account in a token
228
+ * @param {string} asset - Token contract id
229
+ * @return {bigint|undefined} - Undefined if not tracked
230
+ */
231
+ getBalance(asset) {
232
+ const backing = this.backing.get(asset)
233
+ return backing?.updated ? backing.balance : undefined
234
+ }
235
+
236
+ /**
237
+ * Get spendable balances in every tracked token by token contract id
238
+ * @return {Map<string, bigint>}
239
+ */
240
+ get balances() {
241
+ const res = new Map()
242
+ for (const [asset, backing] of this.backing) {
243
+ if (backing.updated) {
244
+ res.set(asset, backing.balance)
245
+ }
246
+ }
247
+ return res
248
+ }
249
+
250
+ /**
251
+ * Whether the account exists on the ledger
252
+ * @return {boolean|undefined}
253
+ */
254
+ get funded() {
255
+ const backing = this.backing.get(this.axis.nativeAsset)
256
+ return backing?.updated ? backing.authorized : undefined
257
+ }
258
+
259
+ /**
260
+ * Get balance, allowance and commitments of the account in a token
261
+ * @param {string} asset - Token contract id
262
+ * @return {AccountAllowance}
263
+ */
264
+ getAllowance(asset) {
265
+ const backing = this.backing.get(asset)
266
+ const committed = this.committed(asset)
267
+ if (!backing?.updated)
268
+ return {asset, known: false, committed}
269
+ return {
270
+ asset,
271
+ known: true,
272
+ balance: backing.balance,
273
+ allowance: backing.allowance,
274
+ liveUntil: backing.liveUntil,
275
+ authorized: backing.authorized,
276
+ pending: backing.pending,
277
+ available: backing.budget,
278
+ committed
279
+ }
280
+ }
281
+
282
+ /**
283
+ * Sell tokens creating a limit remainder order if not executed in full
284
+ * @param {TradeParams} params - `amount` of `selling` to sell; `price` is the minimum `buying` per 1 `selling`
285
+ * @return {Promise<TradeResult>}
286
+ */
287
+ async sell(params) {
288
+ return this.serialize(() => this.trade(TradeDirection.Sell, params))
289
+ }
290
+
291
+ /**
292
+ * Buy tokens creating a limit remainder order if not executed in full
293
+ * @param {TradeParams} params - `amount` of `buying` to acquire; `price` is the maximum `selling` per 1 `buying`
294
+ * @return {Promise<TradeResult>}
295
+ */
296
+ async buy(params) {
297
+ return this.serialize(() => this.trade(TradeDirection.Buy, params))
298
+ }
299
+
300
+ /**
301
+ * Simulate a sell with the same crossing and approval as `sell`, without signing or submitting it
302
+ * @param {TradeParams} params - Same as `sell`
303
+ * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
304
+ */
305
+ async estimateSell(params) {
306
+ const {payload} = await this.prepareTrade(TradeDirection.Sell, params)
307
+ const client = await this.client()
308
+ return client.estimateSell(payload)
309
+ }
310
+
311
+ /**
312
+ * Simulate a buy with the same crossing and approval as `buy`, without signing or submitting it
313
+ * @param {TradeParams} params - Same as `buy`
314
+ * @return {Promise<import('./index.js').TradeEstimate>} - Network fee and expected result
315
+ */
316
+ async estimateBuy(params) {
317
+ const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
318
+ const client = await this.client()
319
+ return client.estimateBuy(payload)
320
+ }
321
+
322
+ /**
323
+ * Change the amount, price or expiration of open orders (omitted fields keep their current values). The allowance of
324
+ * every sold token follows what its open orders need: raised when they grow, or when it does not back the changed
325
+ * orders, lowered when they shrink
326
+ * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
327
+ * @return {Promise<bigint[]>} - Updated order ids
328
+ */
329
+ async update(updates) {
330
+ return this.serialize(async () => {
331
+ await this.whenReady()
332
+ const changes = updates.map(update => {
333
+ const current = this.getOrder(update.id)
334
+ if (!current && (update.amount === undefined || update.price === undefined))
335
+ throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
336
+ return {
337
+ current,
338
+ update: {
339
+ id: BigInt(update.id),
340
+ amount: update.amount ?? current.amount,
341
+ price: update.price ?? current.price,
342
+ expires: update.expires ?? current?.expires ?? 0
343
+ }
344
+ }
345
+ })
346
+ return this.submitUpdates(changes, {grow: true})
347
+ })
348
+ }
349
+
350
+ /**
351
+ * Cancel open orders, lowering the allowance of every sold token to what its remaining open orders need
352
+ * @param {Array<bigint|string>} ids
353
+ * @return {Promise<void>}
354
+ */
355
+ async cancel(ids) {
356
+ await this.serialize(() => this.removeOrders(ids))
357
+ }
358
+
359
+ /**
360
+ * Cancel all open orders, lowering the allowances like `cancel`
361
+ * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
362
+ * @return {Promise<string[]>} - Canceled order ids
363
+ */
364
+ async cancelAll({market} = {}) {
365
+ return this.serialize(async () => {
366
+ await this.whenReady()
367
+ const ids = this.getOrders({market}).map(order => order.id)
368
+ if (ids.length) {
369
+ await this.removeOrders(ids)
370
+ }
371
+ return ids
372
+ })
373
+ }
374
+
375
+ /**
376
+ * Set the allowances granted to the AXIS contract on tokens to zero, optionally canceling the open orders selling them
377
+ * in the same transactions. The revocation goes with the first transaction. Works while the contract is frozen
378
+ * @param {string[]} assets - Token contract ids
379
+ * @param {{cancelOrders?: boolean}} [options] - Also cancel every open order selling these tokens
380
+ * @return {Promise<AccountRevokeResult>}
381
+ * @throws {Error} - The submission error, with the `revoked` tokens and the `canceled` order ids done before it
382
+ */
383
+ async revoke(assets, {cancelOrders = false} = {}) {
384
+ return this.serialize(async () => {
385
+ const tokens = [...new Set(assets)]
386
+ let ids = []
387
+ if (cancelOrders) {
388
+ await this.whenReady()
389
+ ids = [...this.allOrders()].filter(order => tokens.includes(order.selling)).map(order => order.id)
390
+ }
391
+ try {
392
+ const canceled = await this.removeOrders(ids, tokens)
393
+ return {revoked: tokens, canceled: canceled.map(id => id.toString())}
394
+ } catch (e) {
395
+ if (e instanceof Error) {
396
+ e.revoked = e.progress?.batches > 0 ? tokens : []
397
+ e.canceled = (e.progress?.updated ?? []).map(id => id.toString())
398
+ }
399
+ throw e
400
+ }
401
+ })
402
+ }
403
+
404
+ /**
405
+ * Fill an open order against the book while keeping profits from price inefficiencies
406
+ * @param {bigint|string} takerOrderId - Order acting as the taker
407
+ * @param {Array<bigint|string>} [orders] - Counter orders, looked up automatically when omitted
408
+ * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
409
+ */
410
+ async crossfill(takerOrderId, orders) {
411
+ return this.serialize(async () => {
412
+ if (!orders) {
413
+ const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
414
+ if (!taker)
415
+ throw new Error(`Order ${takerOrderId} not found`)
416
+ orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
417
+ }
418
+ const client = await this.client()
419
+ const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
420
+ return {sold, bought, surplus}
421
+ })
422
+ }
423
+
424
+ /**
425
+ * Swap across one or several markets along the best route found by the AXIS API
426
+ * @param {SwapParams} params
427
+ * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
428
+ */
429
+ async swap(params) {
430
+ return this.serialize(() => this.trySwap(params))
431
+ }
432
+
433
+ /**
434
+ * @param {SwapParams} params
435
+ * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
436
+ * @private
437
+ */
438
+ async trySwap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
439
+ await this.whenReady()
440
+ const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
441
+ const quote = direction === TradeDirection.Buy ?
442
+ await this.axis.api.quoteBuy(params) :
443
+ await this.axis.api.quoteSell(params)
444
+ const best = quote.paths?.[0]
445
+ if (quote.status !== 'success' || !best?.path?.length)
446
+ throw new Error(quote.error || 'No route available')
447
+ const path = best.path.map(hop => ({asset: hop.buying, orders: hop.orders.filter(Boolean).map(id => BigInt(id))}))
448
+ const tolerance = BigInt(Math.round(slippage * 10_000))
449
+ let sellingAmount = BigInt(best.sold)
450
+ let buyingAmount = BigInt(best.bought)
451
+ if (direction === TradeDirection.Buy) {
452
+ sellingAmount = (sellingAmount * (10_000n + tolerance) + 9_999n) / 10_000n
453
+ } else {
454
+ buyingAmount = buyingAmount * (10_000n - tolerance) / 10_000n
455
+ }
456
+ //`sellingAmount` is the exact spend of a sell and the most a buy may spend
457
+ const approve = await this.planApproval(selling, sellingAmount)
458
+ if (approve) {
459
+ this.emit('approve', {asset: selling, ...approve})
460
+ }
461
+ const client = await this.client()
462
+ const [sold, bought] = await client.swap({
463
+ direction,
464
+ trader: this.address,
465
+ selling,
466
+ sellingAmount,
467
+ buyingAmount,
468
+ path,
469
+ approve
470
+ })
471
+ this.spent.set(selling, Date.now())
472
+ return {sold, bought, approve}
473
+ }
474
+
475
+ /**
476
+ * Compute approval for a call
477
+ * @param {string} asset - Token contract id
478
+ * @param {bigint} required - Max amount the call may spend
479
+ * @return {Promise<{amount: bigint, liveUntil: number}|undefined>}
480
+ */
481
+ async planApproval(asset, required) {
482
+ await this.whenReady()
483
+ const allowance = await this.readAllowance(asset) ?? 0n //unknown: a redundant approval, never a shortfall
484
+ return planApproval({
485
+ required,
486
+ committed: this.committed(asset),
487
+ allowance,
488
+ liveUntil: this.backing.get(asset)?.liveUntil ?? 0,
489
+ ledger: await this.axis.getLedger(),
490
+ ttl: this.approvalTtl
491
+ })
492
+ }
493
+
494
+ /**
495
+ * Current allowance of a token: the pushed value while it can be trusted, otherwise read over RPC
496
+ * @param {string} asset - Token contract id
497
+ * @return {Promise<bigint|undefined>} - Undefined when the RPC read fails
498
+ * @throws {Error} - If the token is not tracked and there is no RPC to read it from
499
+ * @private
500
+ */
501
+ async readAllowance(asset) {
502
+ const backing = this.backing.get(asset)
503
+ if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances))
504
+ return backing.allowance
505
+ const {tokenBalances} = this.axis
506
+ if (!tokenBalances)
507
+ throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
508
+ await this.axis.getContractId() //the allowance spender
509
+ return tokenBalances.getAllowance(asset, this.address).catch(() => undefined)
510
+ }
511
+
512
+ /**
513
+ * Check whether the pushed allowance of a token can be used as is
514
+ * @param {string} asset - Token contract id
515
+ * @return {boolean}
516
+ * @private
517
+ */
518
+ isAllowanceCurrent(asset) {
519
+ const backing = this.backing.get(asset)
520
+ if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
521
+ return false
522
+ if (this.pendingApproval(asset))
523
+ return false //set by this client, not confirmed by the push yet
524
+ const spent = this.spent.get(asset)
525
+ if (spent === undefined)
526
+ return true
527
+ if (Date.now() - spent < 30_000) //the spend lowers the allowance before the push reporting it arrives
528
+ return false //TODO: try to read allowance change from tx result meta changes
529
+ this.spent.delete(asset)
530
+ return true
531
+ }
532
+
533
+ /**
534
+ * @param {number} direction
535
+ * @param {TradeParams} params
536
+ * @return {Promise<TradeResult>}
537
+ * @private
538
+ */
539
+ async trade(direction, params) {
540
+ const {payload, planned} = await this.prepareTrade(direction, params)
541
+ const {selling, buying, amount, price, expires, approve} = payload
542
+ if (planned && approve) {
543
+ this.emit('approve', {asset: selling, ...approve})
544
+ }
545
+ const client = await this.client()
546
+ const [sold, bought, createdId] = direction === TradeDirection.Buy ?
547
+ await client.buy(payload) :
548
+ await client.sell(payload)
549
+ this.spent.set(selling, Date.now())
550
+ let order
551
+ if (createdId) {
552
+ order = await this.trackCreated(createdId, {direction, selling, buying, amount, price, sold, bought, expires})
553
+ }
554
+ return {sold, bought, orderId: createdId ? createdId.toString() : undefined, order, approve}
555
+ }
556
+
557
+ /**
558
+ * Resolve the crossing orders, the price of a market order and the approval of a trade
559
+ * @param {number} direction
560
+ * @param {TradeParams} params
561
+ * @return {Promise<{payload: import('./index.js').TradeArguments, planned: boolean}>} - Contract call arguments,
562
+ * `planned` if the approval was planned by the account rather than supplied
563
+ * @private
564
+ */
565
+ async prepareTrade(direction, {selling, buying, amount, price, kind, expires, orders, approve}) {
566
+ await this.whenReady()
567
+ amount = BigInt(amount)
568
+ const market = price === undefined || price === null
569
+ if (kind === undefined) {
570
+ kind = market ? OrderKind.Fill : OrderKind.Limit
571
+ }
572
+ let crossing
573
+ if (!orders || market) {
574
+ //a limit order crosses only the orders its price reaches (the contract threshold: the price of a buy, the
575
+ //inverted price of a sell) and rests with the remainder, so a partial crossing is quoted as well
576
+ const maxPrice = market ? undefined : direction === TradeDirection.Buy ? BigInt(price) : invertPrice(BigInt(price))
577
+ crossing = await this.findQuote(direction, selling, buying, amount, maxPrice)
578
+ }
579
+ if (market) {
580
+ //cross everything the quote found: the limit is the worst maker price (makers price `selling` per
581
+ //`buying` of a buyer; seen from a seller, invert it)
582
+ if (!crossing.worstPrice)
583
+ throw new Error('Not enough liquidity for a market order')
584
+ price = direction === TradeDirection.Buy ? crossing.worstPrice : invertPrice(crossing.worstPrice)
585
+ }
586
+ price = BigInt(price)
587
+ const planned = approve === undefined
588
+ if (planned) {
589
+ const required = direction === TradeDirection.Buy ? maxQuoteSpend(amount, price) : amount
590
+ approve = await this.planApproval(selling, required)
591
+ }
592
+ const payload = {
593
+ kind,
594
+ trader: this.address,
595
+ amount,
596
+ selling,
597
+ buying,
598
+ price,
599
+ orders: (orders ?? crossing.orders).map(id => BigInt(id)),
600
+ expires,
601
+ approve: approve || undefined
602
+ }
603
+ return {payload, planned}
604
+ }
605
+
606
+ /**
607
+ * Count an order this client created as committed until the indexer reports it
608
+ * @param {bigint} id
609
+ * @param {{}} trade - Trade parameters and result, for an estimate if the order cannot be read
610
+ * @return {Promise<AccountOrder|undefined>}
611
+ * @private
612
+ */
613
+ async trackCreated(id, {direction, selling, buying, amount, price, sold, bought, expires}) {
614
+ const key = id.toString()
615
+ if (this.orders.has(key))
616
+ return this.orders.get(key) //already reported
617
+ let stored
618
+ try {
619
+ const client = await this.client()
620
+ stored = await client.order(id)
621
+ } catch (e) {
622
+ //estimate below
623
+ }
624
+ if (this.orders.has(key))
625
+ return this.orders.get(key)
626
+ let orderAmount
627
+ let orderPrice
628
+ if (stored) {
629
+ orderAmount = stored.amount
630
+ orderPrice = stored.price
631
+ } else if (direction === TradeDirection.Sell) {
632
+ orderAmount = amount - sold
633
+ orderPrice = price
634
+ } else {
635
+ //the remainder of a buy sells `selling` for the rest of `buying` at the limit
636
+ orderAmount = maxQuoteSpend(amount - bought, price)
637
+ orderPrice = invertPrice(price)
638
+ }
639
+ const now = Date.now()
640
+ /** @type {AccountOrder} */
641
+ const order = {
642
+ id: key,
643
+ owner: this.address,
644
+ selling,
645
+ buying,
646
+ market: pairKey(selling, buying),
647
+ status: 'ACTIVE',
648
+ price: orderPrice,
649
+ amount: orderAmount,
650
+ quote: orderAmount,
651
+ expires: Number(stored?.expires ?? expires ?? 0),
652
+ created: now,
653
+ updated: now,
654
+ cursor: undefined,
655
+ backed: null,
656
+ backedPct: null,
657
+ backingPending: true,
658
+ filledPct: 0,
659
+ pending: true
660
+ }
661
+ this.local.set(key, {order, expires: now + LOCAL_ORDER_TTL})
662
+ this.emit('pending', order)
663
+ this.emit('change')
664
+ return order
665
+ }
666
+
667
+ /**
668
+ * Crossing orders of a direct-market trade and the worst price among them
669
+ * @param {number} direction
670
+ * @param {string} selling
671
+ * @param {string} buying
672
+ * @param {bigint} amount - `selling` amount of a sell, `buying` amount of a buy
673
+ * @param {bigint} [maxPrice] - Highest maker price to cross, for a limit order
674
+ * @return {Promise<{orders: string[], worstPrice: bigint|null}>}
675
+ * @private
676
+ */
677
+ async findQuote(direction, selling, buying, amount, maxPrice) {
678
+ const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString(), direct: true, maxPrice}
679
+ try {
680
+ const quote = direction === TradeDirection.Buy ?
681
+ await this.axis.api.quoteBuy(params) :
682
+ await this.axis.api.quoteSell(params)
683
+ const hop = quote.status === 'success' ? quote.paths?.[0]?.path?.[0] : null
684
+ if (hop)
685
+ return {orders: hop.orders ?? [], worstPrice: hop.worstPrice ? BigInt(hop.worstPrice) : null}
686
+ } catch (e) {
687
+ //nothing to cross: a limit order simply rests
688
+ }
689
+ return {orders: [], worstPrice: null}
690
+ }
691
+
692
+ /**
693
+ * Run calls submitting transactions one at a time: each one reads the sequence number and plans its approvals only
694
+ * after the previous one settled, so concurrent calls neither collide on the sequence number nor overwrite each
695
+ * other's approvals
696
+ * @template T
697
+ * @param {function(): Promise<T>} call
698
+ * @return {Promise<T>}
699
+ * @private
700
+ */
701
+ serialize(call) {
702
+ const result = this.queue.then(call)
703
+ this.queue = result.then(() => undefined, () => undefined)
704
+ return result
705
+ }
706
+
707
+ /**
708
+ * Remove orders, lowering the allowances to what the remaining orders need
709
+ * @param {Array<bigint|string>} ids
710
+ * @param {string[]} [revoke] - Tokens to revoke the allowance on with the first transaction
711
+ * @return {Promise<bigint[]>} - Removed order ids
712
+ * @private
713
+ */
714
+ removeOrders(ids, revoke) {
715
+ const changes = ids.map(id => ({current: this.getOrder(id), update: {id: BigInt(id), amount: 0n, price: 0n, expires: 0}}))
716
+ return this.submitUpdates(changes, {revoke})
717
+ }
718
+
719
+ /**
720
+ * Send order changes in `update` batches. Each batch carries the approvals that keep the allowance of every token it
721
+ * changes at what the open orders selling it need once the batch applies: raised when they grow (`grow` only), or
722
+ * when the allowance does not back the changed orders, lowered when they shrink. The `revoke` tokens are set to zero
723
+ * with the first batch
724
+ * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} changes - New values per order, with the order in
725
+ * memory when known
726
+ * @param {{grow?: boolean, revoke?: string[]}} [options] - `grow`: allowances may be raised (updates, never cancels)
727
+ * @return {Promise<bigint[]>} - Updated or removed order ids
728
+ * @throws {Error} - The submission error, with `progress` `{updated, batches}` done before it
729
+ * @private
730
+ */
731
+ async submitUpdates(changes, {grow = false, revoke = []} = {}) {
732
+ const batches = splitBatches(changes, revoke)
733
+ if (!batches.length)
734
+ return []
735
+ const plan = await this.snapshotAllowances(changes, revoke, grow)
736
+ const client = await this.client()
737
+ const ids = []
738
+ for (let i = 0; i < batches.length; i++) {
739
+ const batch = batches[i]
740
+ const approvals = i === 0 ? revoke.map(asset => ({asset, amount: 0n, liveUntil: 0})) : []
741
+ if (plan) {
742
+ approvals.push(...planBatch(plan, batch, grow))
743
+ }
744
+ for (const approval of approvals) {
745
+ this.emit('approve', approval)
746
+ }
747
+ try {
748
+ ids.push(...await client.update({trader: this.address, updates: batch.map(change => change.update), approvals}))
749
+ } catch (e) {
750
+ if (e instanceof Error) {
751
+ e.progress = {updated: ids, batches: i}
752
+ }
753
+ throw e
754
+ }
755
+ this.applyBatch(batch, approvals)
756
+ }
757
+ return ids
758
+ }
759
+
760
+ /**
761
+ * Committed amounts and allowances of the tokens the changed orders sell, read once before the first batch: every
762
+ * batch target derives from them, as pushes arriving between batches already drop the removed orders
763
+ * @param {Array<{current?: AccountOrder}>} changes
764
+ * @param {string[]} revoke - Tokens revoked anyway
765
+ * @param {boolean} grow - Whether allowances may be raised: a failed read throws then, otherwise nothing is planned
766
+ * @return {Promise<AllowancePlan|null>} - Null when no allowance is planned
767
+ * @private
768
+ */
769
+ async snapshotAllowances(changes, revoke, grow) {
770
+ const assets = new Set()
771
+ for (const {current} of changes) {
772
+ if (current && !revoke.includes(current.selling)) {
773
+ assets.add(current.selling)
774
+ }
775
+ }
776
+ if (!assets.size || !this.loaded)
777
+ return null
778
+ try {
779
+ const ledger = await this.axis.getLedger()
780
+ const tokens = new Map()
781
+ for (const asset of assets) {
782
+ const liveUntil = this.backing.get(asset)?.liveUntil ?? 0
783
+ let allowance = await this.readAllowance(asset)
784
+ if (allowance !== undefined && liveUntil > 0 && liveUntil < ledger) {
785
+ allowance = 0n //an expired allowance reads as zero
786
+ }
787
+ tokens.set(asset, {committed: this.committed(asset), allowance, liveUntil, change: 0n})
788
+ }
789
+ return {ledger, ttl: this.approvalTtl, tokens}
790
+ } catch (e) {
791
+ if (grow)
792
+ throw e
793
+ return null //a cancel goes through without lowering the allowances
794
+ }
795
+ }
796
+
797
+ /**
798
+ * Reflect a confirmed `update` batch before the indexer reports it: removed orders leave the open orders, changed
799
+ * ones take their new values, approved allowances replace the pushed ones
800
+ * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} batch
801
+ * @param {import('./index.js').Approval[]} approvals
802
+ * @private
803
+ */
804
+ applyBatch(batch, approvals) {
805
+ const until = Date.now() + LOCAL_ORDER_TTL
806
+ for (const {current, update} of batch) {
807
+ const key = update.id.toString()
808
+ if (update.amount === 0n) {
809
+ this.local.delete(key)
810
+ if (this.orders.has(key)) {
811
+ this.removed.set(key, until)
812
+ }
813
+ } else if (current) {
814
+ Object.assign(current, {amount: update.amount, price: update.price, expires: Number(update.expires)})
815
+ }
816
+ }
817
+ for (const {asset, amount, liveUntil} of approvals) {
818
+ const backing = this.backing.get(asset)
819
+ this.approved.set(asset, {
820
+ amount,
821
+ liveUntil,
822
+ replaced: backing && {allowance: backing.allowance, liveUntil: backing.liveUntil},
823
+ until: Date.now() + APPROVAL_CONFIRM_TIMEOUT
824
+ })
825
+ if (backing) {
826
+ const updated = withAllowance(backing, amount, liveUntil)
827
+ this.backing.set(asset, updated)
828
+ this.emit('backing', {asset, backing: updated})
829
+ }
830
+ }
831
+ this.emit('change')
832
+ }
833
+
834
+ /**
835
+ * Keep an allowance this client set over an incoming record that still shows the allowance it replaced
836
+ * @param {string} asset
837
+ * @param {AccountBacking} backing - Incoming record
838
+ * @return {AccountBacking}
839
+ * @private
840
+ */
841
+ reconcileBacking(asset, backing) {
842
+ const expected = this.pendingApproval(asset)
843
+ if (!expected)
844
+ return backing
845
+ const {replaced} = expected
846
+ if (replaced && backing.allowance === replaced.allowance && backing.liveUntil === replaced.liveUntil)
847
+ return withAllowance(backing, expected.amount, expected.liveUntil)
848
+ this.approved.delete(asset) //the record shows the approval, or a later change
849
+ return backing
850
+ }
851
+
852
+ /**
853
+ * Allowance set by this client that the pushed state did not confirm yet
854
+ * @param {string} asset
855
+ * @return {{amount: bigint, liveUntil: number, replaced?: {allowance: bigint, liveUntil: number}}|undefined}
856
+ * @private
857
+ */
858
+ pendingApproval(asset) {
859
+ const expected = this.approved.get(asset)
860
+ if (expected && expected.until < Date.now()) {
861
+ this.approved.delete(asset)
862
+ return undefined
863
+ }
864
+ return expected
865
+ }
866
+
867
+ /**
868
+ * Whether an order was removed by this client and the indexer has not reported it yet
869
+ * @param {string} id
870
+ * @return {boolean}
871
+ * @private
872
+ */
873
+ isRemoved(id) {
874
+ const until = this.removed.get(id)
875
+ if (until === undefined)
876
+ return false
877
+ if (until < Date.now()) {
878
+ this.removed.delete(id)
879
+ return false
880
+ }
881
+ return true
882
+ }
883
+
884
+ /**
885
+ * @return {Promise<AxisContractClient>}
886
+ * @private
887
+ */
888
+ async client() {
889
+ if (!this.signTransaction)
890
+ throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
891
+ return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
892
+ }
893
+
894
+ /**
895
+ * @param {number} [timeout]
896
+ * @return {Promise<void>}
897
+ * @private
898
+ */
899
+ async whenReady(timeout = READY_TIMEOUT) {
900
+ if (this.loaded)
901
+ return
902
+ let timer
903
+ try {
904
+ await Promise.race([
905
+ this.ready,
906
+ new Promise((resolve, reject) => {
907
+ timer = setTimeout(() => reject(new Error('The account state is not available: check the AXIS API connection')), timeout)
908
+ })
909
+ ])
910
+ } finally {
911
+ clearTimeout(timer)
912
+ }
913
+ }
914
+
915
+ /**
916
+ * @param {StreamMessage} message
917
+ * @private
918
+ */
919
+ handle(message) {
920
+ switch (message.type) {
921
+ case 'account':
922
+ this.live = true
923
+ return this.applySnapshot(message)
924
+ case 'order':
925
+ return this.applyOrder(message)
926
+ case 'backing':
927
+ return this.applyBacking(message)
928
+ case 'trade':
929
+ return this.emit('trade', message.trade)
930
+ case 'swap':
931
+ return this.emit('swap', message.swap)
932
+ case 'error':
933
+ return this.emit('error', new Error(message.error))
934
+ }
935
+ }
936
+
937
+ /**
938
+ * Replace the state with a snapshot
939
+ * @param {ApiAccount} state
940
+ * @param {boolean} [mergeBacking] - Keep the tokens missing from the snapshot
941
+ * @private
942
+ */
943
+ applySnapshot(state, mergeBacking = false) {
944
+ const previous = this.orders
945
+ const next = new Map()
946
+ for (const raw of state.orders || []) {
947
+ const order = parseApiOrder(raw)
948
+ next.set(order.id, order)
949
+ this.local.delete(order.id)
950
+ }
951
+ this.orders = next
952
+ for (const id of this.removed.keys()) {
953
+ if (!next.has(id)) {
954
+ this.removed.delete(id)
955
+ }
956
+ }
957
+ const backing = mergeBacking ? new Map(this.backing) : new Map()
958
+ for (const [asset, raw] of Object.entries(state.backing || {})) {
959
+ backing.set(asset, this.reconcileBacking(asset, parseBacking(asset, raw)))
960
+ }
961
+ this.backing = backing
962
+ if (this.loaded) {
963
+ for (const [id, order] of previous) {
964
+ if (!next.has(id)) {
965
+ this.emit('remove', order)
966
+ }
967
+ }
968
+ for (const [id, order] of next) {
969
+ if (!previous.has(id)) {
970
+ this.emit('new', order)
971
+ }
972
+ }
973
+ }
974
+ if (!this.loaded) {
975
+ this.loaded = true
976
+ this.resolveReady()
977
+ this.emit('ready')
978
+ }
979
+ this.emit('change')
980
+ }
981
+
982
+ /**
983
+ * @param {{action: string, order: import('./api-client.js').ApiOrder, fill?: {}}} message
984
+ * @private
985
+ */
986
+ applyOrder({action, order: raw, fill: rawFill}) {
987
+ const order = parseApiOrder(raw)
988
+ this.local.delete(order.id)
989
+ const previous = this.orders.get(order.id)
990
+ const removed = action === 'filled' || action === 'cancel' || action === 'expire'
991
+ if (removed) {
992
+ this.orders.delete(order.id)
993
+ this.removed.delete(order.id)
994
+ } else {
995
+ if (previous && order.backed === null) {
996
+ //the event serialization may lack the split; keep the last known one until the backing update
997
+ order.backed = previous.backed
998
+ order.backedPct = previous.backedPct
999
+ order.backingPending = previous.backingPending
1000
+ }
1001
+ this.orders.set(order.id, order)
1002
+ }
1003
+ const fill = rawFill && {
1004
+ order,
1005
+ sold: BigInt(rawFill.sold),
1006
+ bought: BigInt(rawFill.bought),
1007
+ taker: rawFill.taker,
1008
+ trade: rawFill.trade?.toString(),
1009
+ ts: Number(rawFill.ts) * 1000,
1010
+ partial: action === 'fill'
1011
+ }
1012
+ this.emit(action, fill || order)
1013
+ if (removed) {
1014
+ this.emit('remove', order)
1015
+ }
1016
+ this.emit('order', {action, order, fill})
1017
+ this.emit('change')
1018
+ }
1019
+
1020
+ /**
1021
+ * @param {{asset: string, backing: import('./api-client.js').ApiBacking|null, backed?: Object<string, string>}} message
1022
+ * @private
1023
+ */
1024
+ applyBacking({asset, backing: raw, backed}) {
1025
+ const backing = raw ? this.reconcileBacking(asset, parseBacking(asset, raw)) : undefined
1026
+ if (backing) {
1027
+ this.backing.set(asset, backing)
1028
+ } else {
1029
+ this.backing.delete(asset)
1030
+ }
1031
+ for (const [id, amount] of Object.entries(backed || {})) {
1032
+ const order = this.orders.get(id)
1033
+ if (!order)
1034
+ continue
1035
+ order.backed = BigInt(amount)
1036
+ order.backedPct = share(order.backed, order.amount)
1037
+ order.backingPending = !backing || backing.pending || !backing.updated
1038
+ }
1039
+ this.emit('backing', {asset, backing})
1040
+ this.emit('change')
1041
+ }
1042
+
1043
+ /**
1044
+ * @return {Iterable<AccountOrder>}
1045
+ * @private
1046
+ */
1047
+ * allOrders() {
1048
+ for (const order of this.orders.values()) {
1049
+ if (!this.isRemoved(order.id)) {
1050
+ yield order
1051
+ }
1052
+ }
1053
+ yield* this.localOrders()
1054
+ }
1055
+
1056
+ /**
1057
+ * Get local orders that haven't expired
1058
+ * @return {AccountOrder[]}
1059
+ * @private
1060
+ */
1061
+ localOrders() {
1062
+ const now = Date.now()
1063
+ const res = []
1064
+ for (const [id, {order, expires}] of this.local) {
1065
+ if (expires < now || this.orders.has(id)) {
1066
+ this.local.delete(id)
1067
+ } else {
1068
+ res.push(order)
1069
+ }
1070
+ }
1071
+ return res
1072
+ }
1073
+
1074
+ /**
1075
+ * @private
1076
+ */
1077
+ startFallback() {
1078
+ if (this.fallbackTimer)
1079
+ return
1080
+ this.fallbackTimer = setInterval(() => {
1081
+ this.refresh().catch(() => {
1082
+ //retried on the next tick
1083
+ })
1084
+ }, this.axis.fallbackPollInterval)
1085
+ }
1086
+
1087
+ /**
1088
+ * @private
1089
+ */
1090
+ stopFallback() {
1091
+ clearInterval(this.fallbackTimer)
1092
+ this.fallbackTimer = undefined
1093
+ }
1094
+ }
1095
+
1096
+ /**
1097
+ * Convert an API order to the client form (bigint amounts and prices, numeric timestamps)
1098
+ * @param {ApiOrder} raw
1099
+ * @return {AccountOrder}
1100
+ */
1101
+ export function parseApiOrder(raw) {
1102
+ const amount = BigInt(raw.amount)
1103
+ const quote = BigInt(raw.quote ?? raw.amount)
1104
+ //unconfirmed until loaded, and while a reload confirming the latest event is due
1105
+ const confirmed = raw.backed !== undefined && !!raw.backing?.updated && !raw.backing?.pending
1106
+ const backed = raw.backed !== undefined ? BigInt(raw.backed) : null
1107
+ return {
1108
+ id: raw.id,
1109
+ owner: raw.owner,
1110
+ selling: raw.selling,
1111
+ buying: raw.buying,
1112
+ market: pairKey(raw.selling, raw.buying),
1113
+ status: raw.status,
1114
+ price: BigInt(raw.price),
1115
+ amount,
1116
+ quote,
1117
+ expires: raw.expires ? Math.floor(parseApiDate(raw.expires) / 1000) : 0,
1118
+ created: parseApiDate(raw.created),
1119
+ updated: parseApiDate(raw.updated),
1120
+ cursor: raw.cursor !== undefined ? BigInt(raw.cursor) : undefined,
1121
+ backed,
1122
+ backedPct: backed === null ? null : share(backed, amount),
1123
+ backingPending: !confirmed,
1124
+ filledPct: quote > 0n ? Math.max(0, Math.min(1, 1 - Number(amount * 10_000n / quote) / 10_000)) : 0,
1125
+ pending: false
1126
+ }
1127
+ }
1128
+
1129
+ /**
1130
+ * @param {string} asset
1131
+ * @param {ApiBacking} raw
1132
+ * @return {AccountBacking}
1133
+ */
1134
+ function parseBacking(asset, raw) {
1135
+ return {
1136
+ asset,
1137
+ balance: BigInt(raw.balance),
1138
+ allowance: BigInt(raw.allowance),
1139
+ liveUntil: raw.liveUntil || 0,
1140
+ authorized: raw.authorized !== false,
1141
+ budget: BigInt(raw.budget ?? 0),
1142
+ updated: parseApiDate(raw.updated),
1143
+ skipped: parseApiDate(raw.skipped),
1144
+ pending: raw.pending === true
1145
+ }
1146
+ }
1147
+
1148
+ /**
1149
+ * @param {bigint} part
1150
+ * @param {bigint} total
1151
+ * @return {number} - 0..1
1152
+ */
1153
+ function share(part, total) {
1154
+ if (total <= 0n)
1155
+ return 1
1156
+ return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
1157
+ }
1158
+
1159
+ /**
1160
+ * Split order changes into `update` batches, leaving event room for the approvals a batch may carry
1161
+ * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} changes
1162
+ * @param {string[]} revoke - Tokens revoked with the first batch
1163
+ * @return {Array<Array<{current?: AccountOrder, update: OrderUpdate}>>}
1164
+ */
1165
+ function splitBatches(changes, revoke) {
1166
+ const batches = []
1167
+ let batch
1168
+ let tokens
1169
+ for (const change of changes) {
1170
+ const asset = change.current?.selling
1171
+ if (batch) {
1172
+ const approvals = tokens.size + (asset && !tokens.has(asset) ? 1 : 0)
1173
+ if (batch.length + 1 + APPROVAL_BATCH_WEIGHT * approvals > UPDATE_BATCH) {
1174
+ batch = undefined
1175
+ }
1176
+ }
1177
+ if (!batch) {
1178
+ batch = []
1179
+ tokens = new Set(batches.length ? [] : revoke)
1180
+ batches.push(batch)
1181
+ }
1182
+ batch.push(change)
1183
+ if (asset) {
1184
+ tokens.add(asset)
1185
+ }
1186
+ }
1187
+ if (!batches.length && revoke.length) {
1188
+ batches.push([]) //a revocation alone
1189
+ }
1190
+ return batches
1191
+ }
1192
+
1193
+ /**
1194
+ * Approvals of one `update` batch, advancing the planned allowances: an allowance grows only when the batch
1195
+ * grows the orders selling the token, or when it does not back the changed orders (the contract checks that), and
1196
+ * lowered when the batch shrinks them
1197
+ * @param {AllowancePlan} plan
1198
+ * @param {Array<{current?: AccountOrder, update: OrderUpdate}>} batch
1199
+ * @param {boolean} grow - Whether allowances may be raised
1200
+ * @return {import('./index.js').Approval[]}
1201
+ */
1202
+ function planBatch({ledger, ttl, tokens}, batch, grow) {
1203
+ //change of the committed amount and the new amounts of the changed orders, per sold token
1204
+ const changed = new Map()
1205
+ for (const {current, update} of batch) {
1206
+ if (!current || !tokens.has(current.selling))
1207
+ continue
1208
+ const entry = changed.get(current.selling) ?? {delta: 0n, need: 0n}
1209
+ entry.delta += update.amount - current.amount
1210
+ entry.need += update.amount
1211
+ changed.set(current.selling, entry)
1212
+ }
1213
+ const approvals = []
1214
+ for (const [asset, {delta, need}] of changed) {
1215
+ const token = tokens.get(asset)
1216
+ token.change += delta
1217
+ let approval
1218
+ if (grow && (delta > 0n || (token.allowance ?? 0n) < need)) {
1219
+ //unknown: a redundant approval, never a shortfall
1220
+ approval = planApproval({required: token.change, committed: token.committed, allowance: token.allowance ?? 0n, liveUntil: token.liveUntil, ledger, ttl})
1221
+ } else if (delta < 0n && token.allowance !== undefined) {
1222
+ approval = planReduction({target: token.committed + token.change, allowance: token.allowance, liveUntil: token.liveUntil, ledger, ttl})
1223
+ }
1224
+ if (approval) {
1225
+ approvals.push({asset, ...approval})
1226
+ token.allowance = approval.amount
1227
+ token.liveUntil = approval.liveUntil
1228
+ }
1229
+ }
1230
+ return approvals
1231
+ }
1232
+
1233
+ /**
1234
+ * @param {AccountBacking} backing
1235
+ * @param {bigint} allowance
1236
+ * @param {number} liveUntil
1237
+ * @return {AccountBacking} - The record with another allowance
1238
+ */
1239
+ function withAllowance(backing, allowance, liveUntil) {
1240
+ const budget = !backing.authorized ? 0n : backing.balance < allowance ? backing.balance : allowance
1241
+ return {...backing, allowance, liveUntil, budget}
1242
+ }
1243
+
1244
+ /**
1245
+ * @param {string|{base: string, quote: string}|string[]|undefined} market
1246
+ * @return {string|undefined}
1247
+ */
1248
+ function toMarketKey(market) {
1249
+ if (!market)
1250
+ return undefined
1251
+ if (typeof market === 'string') {
1252
+ const [x, y] = market.split('/')
1253
+ return pairKey(x, y)
1254
+ }
1255
+ if (Array.isArray(market))
1256
+ return pairKey(market[0], market[1])
1257
+ return pairKey(market.base, market.quote)
1258
+ }
1259
+
1260
+ /**
1261
+ * Newest first: unconfirmed local orders, then by creation position
1262
+ * @param {AccountOrder} x
1263
+ * @param {AccountOrder} y
1264
+ * @return {number}
1265
+ */
1266
+ function newestFirst(x, y) {
1267
+ if (x.cursor === undefined || y.cursor === undefined)
1268
+ return (x.cursor === undefined ? 0 : 1) - (y.cursor === undefined ? 0 : 1) || y.created - x.created
1269
+ return x.cursor < y.cursor ? 1 : x.cursor > y.cursor ? -1 : 0
1270
+ }
1271
+
1272
+ /**
1273
+ * @typedef {{}} AccountOrder - Open order of a tracked account
1274
+ * @property {string} id - Order id (decimal u128)
1275
+ * @property {string} owner - Maker address
1276
+ * @property {string} selling - Sold token
1277
+ * @property {string} buying - Bought token
1278
+ * @property {string} market - Market key
1279
+ * @property {'ACTIVE'|'FILLED'|'CANCELED'|'EXPIRED'} status - Current status
1280
+ * @property {bigint} price - `buying` per 1 `selling`, contract scale (18 decimals)
1281
+ * @property {bigint} amount - Amount of `selling` left
1282
+ * @property {bigint} quote - Amount of `selling` at creation
1283
+ * @property {number} expires - Expiration UNIX timestamp in seconds, 0 = none
1284
+ * @property {number} created - Creation time, UNIX milliseconds
1285
+ * @property {number} updated - Last change, UNIX milliseconds
1286
+ * @property {bigint} [cursor] - Paging cursor (undefined for unconfirmed local orders)
1287
+ * @property {bigint|null} backed - Share of the account budget in `selling` that backs the order
1288
+ * @property {number|null} backedPct - `backed / amount` (0..1), null when unknown
1289
+ * @property {boolean} backingPending - The backing is not confirmed yet
1290
+ * @property {number} filledPct - Filled share of the initial amount (0..1)
1291
+ * @property {boolean} pending - Created by this client, not reported by the indexer yet
1292
+ */
1293
+
1294
+ /**
1295
+ * @typedef {{}} AccountBacking - Balance and allowance of the account in a token, as tracked by the indexer
1296
+ * @property {string} asset
1297
+ * @property {bigint} balance - Spendable amount (balance minus reserve and liabilities)
1298
+ * @property {bigint} allowance - Allowance granted to the AXIS contract
1299
+ * @property {number} liveUntil - Ledger sequence the allowance lives until
1300
+ * @property {boolean} authorized - Whether the account can send and receive the token
1301
+ * @property {bigint} budget - min(balance, allowance), 0 when unauthorized or expired
1302
+ * @property {number} updated - Last load, UNIX milliseconds (0 = not loaded)
1303
+ * @property {number} skipped - Last skipped fill of an order selling the token, UNIX milliseconds (0 = none)
1304
+ * @property {boolean} pending - A reload confirming the latest change is due
1305
+ */
1306
+
1307
+ /**
1308
+ * @typedef {{}} AccountAllowance
1309
+ * @property {string} asset
1310
+ * @property {boolean} known - Whether the backing is tracked and loaded
1311
+ * @property {bigint} [balance]
1312
+ * @property {bigint} [allowance]
1313
+ * @property {number} [liveUntil]
1314
+ * @property {boolean} [authorized]
1315
+ * @property {boolean} [pending]
1316
+ * @property {bigint} [available] - min(balance, allowance)
1317
+ * @property {bigint} committed - Remaining amount of the open orders selling the token
1318
+ */
1319
+
1320
+ /**
1321
+ * @typedef {{}} AccountFill
1322
+ * @property {AccountOrder} order - Order after the fill
1323
+ * @property {bigint} sold - Amount of `selling` delivered
1324
+ * @property {bigint} bought - Amount of `buying` received
1325
+ * @property {string} taker - Taker address
1326
+ * @property {string} trade - Trade id
1327
+ * @property {number} ts - Trade time, UNIX milliseconds
1328
+ * @property {boolean} partial - Whether the order is still open
1329
+ */
1330
+
1331
+ /**
1332
+ * @typedef {{}} TradeParams
1333
+ * @property {string} selling - Token sent
1334
+ * @property {string} buying - Token received
1335
+ * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1336
+ * @property {bigint|string} [price] - Limit price, contract scale; omitted for a market order
1337
+ * @property {number} [kind] - {@link OrderKind}: `Limit` by default, `Fill` for a market order
1338
+ * @property {number} [expires] - Expiration UNIX timestamp (seconds) of the resting remainder
1339
+ * @property {Array<bigint|string>} [orders] - Counter orders to cross, looked up automatically when omitted
1340
+ * @property {Approval|null} [approve] - Explicit approval (`null` for none)
1341
+ */
1342
+
1343
+ /**
1344
+ * @typedef {{}} TradeResult
1345
+ * @property {bigint} sold - Amount of `selling` sent
1346
+ * @property {bigint} bought - Amount of `buying` received
1347
+ * @property {string} [orderId] - ID of the order created for a limit remainder
1348
+ * @property {AccountOrder} [order] - The created order (unconfirmed until the indexer reports it)
1349
+ * @property {Approval} [approve] - Approval granted with the trade
1350
+ */
1351
+
1352
+ /**
1353
+ * @typedef {{}} AccountRevokeResult
1354
+ * @property {string[]} revoked - Tokens whose allowance was set to zero
1355
+ * @property {string[]} canceled - Canceled order ids
1356
+ */
1357
+
1358
+ /**
1359
+ * @typedef {{}} AllowancePlan - Allowances planned across the `update` batches of a call
1360
+ * @property {number} ledger - Current ledger sequence
1361
+ * @property {number} ttl - Lifetime of a new allowance, in ledgers
1362
+ * @property {Map<string, {committed: bigint, allowance?: bigint, liveUntil: number, change: bigint}>} tokens - Open amount before the call, the current allowance (undefined when unknown) and the committed change of the batches planned so far for each sold token
1363
+ */
1364
+
1365
+ /**
1366
+ * @typedef {import('./index.js').OrderUpdate} OrderUpdate
1367
+ */
1368
+
1369
+ /**
1370
+ * @typedef {{}} SwapParams
1371
+ * @property {string} selling - Token sent
1372
+ * @property {string} buying - Token received
1373
+ * @property {bigint|string} amount - `selling` amount of a sell, `buying` amount of a buy (raw units)
1374
+ * @property {number} [direction] - {@link TradeDirection}, `Sell` by default
1375
+ * @property {number} [slippage] - Price tolerance as a fraction (0.005 = 0.5%), 0 by default
1376
+ */