@axis-markets/client 0.4.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,197 @@
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 {{a: string, b: string, created?: string, refreshed?: string}} record - Market data
11
+ */
12
+ constructor(axis, record) {
13
+ this.axis = axis
14
+ const [a, b] = canonicalPair(record.a, record.b)
15
+ this.a = a
16
+ this.b = b
17
+ this.key = a + '/' + b
18
+ this.update(record)
19
+ }
20
+
21
+ /**
22
+ * Base asset
23
+ * @type {string}
24
+ * @readonly
25
+ */
26
+ a
27
+ /**
28
+ * Quote asset
29
+ * @type {string}
30
+ * @readonly
31
+ */
32
+ b
33
+ /**
34
+ * Canonical market key `a/b`
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
+ * Base asset
52
+ * @return {string}
53
+ */
54
+ get base() {
55
+ return this.a
56
+ }
57
+
58
+ /**
59
+ * Quote asset
60
+ * @return {string}
61
+ */
62
+ get quote() {
63
+ return this.b
64
+ }
65
+
66
+ /**
67
+ * Check whether the asset is one of the market assets
68
+ * @param {string} asset
69
+ * @return {boolean}
70
+ */
71
+ has(asset) {
72
+ return asset === this.a || asset === this.b
73
+ }
74
+
75
+ /**
76
+ * The other market asset
77
+ * @param {string} asset - One of the market assets
78
+ * @return {string}
79
+ */
80
+ counter(asset) {
81
+ if (asset === this.a)
82
+ return this.b
83
+ if (asset === this.b)
84
+ return this.a
85
+ throw new Error(`Asset ${asset} does not belong to the market ${this.key}`)
86
+ }
87
+
88
+ /**
89
+ * Apply the contract state change record
90
+ * @param {{created?: string, refreshed?: string}} record
91
+ * @internal
92
+ */
93
+ update(record) {
94
+ if (record.created) {
95
+ this.created = parseApiDate(record.created)
96
+ }
97
+ if (record.refreshed) {
98
+ this.refreshed = parseApiDate(record.refreshed)
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Re-check both market assets against the price oracle and cache oracle prices
104
+ * @param {Signer} [signer] - Transaction source, the {@link Axis} signer by default
105
+ * @return {Promise<Market|undefined>}
106
+ */
107
+ async requote(signer) {
108
+ return this.axis.contractClient(signer).requote(this.a, this.b)
109
+ }
110
+
111
+ /**
112
+ * Extend oracle price feeds access for the market
113
+ * @param {{amount: bigint, sponsor?: string, signer?: Signer}} params - `amount` of fee tokens to burn
114
+ * @return {Promise<bigint[]>} - New access expiration UNIX timestamps (in seconds) for each oracle-listed asset
115
+ */
116
+ async subsidize({amount, sponsor, signer}) {
117
+ const client = this.axis.contractClient(signer)
118
+ return client.subsidize({sponsor: sponsor ?? client.publicKey, selling: this.a, buying: this.b, amount})
119
+ }
120
+
121
+ /**
122
+ * Orderbook depth data with given precision
123
+ * @param {{base?: string, depth?: number, step?: string, limit?: number}} [params] - `base` is the base asset, `step` the price step (automatic by default)
124
+ * @return {Promise<import('./api-client.js').OrderbookDepth>}
125
+ */
126
+ async getDepth({base = this.a, depth, step, limit} = {}) {
127
+ return this.axis.api.getDepth({market: base + '/' + this.counter(base), depth, step, limit})
128
+ }
129
+
130
+ /**
131
+ * Stream the orderbook depth
132
+ * Returns a snapshot, then updates on book changes
133
+ * @param {{base?: string, depth?: number, step?: string, limit?: number}} params
134
+ * @param {function(OrderbookDepth): void} callback
135
+ * @return {function(): void} - Unsubscribe function
136
+ */
137
+ subscribeDepth({base = this.a, depth, step, limit} = {}, callback) {
138
+ const market = base + '/' + this.counter(base)
139
+ return this.axis.stream.subscribe('depth', {market, depth, step, limit}, message => {
140
+ if (message.type === 'depth') {
141
+ callback(message.data)
142
+ }
143
+ })
144
+ }
145
+
146
+ /**
147
+ * Stream the market trades
148
+ * Returns a snapshot, then updates on trades
149
+ * @param {function(ApiTrade[], boolean): void} callback - Trades and whether they are the snapshot
150
+ * @return {function(): void} - Unsubscribe function
151
+ */
152
+ subscribeTrades(callback) {
153
+ return this.axis.stream.subscribe('trades', {market: this.key}, message => {
154
+ if (message.type === 'trades') {
155
+ callback(message.trades, true)
156
+ } else if (message.type === 'trade') {
157
+ callback([message.trade], false)
158
+ }
159
+ })
160
+ }
161
+
162
+ /**
163
+ * Stream the market candles
164
+ * Returns a snapshot, then updates on trades
165
+ * @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)
166
+ * @param {function(Candle[], boolean): void} callback - Candles
167
+ * @return {function(): void} - Unsubscribe function
168
+ */
169
+ subscribeCandles({base = this.a, resolution, limit}, callback) {
170
+ const market = base + '/' + this.counter(base)
171
+ return this.axis.stream.subscribe('candles', {market, resolution, limit}, message => {
172
+ if (message.type === 'candles') {
173
+ callback(message.candles, true)
174
+ } else if (message.type === 'candle') {
175
+ callback([message.candle], false)
176
+ }
177
+ })
178
+ }
179
+
180
+ /**
181
+ * Last 24h ticker entry of the market, available while {@link Axis#subscribeTicker} runs
182
+ * @return {TickerEntry|undefined}
183
+ */
184
+ get ticker() {
185
+ return this.axis.tickers.get(this.key)
186
+ }
187
+
188
+ toJSON() {
189
+ return {a: this.a, b: this.b, key: this.key, created: this.created, refreshed: this.refreshed}
190
+ }
191
+ }
192
+
193
+ /**
194
+ * @typedef {{}} Signer - Account signing contract calls
195
+ * @property {string} publicKey - Transaction source account
196
+ * @property {SignTransactionCallback} signTransaction
197
+ */
package/src/axis.js ADDED
@@ -0,0 +1,408 @@
1
+ import {Asset, Networks} from '@stellar/stellar-sdk'
2
+ import {Emitter} from './emitter.js'
3
+ import {AxisApiClient, AxisApiError} from './api-client.js'
4
+ import {AxisStreamClient} from './stream-client.js'
5
+ import {TokenBalance} from './token-balance.js'
6
+ import {AxisMarket} from './axis-market.js'
7
+ import {AxisAccount, parseApiOrder} from './axis-account.js'
8
+ import {pairKey} from './asset-pair.js'
9
+ import {parseApiDate} from './api-dates.js'
10
+ import {AxisContractClient} from './index.js'
11
+
12
+ /** Max stale ledger threshold, in ms */
13
+ const LEDGER_STALE_THRESHOLD = 60_000
14
+
15
+ /**
16
+ * High-level AXIS DEX state
17
+ *
18
+ * Emits:
19
+ * - `change` - anything in the contract state changed
20
+ * - `frozen` `boolean` - the frozen state toggled
21
+ * - `config` {ContractInfoConfig} - contract configuration changed
22
+ * - `market` `{market: AxisMarket, created: boolean}` - a market was opened or updated
23
+ * - `connection` `boolean` - WebSocket push connection opened or dropped
24
+ * - `ledger` `number` - new ledger processed by the indexer
25
+ */
26
+ export class Axis extends Emitter {
27
+ /**
28
+ * @param {AxisOptions} options
29
+ */
30
+ constructor({apiUrl, wsUrl, rpcUrl, contractId, networkPassphrase = Networks.PUBLIC, fee, signer, WebSocket, fallbackPollInterval = 15_000}) {
31
+ super()
32
+ if (!contractId)
33
+ throw new TypeError('AXIS contract id is required')
34
+ this.api = new AxisApiClient(apiUrl)
35
+ this.stream = new AxisStreamClient(wsUrl || toWsUrl(this.api.serverUrl), {WebSocket})
36
+ this.rpcUrl = rpcUrl
37
+ this.contractId = contractId
38
+ this.networkPassphrase = networkPassphrase
39
+ this.fee = fee
40
+ this.signer = signer
41
+ this.fallbackPollInterval = fallbackPollInterval
42
+ this.tokenBalances = rpcUrl ? new TokenBalance({rpcUrl, networkPassphrase, spender: contractId}) : undefined
43
+ this.nativeAsset = Asset.native().contractId(networkPassphrase)
44
+ this.stream.on('open', () => {
45
+ this.stopFallback()
46
+ this.emit('connection', true)
47
+ })
48
+ this.stream.on('close', () => {
49
+ this.startFallback()
50
+ this.emit('connection', false)
51
+ })
52
+ }
53
+
54
+ /**
55
+ * Aggregator REST client
56
+ * @type {AxisApiClient}
57
+ * @readonly
58
+ */
59
+ api
60
+ /**
61
+ * Aggregator WebSocket API client
62
+ * @type {AxisStreamClient}
63
+ * @readonly
64
+ */
65
+ stream
66
+ /**
67
+ * Token balance wrappers
68
+ * @type {TokenBalance}
69
+ * @readonly
70
+ */
71
+ tokenBalances
72
+ /**
73
+ * Contract address of the native XLM token
74
+ * @type {string}
75
+ * @readonly
76
+ */
77
+ nativeAsset
78
+ /**
79
+ * Last known ledger
80
+ * @type {number}
81
+ */
82
+ ledger = 0
83
+ /**
84
+ * Last updated UNIX milliseconds
85
+ * @type {number}
86
+ */
87
+ ledgerTime = 0
88
+ /**
89
+ * Whether trading is suspended
90
+ * @type {boolean}
91
+ */
92
+ frozen = false
93
+ /**
94
+ * Contract configuration
95
+ * @type {ContractInfoConfig}
96
+ */
97
+ config
98
+ /**
99
+ * Available AXIS markets
100
+ * @type {Map<string, AxisMarket>}
101
+ * @readonly
102
+ */
103
+ markets = new Map()
104
+ /**
105
+ * 24h ticker entries
106
+ * @type {Map<string, TickerEntry>}
107
+ * @readonly
108
+ */
109
+ tickers = new Map() //TODO: move inside AxisMarket
110
+ /**
111
+ * Tracked accounts
112
+ * @type {Map<string, AxisAccount>}
113
+ * @private
114
+ */
115
+ accounts = new Map()
116
+ /**
117
+ * Contract clients by signer
118
+ * @type {Map<string, {signTransaction: function, client: AxisContractClient}>}
119
+ * @private
120
+ */
121
+ clients = new Map() //TODO: check if we can use a single AxisContractClient instance instead
122
+ /**
123
+ * @type {Promise<Axis>}
124
+ * @private
125
+ */
126
+ connecting
127
+
128
+ /**
129
+ * Whether the contract state loaded
130
+ * @return {boolean}
131
+ */
132
+ get loaded() {
133
+ return !!this.loadedAt
134
+ }
135
+
136
+ /**
137
+ * Load the contract state and track its changes
138
+ * @return {Promise<Axis>}
139
+ */
140
+ connect() {
141
+ if (!this.connecting) {
142
+ this.connecting = new Promise((resolve, reject) => {
143
+ //works with the push API, or the REST API if the push connection is not available
144
+ let settled = false
145
+ const done = () => {
146
+ if (!settled) {
147
+ settled = true
148
+ resolve(this)
149
+ }
150
+ }
151
+ this.unsubscribeContract = this.stream.subscribe('contract', {}, message => {
152
+ if (message.ledger) {
153
+ this.applyLedger(message.ledger)
154
+ }
155
+ if (message.type === 'contract') {
156
+ this.applyContractSnapshot(message.data)
157
+ done()
158
+ }
159
+ })
160
+ //do not wait for a push connection that may never open
161
+ this.api.getContract()
162
+ .then(data => {
163
+ if (!this.loaded) {
164
+ this.applyContractSnapshot(data)
165
+ }
166
+ done()
167
+ })
168
+ .catch(e => {
169
+ if (!settled && !this.stream.connected) {
170
+ this.startFallback()
171
+ settled = true
172
+ this.connecting = undefined
173
+ this.unsubscribeContract?.()
174
+ reject(e)
175
+ }
176
+ })
177
+ })
178
+ }
179
+ return this.connecting
180
+ }
181
+
182
+ /**
183
+ * Current ledger sequence
184
+ * @return {Promise<number>}
185
+ */
186
+ async getLedger() {
187
+ if (this.ledger && this.stream.connected && Date.now() - this.ledgerTime < LEDGER_STALE_THRESHOLD)
188
+ return this.ledger
189
+ if (this.tokenBalances)
190
+ return this.tokenBalances.getLatestLedger()
191
+ if (this.ledger)
192
+ return this.ledger
193
+ throw new Error('The current ledger is unknown: connect to the Aggregator or set the `rpcUrl` option')
194
+ }
195
+
196
+ /**
197
+ * Get market of the asset pair
198
+ * @param {string} asset1 - Token contract address
199
+ * @param {string} asset2 - Token contract address
200
+ * @return {AxisMarket|undefined}
201
+ */
202
+ getMarket(asset1, asset2) {
203
+ return this.markets.get(pairKey(asset1, asset2)) //TODO: accept also stellar classic asset format CODE:ISSUER and convert it to contract address automatically
204
+ }
205
+
206
+ /**
207
+ * Get live order by id
208
+ * @param {bigint|string} id - Order id
209
+ * @return {Promise<AccountOrder|undefined>} - Undefined if not found (filled, removed, expired)
210
+ */
211
+ async getOrder(id) {
212
+ const key = id.toString()
213
+ for (const account of this.accounts.values()) {
214
+ const order = account.orders.get(key)
215
+ if (order)
216
+ return order
217
+ }
218
+ try {
219
+ return parseApiOrder(await this.api.getOrder(key))
220
+ } catch (e) {
221
+ if (e instanceof AxisApiError && e.status === 404)
222
+ return undefined
223
+ throw e
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Trader wrapper tracking the orders and allowances for an account (one instance per account address)
229
+ * @param {string} address - Trader address
230
+ * @param {{signTransaction: [SignTransactionCallback]}} [options] - Transaction signing callback
231
+ * @return {AxisAccount}
232
+ */
233
+ account(address, {signTransaction} = {}) {
234
+ let account = this.accounts.get(address)
235
+ if (!account) {
236
+ account = new AxisAccount(this, address, {signTransaction})
237
+ this.accounts.set(address, account)
238
+ account.start()
239
+ } else if (signTransaction) {
240
+ account.signTransaction = signTransaction
241
+ }
242
+ return account
243
+ }
244
+
245
+ /**
246
+ * Stream the 24h ticker of every market
247
+ * Sends a full snapshot, then updates caused by trades
248
+ * @param {function(Ticker24hResult): void} [callback]
249
+ * @return {function(): void} - Unsubscribe function
250
+ */
251
+ subscribeTicker(callback) {
252
+ return this.stream.subscribe('ticker', {}, message => {
253
+ if (message.type !== 'ticker')
254
+ return
255
+ for (const entry of message.data.ticker) {
256
+ this.tickers.set(entry.symbol, entry)
257
+ }
258
+ callback?.(message.data)
259
+ })
260
+ }
261
+
262
+ /**
263
+ * Extend the contract instance and code lifetime
264
+ * @param {Signer} [signer] - Transaction source, the default signer by default
265
+ * @return {Promise<void>}
266
+ */
267
+ async keepalive(signer) {
268
+ return this.contractClient(signer).keepalive()
269
+ }
270
+
271
+ /**
272
+ * Stop following the contract state and tracked accounts
273
+ */
274
+ close() {
275
+ this.stopFallback()
276
+ this.unsubscribeContract?.()
277
+ for (const account of [...this.accounts.values()]) {
278
+ account.close()
279
+ }
280
+ this.stream.close()
281
+ this.connecting = undefined
282
+ }
283
+
284
+ /**
285
+ * Contract client signing with the given account
286
+ * @param {Signer} [signer] - The default signer if omitted
287
+ * @return {AxisContractClient}
288
+ * @internal
289
+ */
290
+ contractClient(signer = this.signer) {
291
+ if (!signer?.publicKey || !signer.signTransaction)
292
+ throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')
293
+ if (!this.rpcUrl)
294
+ throw new Error('The `rpcUrl` option is required to submit transactions')
295
+ const cached = this.clients.get(signer.publicKey)
296
+ if (cached && cached.signTransaction === signer.signTransaction)
297
+ return cached.client
298
+ const client = new AxisContractClient({
299
+ publicKey: signer.publicKey,
300
+ signTransaction: signer.signTransaction,
301
+ rpcUrl: this.rpcUrl,
302
+ contractId: this.contractId,
303
+ networkPassphrase: this.networkPassphrase,
304
+ fee: this.fee
305
+ })
306
+ this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})
307
+ return client
308
+ }
309
+
310
+ /**
311
+ * @param {AxisAccount} account
312
+ * @internal
313
+ */
314
+ releaseAccount(account) {
315
+ if (this.accounts.get(account.address) === account) {
316
+ this.accounts.delete(account.address)
317
+ }
318
+ }
319
+
320
+ /**
321
+ * Apply a contract state snapshot
322
+ * @param {ContractInfo} data
323
+ * @private
324
+ */
325
+ applyContractSnapshot(data) {
326
+ this.loadedAt = Date.now()
327
+ const frozen = data.frozen === true
328
+ if (frozen !== this.frozen) {
329
+ this.frozen = frozen
330
+ this.emit('frozen', frozen)
331
+ }
332
+ if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {
333
+ this.config = data.config
334
+ this.emit('config', data.config)
335
+ }
336
+ for (const record of data.markets || []) {
337
+ const key = pairKey(record.a, record.b)
338
+ const market = this.markets.get(key)
339
+ if (!market) {
340
+ const created = new AxisMarket(this, record)
341
+ this.markets.set(key, created)
342
+ this.emit('market', {market: created, created: true})
343
+ } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {
344
+ market.update(record)
345
+ this.emit('market', {market, created: false})
346
+ }
347
+ }
348
+ this.emit('change')
349
+ }
350
+
351
+ /**
352
+ * @param {number} ledger
353
+ * @private
354
+ */
355
+ applyLedger(ledger) {
356
+ this.ledgerTime = Date.now()
357
+ if (ledger > this.ledger) {
358
+ this.ledger = ledger
359
+ this.emit('ledger', ledger)
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Poll the contract state over REST while the push connection is down
365
+ * @private
366
+ */
367
+ startFallback() {
368
+ if (this.fallbackTimer || !this.connecting)
369
+ return
370
+ this.fallbackTimer = setInterval(() => {
371
+ this.api.getContract()
372
+ .then(data => this.applyContractSnapshot(data))
373
+ .catch(() => {
374
+ //retried on the next tick
375
+ })
376
+ }, this.fallbackPollInterval)
377
+ }
378
+
379
+ /**
380
+ * @private
381
+ */
382
+ stopFallback() {
383
+ clearInterval(this.fallbackTimer)
384
+ this.fallbackTimer = undefined
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Derive the push API endpoint from the REST API URL
390
+ * @param {string} apiUrl
391
+ * @return {string}
392
+ */
393
+ export function toWsUrl(apiUrl) {
394
+ return apiUrl.replace(/^http/i, 'ws').replace(/\/+$/, '') + '/ws'
395
+ }
396
+
397
+ /**
398
+ * @typedef {{}} AxisOptions
399
+ * @property {string} apiUrl - Aggregator REST API URL
400
+ * @property {string} contractId - AXIS contract address
401
+ * @property {string} [wsUrl] - Aggregator push API URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)
402
+ * @property {string} [rpcUrl] - Stellar RPC URL
403
+ * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)
404
+ * @property {string} [fee] - Transaction fee
405
+ * @property {Signer} [signer] - Default signer settings for contract operations
406
+ * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds
407
+ * @property {typeof WebSocket} [WebSocket] - WebSocket implementation
408
+ */
@@ -0,0 +1,15 @@
1
+ /** Trading order type */
2
+ export const OrderKind = {
3
+ /** Execute trade, create a limit order if not executed in full */
4
+ Limit: 1,
5
+ /** Execute trade without creating a limit order */
6
+ Fill: 2,
7
+ /** Execute trade, cancel if was not executed in full */
8
+ FillOrKill: 3
9
+ }
10
+
11
+ /** Trade direction instructions */
12
+ export const TradeDirection = {
13
+ Sell: 1,
14
+ Buy: 2
15
+ }