@axis-markets/client 0.8.3 → 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,15 +1,21 @@
1
1
  import {Emitter} from './emitter.js'
2
2
  import {pairKey, invertPrice} from './asset-pair.js'
3
3
  import {parseApiDate} from './api-dates.js'
4
- import {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'
4
+ import {planApproval, planReduction, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'
5
5
  import {OrderKind, TradeDirection} from './constants.js'
6
6
 
7
7
  /** Orders per `update` transaction */
8
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
9
12
  /** Time to wait for the account state before trading, in milliseconds */
10
13
  const READY_TIMEOUT = 15_000
11
14
  /** How long an order created by this client counts as committed before the indexer reports it, in milliseconds */
12
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
13
19
 
14
20
  /**
15
21
  * Trader wrapper that tracks every open order of an account across all markets and the account backing.
@@ -27,7 +33,7 @@ const LOCAL_ORDER_TTL = 120_000
27
33
  * - `remove` {@link AccountOrder} - an order left the open orders (after `filled`, `cancel`, `expire`)
28
34
  * - `order` `{action, order, fill?}` - any order change
29
35
  * - `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
36
+ * - `approve` `{asset, amount, liveUntil}` - a call is about to set an allowance (grant, renew, lower or revoke it)
31
37
  * - `trade` {ApiTrade} - the account performed a trade
32
38
  * - `swap` {ApiSwap} - the account performed a swap
33
39
  * - `change` - the open orders or the backing changed
@@ -105,6 +111,24 @@ export class AxisAccount extends Emitter {
105
111
  * @private
106
112
  */
107
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()
108
132
  /**
109
133
  * @type {function(): void}
110
134
  * @private
@@ -179,6 +203,8 @@ export class AxisAccount extends Emitter {
179
203
  */
180
204
  getOrder(id) {
181
205
  const key = id.toString()
206
+ if (this.isRemoved(key))
207
+ return undefined
182
208
  return this.orders.get(key) ?? this.localOrders().find(order => order.id === key)
183
209
  }
184
210
 
@@ -259,7 +285,7 @@ export class AxisAccount extends Emitter {
259
285
  * @return {Promise<TradeResult>}
260
286
  */
261
287
  async sell(params) {
262
- return this.trade(TradeDirection.Sell, params)
288
+ return this.serialize(() => this.trade(TradeDirection.Sell, params))
263
289
  }
264
290
 
265
291
  /**
@@ -268,7 +294,7 @@ export class AxisAccount extends Emitter {
268
294
  * @return {Promise<TradeResult>}
269
295
  */
270
296
  async buy(params) {
271
- return this.trade(TradeDirection.Buy, params)
297
+ return this.serialize(() => this.trade(TradeDirection.Buy, params))
272
298
  }
273
299
 
274
300
  /**
@@ -294,82 +320,85 @@ export class AxisAccount extends Emitter {
294
320
  }
295
321
 
296
322
  /**
297
- * Change the amount, price or expiration of open orders (omitted fields keep their current values)
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
298
326
  * @param {Array<{id: bigint|string, amount?: bigint, price?: bigint, expires?: number}>} updates
299
327
  * @return {Promise<bigint[]>} - Updated order ids
300
328
  */
301
329
  async update(updates) {
302
- await this.whenReady()
303
- const normalized = updates.map(update => {
304
- const current = this.getOrder(update.id)
305
- if (!current && (update.amount === undefined || update.price === undefined))
306
- throw new Error(`Order ${update.id} is not an open order of ${this.address}`)
307
- return {
308
- current,
309
- update: {
310
- id: BigInt(update.id),
311
- amount: update.amount ?? current.amount,
312
- price: update.price ?? current.price,
313
- expires: update.expires ?? current?.expires ?? 0
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
+ }
314
344
  }
315
- }
345
+ })
346
+ return this.submitUpdates(changes, {grow: true})
316
347
  })
317
- //extra commitment per sold token
318
- const growth = new Map()
319
- for (const {current, update} of normalized) {
320
- if (!current)
321
- continue
322
- growth.set(current.selling, (growth.get(current.selling) ?? 0n) + update.amount - current.amount)
323
- }
324
- const approvals = []
325
- for (const [asset, delta] of growth) {
326
- if (delta <= 0n)
327
- continue
328
- const approve = await this.planApproval(asset, delta)
329
- if (approve) {
330
- this.emit('approve', {asset, ...approve})
331
- approvals.push({asset, ...approve})
332
- }
333
- }
334
- const client = await this.client()
335
- const res = []
336
- for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
337
- const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
338
- //approvals travel with the first batch, before its backing check
339
- const ids = await client.update({trader: this.address, updates: batch, approvals: i === 0 ? approvals : []})
340
- res.push(...ids)
341
- }
342
- return res
343
348
  }
344
349
 
345
350
  /**
346
- * Cancel open orders
351
+ * Cancel open orders, lowering the allowance of every sold token to what its remaining open orders need
347
352
  * @param {Array<bigint|string>} ids
348
353
  * @return {Promise<void>}
349
354
  */
350
355
  async cancel(ids) {
351
- const client = await this.client()
352
- const all = ids.map(id => BigInt(id))
353
- for (let i = 0; i < all.length; i += UPDATE_BATCH) {
354
- await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
355
- }
356
- for (const id of all) {
357
- this.local.delete(id.toString())
358
- }
356
+ await this.serialize(() => this.removeOrders(ids))
359
357
  }
360
358
 
361
359
  /**
362
- * Cancel all open orders
360
+ * Cancel all open orders, lowering the allowances like `cancel`
363
361
  * @param {{market?: string|{base: string, quote: string}|string[]}} [filter]
364
362
  * @return {Promise<string[]>} - Canceled order ids
365
363
  */
366
364
  async cancelAll({market} = {}) {
367
- await this.whenReady()
368
- const ids = this.getOrders({market}).map(order => order.id)
369
- if (ids.length) {
370
- await this.cancel(ids)
371
- }
372
- return ids
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
+ })
373
402
  }
374
403
 
375
404
  /**
@@ -379,15 +408,17 @@ export class AxisAccount extends Emitter {
379
408
  * @return {Promise<{sold: bigint, bought: bigint, surplus: bigint}>}
380
409
  */
381
410
  async crossfill(takerOrderId, orders) {
382
- if (!orders) {
383
- const taker = this.getOrder(takerOrderId) ?? await this.axis.getOrder(takerOrderId)
384
- if (!taker)
385
- throw new Error(`Order ${takerOrderId} not found`)
386
- orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
387
- }
388
- const client = await this.client()
389
- const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
390
- return {sold, bought, surplus}
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
+ })
391
422
  }
392
423
 
393
424
  /**
@@ -395,7 +426,16 @@ export class AxisAccount extends Emitter {
395
426
  * @param {SwapParams} params
396
427
  * @return {Promise<{sold: bigint, bought: bigint, approve?: import('./index.js').Approval}>}
397
428
  */
398
- async swap({selling, buying, amount, direction = TradeDirection.Sell, slippage = 0}) {
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}) {
399
439
  await this.whenReady()
400
440
  const params = {sellingAsset: selling, buyingAsset: buying, amount: amount.toString()}
401
441
  const quote = direction === TradeDirection.Buy ?
@@ -440,27 +480,35 @@ export class AxisAccount extends Emitter {
440
480
  */
441
481
  async planApproval(asset, required) {
442
482
  await this.whenReady()
443
- const backing = this.backing.get(asset)
444
- let allowance
445
- if (this.isAllowanceCurrent(asset) || (backing?.updated && !this.axis.tokenBalances)) {
446
- allowance = backing.allowance
447
- } else {
448
- const {tokenBalances} = this.axis
449
- if (!tokenBalances)
450
- throw new Error(`The allowance of ${this.address} in ${asset} is not tracked: set the \`rpcUrl\` option to read it`)
451
- await this.axis.getContractId() //the allowance spender
452
- allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
453
- }
483
+ const allowance = await this.readAllowance(asset) ?? 0n //unknown: a redundant approval, never a shortfall
454
484
  return planApproval({
455
485
  required,
456
486
  committed: this.committed(asset),
457
487
  allowance,
458
- liveUntil: backing?.liveUntil ?? 0,
488
+ liveUntil: this.backing.get(asset)?.liveUntil ?? 0,
459
489
  ledger: await this.axis.getLedger(),
460
490
  ttl: this.approvalTtl
461
491
  })
462
492
  }
463
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
+
464
512
  /**
465
513
  * Check whether the pushed allowance of a token can be used as is
466
514
  * @param {string} asset - Token contract id
@@ -471,6 +519,8 @@ export class AxisAccount extends Emitter {
471
519
  const backing = this.backing.get(asset)
472
520
  if (!this.live || !this.axis.stream.connected || !backing?.updated || backing.pending)
473
521
  return false
522
+ if (this.pendingApproval(asset))
523
+ return false //set by this client, not confirmed by the push yet
474
524
  const spent = this.spent.get(asset)
475
525
  if (spent === undefined)
476
526
  return true
@@ -639,6 +689,198 @@ export class AxisAccount extends Emitter {
639
689
  return {orders: [], worstPrice: null}
640
690
  }
641
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
+
642
884
  /**
643
885
  * @return {Promise<AxisContractClient>}
644
886
  * @private
@@ -707,9 +949,14 @@ export class AxisAccount extends Emitter {
707
949
  this.local.delete(order.id)
708
950
  }
709
951
  this.orders = next
952
+ for (const id of this.removed.keys()) {
953
+ if (!next.has(id)) {
954
+ this.removed.delete(id)
955
+ }
956
+ }
710
957
  const backing = mergeBacking ? new Map(this.backing) : new Map()
711
958
  for (const [asset, raw] of Object.entries(state.backing || {})) {
712
- backing.set(asset, parseBacking(asset, raw))
959
+ backing.set(asset, this.reconcileBacking(asset, parseBacking(asset, raw)))
713
960
  }
714
961
  this.backing = backing
715
962
  if (this.loaded) {
@@ -743,6 +990,7 @@ export class AxisAccount extends Emitter {
743
990
  const removed = action === 'filled' || action === 'cancel' || action === 'expire'
744
991
  if (removed) {
745
992
  this.orders.delete(order.id)
993
+ this.removed.delete(order.id)
746
994
  } else {
747
995
  if (previous && order.backed === null) {
748
996
  //the event serialization may lack the split; keep the last known one until the backing update
@@ -774,7 +1022,7 @@ export class AxisAccount extends Emitter {
774
1022
  * @private
775
1023
  */
776
1024
  applyBacking({asset, backing: raw, backed}) {
777
- const backing = raw ? parseBacking(asset, raw) : undefined
1025
+ const backing = raw ? this.reconcileBacking(asset, parseBacking(asset, raw)) : undefined
778
1026
  if (backing) {
779
1027
  this.backing.set(asset, backing)
780
1028
  } else {
@@ -797,7 +1045,11 @@ export class AxisAccount extends Emitter {
797
1045
  * @private
798
1046
  */
799
1047
  * allOrders() {
800
- yield* this.orders.values()
1048
+ for (const order of this.orders.values()) {
1049
+ if (!this.isRemoved(order.id)) {
1050
+ yield order
1051
+ }
1052
+ }
801
1053
  yield* this.localOrders()
802
1054
  }
803
1055
 
@@ -904,6 +1156,91 @@ function share(part, total) {
904
1156
  return Math.max(0, Math.min(1, Number(part * 10_000n / total) / 10_000))
905
1157
  }
906
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
+
907
1244
  /**
908
1245
  * @param {string|{base: string, quote: string}|string[]|undefined} market
909
1246
  * @return {string|undefined}
@@ -1012,6 +1349,23 @@ function newestFirst(x, y) {
1012
1349
  * @property {Approval} [approve] - Approval granted with the trade
1013
1350
  */
1014
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
+
1015
1369
  /**
1016
1370
  * @typedef {{}} SwapParams
1017
1371
  * @property {string} selling - Token sent