@axis-markets/client 0.8.1 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
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} from './allowance.js'
4
+ import {planApproval, maxQuoteSpend, APPROVAL_TTL_LEDGERS} from './allowance.js'
5
5
  import {OrderKind, TradeDirection} from './constants.js'
6
6
 
7
7
  /** Orders per `update` transaction */
@@ -37,13 +37,14 @@ export class AxisAccount extends Emitter {
37
37
  /**
38
38
  * @param {Axis} axis
39
39
  * @param {string} address - Trader address
40
- * @param {{signTransaction?: SignTransactionCallback}} [options]
40
+ * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options]
41
41
  */
42
- constructor(axis, address, {signTransaction} = {}) {
42
+ constructor(axis, address, {signTransaction, approvalTtl} = {}) {
43
43
  super()
44
44
  this.axis = axis
45
45
  this.address = address
46
46
  this.signTransaction = signTransaction
47
+ this.approvalTtl = approvalTtl || APPROVAL_TTL_LEDGERS
47
48
  this.ready = new Promise(resolve => this.resolveReady = resolve)
48
49
  }
49
50
 
@@ -58,6 +59,11 @@ export class AxisAccount extends Emitter {
58
59
  * @type {SignTransactionCallback|undefined}
59
60
  */
60
61
  signTransaction
62
+ /**
63
+ * Lifetime of the allowances granted by trading calls, in ledgers
64
+ * @type {number}
65
+ */
66
+ approvalTtl
61
67
  /**
62
68
  * Open orders by id
63
69
  * @type {Map<string, AccountOrder>}
@@ -272,7 +278,8 @@ export class AxisAccount extends Emitter {
272
278
  */
273
279
  async estimateSell(params) {
274
280
  const {payload} = await this.prepareTrade(TradeDirection.Sell, params)
275
- return this.client().estimateSell(payload)
281
+ const client = await this.client()
282
+ return client.estimateSell(payload)
276
283
  }
277
284
 
278
285
  /**
@@ -282,7 +289,8 @@ export class AxisAccount extends Emitter {
282
289
  */
283
290
  async estimateBuy(params) {
284
291
  const {payload} = await this.prepareTrade(TradeDirection.Buy, params)
285
- return this.client().estimateBuy(payload)
292
+ const client = await this.client()
293
+ return client.estimateBuy(payload)
286
294
  }
287
295
 
288
296
  /**
@@ -323,7 +331,7 @@ export class AxisAccount extends Emitter {
323
331
  approvals.push({asset, ...approve})
324
332
  }
325
333
  }
326
- const client = this.client()
334
+ const client = await this.client()
327
335
  const res = []
328
336
  for (let i = 0; i < normalized.length; i += UPDATE_BATCH) {
329
337
  const batch = normalized.slice(i, i + UPDATE_BATCH).map(n => n.update)
@@ -340,7 +348,7 @@ export class AxisAccount extends Emitter {
340
348
  * @return {Promise<void>}
341
349
  */
342
350
  async cancel(ids) {
343
- const client = this.client()
351
+ const client = await this.client()
344
352
  const all = ids.map(id => BigInt(id))
345
353
  for (let i = 0; i < all.length; i += UPDATE_BATCH) {
346
354
  await client.cancel(this.address, all.slice(i, i + UPDATE_BATCH))
@@ -377,7 +385,8 @@ export class AxisAccount extends Emitter {
377
385
  throw new Error(`Order ${takerOrderId} not found`)
378
386
  orders = (await this.findQuote(TradeDirection.Sell, taker.selling, taker.buying, taker.amount)).orders
379
387
  }
380
- const [sold, bought, surplus] = await this.client().crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
388
+ const client = await this.client()
389
+ const [sold, bought, surplus] = await client.crossfill(this.address, BigInt(takerOrderId), orders.map(id => BigInt(id)))
381
390
  return {sold, bought, surplus}
382
391
  }
383
392
 
@@ -409,7 +418,8 @@ export class AxisAccount extends Emitter {
409
418
  if (approve) {
410
419
  this.emit('approve', {asset: selling, ...approve})
411
420
  }
412
- const [sold, bought] = await this.client().swap({
421
+ const client = await this.client()
422
+ const [sold, bought] = await client.swap({
413
423
  direction,
414
424
  trader: this.address,
415
425
  selling,
@@ -438,6 +448,7 @@ export class AxisAccount extends Emitter {
438
448
  const {tokenBalances} = this.axis
439
449
  if (!tokenBalances)
440
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
441
452
  allowance = await tokenBalances.getAllowance(asset, this.address).catch(() => 0n) //unknown: a redundant approval, never a shortfall
442
453
  }
443
454
  return planApproval({
@@ -445,7 +456,8 @@ export class AxisAccount extends Emitter {
445
456
  committed: this.committed(asset),
446
457
  allowance,
447
458
  liveUntil: backing?.liveUntil ?? 0,
448
- ledger: await this.axis.getLedger()
459
+ ledger: await this.axis.getLedger(),
460
+ ttl: this.approvalTtl
449
461
  })
450
462
  }
451
463
 
@@ -480,7 +492,7 @@ export class AxisAccount extends Emitter {
480
492
  if (planned && approve) {
481
493
  this.emit('approve', {asset: selling, ...approve})
482
494
  }
483
- const client = this.client()
495
+ const client = await this.client()
484
496
  const [sold, bought, createdId] = direction === TradeDirection.Buy ?
485
497
  await client.buy(payload) :
486
498
  await client.sell(payload)
@@ -554,7 +566,8 @@ export class AxisAccount extends Emitter {
554
566
  return this.orders.get(key) //already reported
555
567
  let stored
556
568
  try {
557
- stored = await this.client().order(id)
569
+ const client = await this.client()
570
+ stored = await client.order(id)
558
571
  } catch (e) {
559
572
  //estimate below
560
573
  }
@@ -627,10 +640,10 @@ export class AxisAccount extends Emitter {
627
640
  }
628
641
 
629
642
  /**
630
- * @return {AxisContractClient}
643
+ * @return {Promise<AxisContractClient>}
631
644
  * @private
632
645
  */
633
- client() {
646
+ async client() {
634
647
  if (!this.signTransaction)
635
648
  throw new Error(`No signTransaction callback for ${this.address}: pass it to axis.account()`)
636
649
  return this.axis.contractClient({publicKey: this.address, signTransaction: this.signTransaction})
@@ -1,181 +1,182 @@
1
- import {canonicalPair} from './asset-pair.js'
2
- import {parseApiDate} from './api-dates.js'
3
-
4
- /**
5
- * DEX Market
6
- */
7
- export class AxisMarket {
8
- /**
9
- * @param {Axis} axis
10
- * @param {{base: string, quote: string, created?: string, refreshed?: string}} record - Market data
11
- */
12
- constructor(axis, record) {
13
- this.axis = axis
14
- const [base, quote] = canonicalPair(record.base, record.quote)
15
- this.base = base
16
- this.quote = quote
17
- this.key = base + '/' + quote
18
- this.update(record)
19
- }
20
-
21
- /**
22
- * Base asset, the first of the pair in the contract canonical order
23
- * @type {string}
24
- * @readonly
25
- */
26
- base
27
- /**
28
- * Quote asset, the second of the pair in the contract canonical order
29
- * @type {string}
30
- * @readonly
31
- */
32
- quote
33
- /**
34
- * Canonical market key `base/quote`
35
- * @type {string}
36
- * @readonly
37
- */
38
- key
39
- /**
40
- * Creation timestamp (first oracle check) (UNIX milliseconds)
41
- * @type {number}
42
- */
43
- created = 0
44
- /**
45
- * Last oracle check (UNIX milliseconds)
46
- * @type {number}
47
- */
48
- refreshed = 0
49
-
50
- /**
51
- * Check whether the asset is one of the market assets
52
- * @param {string} asset
53
- * @return {boolean}
54
- */
55
- has(asset) {
56
- return asset === this.base || asset === this.quote
57
- }
58
-
59
- /**
60
- * The other market asset
61
- * @param {string} asset - One of the market assets
62
- * @return {string}
63
- */
64
- counter(asset) {
65
- if (asset === this.base)
66
- return this.quote
67
- if (asset === this.quote)
68
- return this.base
69
- throw new Error(`Asset ${asset} does not belong to the market ${this.key}`)
70
- }
71
-
72
- /**
73
- * Apply the contract state change record
74
- * @param {{created?: string, refreshed?: string}} record
75
- * @internal
76
- */
77
- update(record) {
78
- if (record.created) {
79
- this.created = parseApiDate(record.created)
80
- }
81
- if (record.refreshed) {
82
- this.refreshed = parseApiDate(record.refreshed)
83
- }
84
- }
85
-
86
- /**
87
- * Re-check both market assets against the price oracle and cache oracle prices
88
- * @param {Signer} [signer] - Transaction source, the {@link Axis} signer by default
89
- * @return {Promise<Market|undefined>}
90
- */
91
- async requote(signer) {
92
- return this.axis.contractClient(signer).requote(this.base, this.quote)
93
- }
94
-
95
- /**
96
- * Extend oracle price feeds access for the market
97
- * @param {{amount: bigint, sponsor?: string, signer?: Signer}} params - `amount` of fee tokens to burn
98
- * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) for each oracle-listed asset
99
- */
100
- async subsidize({amount, sponsor, signer}) {
101
- const client = this.axis.contractClient(signer)
102
- return client.subsidize({sponsor: sponsor ?? client.publicKey, selling: this.base, buying: this.quote, amount})
103
- }
104
-
105
- /**
106
- * Orderbook depth data with given precision
107
- * @param {{base?: string, depth?: number, step?: string, limit?: number}} [params] - `base` is the base asset, `step` the price step (automatic by default)
108
- * @return {Promise<import('./api-client.js').OrderbookDepth>}
109
- */
110
- async getDepth({base = this.base, depth, step, limit} = {}) {
111
- return this.axis.api.getDepth({market: base + '/' + this.counter(base), depth, step, limit})
112
- }
113
-
114
- /**
115
- * Stream the orderbook depth
116
- * Returns a snapshot, then updates on book changes
117
- * @param {{base?: string, depth?: number, step?: string, limit?: number}} params
118
- * @param {function(OrderbookDepth): void} callback
119
- * @return {function(): void} - Unsubscribe function
120
- */
121
- subscribeDepth({base = this.base, depth, step, limit} = {}, callback) {
122
- const market = base + '/' + this.counter(base)
123
- return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {
124
- if (message.type === 'depth') {
125
- callback(message.data)
126
- }
127
- })
128
- }
129
-
130
- /**
131
- * Stream the market trades
132
- * Returns a snapshot, then updates on trades
133
- * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot
134
- * @return {function(): void} - Unsubscribe function
135
- */
136
- subscribeTrades(callback) {
137
- return this.axis.stream.subscribe('trades', {market: this.key}, message => {
138
- if (message.type === 'trades') {
139
- callback(message.trades, true)
140
- } else if (message.type === 'trade') {
141
- callback([message.trade], false)
142
- }
143
- })
144
- }
145
-
146
- /**
147
- * Stream the market candles
148
- * Returns a snapshot, then updates on trades
149
- * @param {{base?: string, resolution: number|string, limit?: number}} params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)
150
- * @param {function(Candle[], boolean): void} callback - Candles
151
- * @return {function(): void} - Unsubscribe function
152
- */
153
- subscribeCandles({base = this.base, resolution, limit}, callback) {
154
- const market = base + '/' + this.counter(base)
155
- return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {
156
- if (message.type === 'candles') {
157
- callback(message.candles, true)
158
- } else if (message.type === 'candle') {
159
- callback([message.candle], false)
160
- }
161
- })
162
- }
163
-
164
- /**
165
- * Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs
166
- * @return {TickerEntry|undefined}
167
- */
168
- get ticker() {
169
- return this.axis.tickers.get(this.key)
170
- }
171
-
172
- toJSON() {
173
- return {base: this.base, quote: this.quote, key: this.key, created: this.created, refreshed: this.refreshed}
174
- }
175
- }
176
-
177
- /**
178
- * @typedef {{}} Signer - Account signing contract calls
179
- * @property {string} publicKey - Transaction source account
180
- * @property {SignTransactionCallback} signTransaction
181
- */
1
+ import {canonicalPair} from './asset-pair.js'
2
+ import {parseApiDate} from './api-dates.js'
3
+
4
+ /**
5
+ * DEX Market
6
+ */
7
+ export class AxisMarket {
8
+ /**
9
+ * @param {Axis} axis
10
+ * @param {{base: string, quote: string, created?: string, refreshed?: string}} record - Market data
11
+ */
12
+ constructor(axis, record) {
13
+ this.axis = axis
14
+ const [base, quote] = canonicalPair(record.base, record.quote)
15
+ this.base = base
16
+ this.quote = quote
17
+ this.key = base + '/' + quote
18
+ this.update(record)
19
+ }
20
+
21
+ /**
22
+ * Base asset, the first of the pair in the contract canonical order
23
+ * @type {string}
24
+ * @readonly
25
+ */
26
+ base
27
+ /**
28
+ * Quote asset, the second of the pair in the contract canonical order
29
+ * @type {string}
30
+ * @readonly
31
+ */
32
+ quote
33
+ /**
34
+ * Canonical market key `base/quote`
35
+ * @type {string}
36
+ * @readonly
37
+ */
38
+ key
39
+ /**
40
+ * Creation timestamp (first oracle check) (UNIX milliseconds)
41
+ * @type {number}
42
+ */
43
+ created = 0
44
+ /**
45
+ * Last oracle check (UNIX milliseconds)
46
+ * @type {number}
47
+ */
48
+ refreshed = 0
49
+
50
+ /**
51
+ * Check whether the asset is one of the market assets
52
+ * @param {string} asset
53
+ * @return {boolean}
54
+ */
55
+ has(asset) {
56
+ return asset === this.base || asset === this.quote
57
+ }
58
+
59
+ /**
60
+ * The other market asset
61
+ * @param {string} asset - One of the market assets
62
+ * @return {string}
63
+ */
64
+ counter(asset) {
65
+ if (asset === this.base)
66
+ return this.quote
67
+ if (asset === this.quote)
68
+ return this.base
69
+ throw new Error(`Asset ${asset} does not belong to the market ${this.key}`)
70
+ }
71
+
72
+ /**
73
+ * Apply the contract state change record
74
+ * @param {{created?: string, refreshed?: string}} record
75
+ * @internal
76
+ */
77
+ update(record) {
78
+ if (record.created) {
79
+ this.created = parseApiDate(record.created)
80
+ }
81
+ if (record.refreshed) {
82
+ this.refreshed = parseApiDate(record.refreshed)
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Re-check both market assets against the price oracle and cache oracle prices
88
+ * @param {Signer} [signer] - Transaction source, the {@link Axis} signer by default
89
+ * @return {Promise<Market|undefined>}
90
+ */
91
+ async requote(signer) {
92
+ const client = await this.axis.contractClient(signer)
93
+ return client.requote(this.base, this.quote)
94
+ }
95
+
96
+ /**
97
+ * Extend oracle price feeds access for the market
98
+ * @param {{amount: bigint, sponsor?: string, signer?: Signer}} params - `amount` of fee tokens to burn
99
+ * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) for each oracle-listed asset
100
+ */
101
+ async subsidize({amount, sponsor, signer}) {
102
+ const client = await this.axis.contractClient(signer)
103
+ return client.subsidize({sponsor: sponsor ?? client.publicKey, selling: this.base, buying: this.quote, amount})
104
+ }
105
+
106
+ /**
107
+ * Orderbook depth data with given precision
108
+ * @param {{base?: string, depth?: number, step?: string, limit?: number}} [params] - `base` is the base asset, `step` the price step (automatic by default)
109
+ * @return {Promise<import('./api-client.js').OrderbookDepth>}
110
+ */
111
+ async getDepth({base = this.base, depth, step, limit} = {}) {
112
+ return this.axis.api.getDepth({market: base + '/' + this.counter(base), depth, step, limit})
113
+ }
114
+
115
+ /**
116
+ * Stream the orderbook depth
117
+ * Returns a snapshot, then updates on book changes
118
+ * @param {{base?: string, depth?: number, step?: string, limit?: number}} params
119
+ * @param {function(OrderbookDepth): void} callback
120
+ * @return {function(): void} - Unsubscribe function
121
+ */
122
+ subscribeDepth({base = this.base, depth, step, limit} = {}, callback) {
123
+ const market = base + '/' + this.counter(base)
124
+ return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {
125
+ if (message.type === 'depth') {
126
+ callback(message.data)
127
+ }
128
+ })
129
+ }
130
+
131
+ /**
132
+ * Stream the market trades
133
+ * Returns a snapshot, then updates on trades
134
+ * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot
135
+ * @return {function(): void} - Unsubscribe function
136
+ */
137
+ subscribeTrades(callback) {
138
+ return this.axis.stream.subscribe('trades', {market: this.key}, message => {
139
+ if (message.type === 'trades') {
140
+ callback(message.trades, true)
141
+ } else if (message.type === 'trade') {
142
+ callback([message.trade], false)
143
+ }
144
+ })
145
+ }
146
+
147
+ /**
148
+ * Stream the market candles
149
+ * Returns a snapshot, then updates on trades
150
+ * @param {{base?: string, resolution: number|string, limit?: number}} params - `base` is the base asset of the view, `resolution` in seconds or an alias (`5m`, `1h`, …), `limit` the candles in the snapshot (200 by default, at most 200)
151
+ * @param {function(Candle[], boolean): void} callback - Candles
152
+ * @return {function(): void} - Unsubscribe function
153
+ */
154
+ subscribeCandles({base = this.base, resolution, limit}, callback) {
155
+ const market = base + '/' + this.counter(base)
156
+ return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {
157
+ if (message.type === 'candles') {
158
+ callback(message.candles, true)
159
+ } else if (message.type === 'candle') {
160
+ callback([message.candle], false)
161
+ }
162
+ })
163
+ }
164
+
165
+ /**
166
+ * Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs
167
+ * @return {TickerEntry|undefined}
168
+ */
169
+ get ticker() {
170
+ return this.axis.tickers.get(this.key)
171
+ }
172
+
173
+ toJSON() {
174
+ return {base: this.base, quote: this.quote, key: this.key, created: this.created, refreshed: this.refreshed}
175
+ }
176
+ }
177
+
178
+ /**
179
+ * @typedef {{}} Signer - Account signing contract calls
180
+ * @property {string} publicKey - Transaction source account
181
+ * @property {SignTransactionCallback} signTransaction
182
+ */