@axis-markets/client 0.5.0 → 0.8.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,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
+ 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
+ */
package/src/axis.js ADDED
@@ -0,0 +1,409 @@
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
+ * AXIS REST API client
56
+ * @type {AxisApiClient}
57
+ * @readonly
58
+ */
59
+ api
60
+ /**
61
+ * AXIS API WebSocket 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 AXIS API 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 with an `ExtendFootprintTTL` operation, restoring them first if archived
264
+ * @param {{days?: number, signer?: Signer}} [params] - Lifetime in days (30 by default) and the transaction source
265
+ * (the default signer by default)
266
+ * @return {Promise<number>} - Ledger sequence both entries live until, at least
267
+ */
268
+ async keepalive({days, signer} = {}) {
269
+ return this.contractClient(signer).keepalive(days)
270
+ }
271
+
272
+ /**
273
+ * Stop following the contract state and tracked accounts
274
+ */
275
+ close() {
276
+ this.stopFallback()
277
+ this.unsubscribeContract?.()
278
+ for (const account of [...this.accounts.values()]) {
279
+ account.close()
280
+ }
281
+ this.stream.close()
282
+ this.connecting = undefined
283
+ }
284
+
285
+ /**
286
+ * Contract client signing with the given account
287
+ * @param {Signer} [signer] - The default signer if omitted
288
+ * @return {AxisContractClient}
289
+ * @internal
290
+ */
291
+ contractClient(signer = this.signer) {
292
+ if (!signer?.publicKey || !signer.signTransaction)
293
+ throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')
294
+ if (!this.rpcUrl)
295
+ throw new Error('The `rpcUrl` option is required to submit transactions')
296
+ const cached = this.clients.get(signer.publicKey)
297
+ if (cached && cached.signTransaction === signer.signTransaction)
298
+ return cached.client
299
+ const client = new AxisContractClient({
300
+ publicKey: signer.publicKey,
301
+ signTransaction: signer.signTransaction,
302
+ rpcUrl: this.rpcUrl,
303
+ contractId: this.contractId,
304
+ networkPassphrase: this.networkPassphrase,
305
+ fee: this.fee
306
+ })
307
+ this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})
308
+ return client
309
+ }
310
+
311
+ /**
312
+ * @param {AxisAccount} account
313
+ * @internal
314
+ */
315
+ releaseAccount(account) {
316
+ if (this.accounts.get(account.address) === account) {
317
+ this.accounts.delete(account.address)
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Apply a contract state snapshot
323
+ * @param {ContractInfo} data
324
+ * @private
325
+ */
326
+ applyContractSnapshot(data) {
327
+ this.loadedAt = Date.now()
328
+ const frozen = data.frozen === true
329
+ if (frozen !== this.frozen) {
330
+ this.frozen = frozen
331
+ this.emit('frozen', frozen)
332
+ }
333
+ if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {
334
+ this.config = data.config
335
+ this.emit('config', data.config)
336
+ }
337
+ for (const record of data.markets || []) {
338
+ const key = pairKey(record.base, record.quote)
339
+ const market = this.markets.get(key)
340
+ if (!market) {
341
+ const created = new AxisMarket(this, record)
342
+ this.markets.set(key, created)
343
+ this.emit('market', {market: created, created: true})
344
+ } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {
345
+ market.update(record)
346
+ this.emit('market', {market, created: false})
347
+ }
348
+ }
349
+ this.emit('change')
350
+ }
351
+
352
+ /**
353
+ * @param {number} ledger
354
+ * @private
355
+ */
356
+ applyLedger(ledger) {
357
+ this.ledgerTime = Date.now()
358
+ if (ledger > this.ledger) {
359
+ this.ledger = ledger
360
+ this.emit('ledger', ledger)
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Poll the contract state over REST while the push connection is down
366
+ * @private
367
+ */
368
+ startFallback() {
369
+ if (this.fallbackTimer || !this.connecting)
370
+ return
371
+ this.fallbackTimer = setInterval(() => {
372
+ this.api.getContract()
373
+ .then(data => this.applyContractSnapshot(data))
374
+ .catch(() => {
375
+ //retried on the next tick
376
+ })
377
+ }, this.fallbackPollInterval)
378
+ }
379
+
380
+ /**
381
+ * @private
382
+ */
383
+ stopFallback() {
384
+ clearInterval(this.fallbackTimer)
385
+ this.fallbackTimer = undefined
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Derive the push API endpoint from the REST API URL
391
+ * @param {string} apiUrl
392
+ * @return {string}
393
+ */
394
+ export function toWsUrl(apiUrl) {
395
+ return apiUrl.replace(/^http/i, 'ws').replace(/\/+$/, '') + '/ws'
396
+ }
397
+
398
+ /**
399
+ * @typedef {{}} AxisOptions
400
+ * @property {string} apiUrl - AXIS REST API URL
401
+ * @property {string} contractId - AXIS contract address
402
+ * @property {string} [wsUrl] - AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)
403
+ * @property {string} [rpcUrl] - Stellar RPC URL
404
+ * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)
405
+ * @property {string} [fee] - Transaction fee
406
+ * @property {Signer} [signer] - Default signer settings for contract operations
407
+ * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds
408
+ * @property {typeof WebSocket} [WebSocket] - WebSocket implementation
409
+ */
@@ -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
+ }