@axis-markets/client 0.8.2 → 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.
package/src/axis.js CHANGED
@@ -1,465 +1,470 @@
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
- this.api = new AxisApiClient(apiUrl)
33
- this.stream = new AxisStreamClient(wsUrl || toWsUrl(this.api.serverUrl), {WebSocket})
34
- this.rpcUrl = rpcUrl
35
- this.contractId = contractId
36
- this.networkPassphrase = networkPassphrase
37
- this.fee = fee
38
- this.signer = signer
39
- this.fallbackPollInterval = fallbackPollInterval
40
- this.tokenBalances = rpcUrl ? new TokenBalance({rpcUrl, networkPassphrase, spender: contractId}) : undefined
41
- this.nativeAsset = Asset.native().contractId(networkPassphrase)
42
- this.stream.on('open', () => {
43
- this.stopFallback()
44
- this.emit('connection', true)
45
- })
46
- this.stream.on('close', () => {
47
- this.startFallback()
48
- this.emit('connection', false)
49
- })
50
- }
51
-
52
- /**
53
- * AXIS REST API client
54
- * @type {AxisApiClient}
55
- * @readonly
56
- */
57
- api
58
- /**
59
- * AXIS contract address
60
- * @type {string|undefined}
61
- * @readonly
62
- */
63
- contractId
64
- /**
65
- * AXIS API WebSocket client
66
- * @type {AxisStreamClient}
67
- * @readonly
68
- */
69
- stream
70
- /**
71
- * Token balance wrappers
72
- * @type {TokenBalance}
73
- * @readonly
74
- */
75
- tokenBalances
76
- /**
77
- * Contract address of the native XLM token
78
- * @type {string}
79
- * @readonly
80
- */
81
- nativeAsset
82
- /**
83
- * Last known ledger
84
- * @type {number}
85
- */
86
- ledger = 0
87
- /**
88
- * Last updated UNIX milliseconds
89
- * @type {number}
90
- */
91
- ledgerTime = 0
92
- /**
93
- * Whether trading is suspended
94
- * @type {boolean}
95
- */
96
- frozen = false
97
- /**
98
- * Contract configuration
99
- * @type {ContractInfoConfig}
100
- */
101
- config
102
- /**
103
- * Available AXIS markets
104
- * @type {Map<string, AxisMarket>}
105
- * @readonly
106
- */
107
- markets = new Map()
108
- /**
109
- * 24h ticker entries
110
- * @type {Map<string, TickerEntry>}
111
- * @readonly
112
- */
113
- tickers = new Map() //TODO: move inside AxisMarket
114
- /**
115
- * Tracked accounts
116
- * @type {Map<string, AxisAccount>}
117
- * @private
118
- */
119
- accounts = new Map()
120
- /**
121
- * Contract clients by signer
122
- * @type {Map<string, {signTransaction: function, client: AxisContractClient}>}
123
- * @private
124
- */
125
- clients = new Map() //TODO: check if we can use a single AxisContractClient instance instead
126
- /**
127
- * @type {Promise<Axis>}
128
- * @private
129
- */
130
- connecting
131
-
132
- /**
133
- * Whether the contract state loaded
134
- * @return {boolean}
135
- */
136
- get loaded() {
137
- return !!this.loadedAt
138
- }
139
-
140
- /**
141
- * Load the contract state and track its changes
142
- * @return {Promise<Axis>}
143
- */
144
- connect() {
145
- if (!this.connecting) {
146
- this.connecting = new Promise((resolve, reject) => {
147
- //works with the push API, or the REST API if the push connection is not available
148
- let settled = false
149
- const done = () => {
150
- if (!settled) {
151
- settled = true
152
- resolve(this)
153
- }
154
- }
155
- const fail = e => {
156
- if (!settled) {
157
- settled = true
158
- this.connecting = undefined
159
- this.unsubscribeContract?.()
160
- reject(e)
161
- }
162
- }
163
- this.unsubscribeContract = this.stream.subscribe('contract', {}, message => {
164
- if (message.ledger) {
165
- this.applyLedger(message.ledger)
166
- }
167
- if (message.type === 'contract') {
168
- try {
169
- this.applyContractSnapshot(message.data)
170
- } catch (e) {
171
- return fail(e) //a snapshot of another contract is ignored after connecting
172
- }
173
- done()
174
- }
175
- })
176
- //do not wait for a push connection that may never open
177
- this.api.getContract()
178
- .then(data => {
179
- if (!this.loaded) {
180
- this.applyContractSnapshot(data)
181
- }
182
- done()
183
- }, e => {
184
- if (!settled && !this.stream.connected) {
185
- this.startFallback()
186
- fail(e)
187
- }
188
- })
189
- .catch(fail)
190
- })
191
- }
192
- return this.connecting
193
- }
194
-
195
- /**
196
- * AXIS contract address
197
- * @return {Promise<string>}
198
- */
199
- async getContractId() {
200
- if (!this.contractId) {
201
- await this.connect()
202
- }
203
- return this.contractId
204
- }
205
-
206
- /**
207
- * Current ledger sequence
208
- * @return {Promise<number>}
209
- */
210
- async getLedger() {
211
- if (this.ledger && this.stream.connected && Date.now() - this.ledgerTime < LEDGER_STALE_THRESHOLD)
212
- return this.ledger
213
- if (this.tokenBalances)
214
- return this.tokenBalances.getLatestLedger()
215
- if (this.ledger)
216
- return this.ledger
217
- throw new Error('The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option')
218
- }
219
-
220
- /**
221
- * Get market of the asset pair
222
- * @param {string} asset1 - Token contract address
223
- * @param {string} asset2 - Token contract address
224
- * @return {AxisMarket|undefined}
225
- */
226
- getMarket(asset1, asset2) {
227
- return this.markets.get(pairKey(asset1, asset2)) //TODO: accept also stellar classic asset format CODE:ISSUER and convert it to contract address automatically
228
- }
229
-
230
- /**
231
- * Get live order by id
232
- * @param {bigint|string} id - Order id
233
- * @return {Promise<AccountOrder|undefined>} - Undefined if not found (filled, removed, expired)
234
- */
235
- async getOrder(id) {
236
- const key = id.toString()
237
- for (const account of this.accounts.values()) {
238
- const order = account.orders.get(key)
239
- if (order)
240
- return order
241
- }
242
- try {
243
- return parseApiOrder(await this.api.getOrder(key))
244
- } catch (e) {
245
- if (e instanceof AxisApiError && e.status === 404)
246
- return undefined
247
- throw e
248
- }
249
- }
250
-
251
- /**
252
- * Trader wrapper tracking the orders and allowances for an account (one instance per account address)
253
- * @param {string} address - Trader address
254
- * @param {{signTransaction: [SignTransactionCallback]}} [options] - Transaction signing callback
255
- * @return {AxisAccount}
256
- */
257
- account(address, {signTransaction} = {}) {
258
- let account = this.accounts.get(address)
259
- if (!account) {
260
- account = new AxisAccount(this, address, {signTransaction})
261
- this.accounts.set(address, account)
262
- account.start()
263
- } else if (signTransaction) {
264
- account.signTransaction = signTransaction
265
- }
266
- return account
267
- }
268
-
269
- /**
270
- * Stream the 24h ticker of every market
271
- * Sends a full snapshot, then updates caused by trades
272
- * @param {function(Ticker24hResult): void} [callback]
273
- * @return {function(): void} - Unsubscribe function
274
- */
275
- subscribeTicker(callback) {
276
- return this.stream.subscribe('ticker', {}, message => {
277
- if (message.type !== 'ticker')
278
- return
279
- for (const entry of message.data.ticker) {
280
- this.tickers.set(entry.symbol, entry)
281
- }
282
- callback?.(message.data)
283
- })
284
- }
285
-
286
- /**
287
- * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring them first if archived
288
- * @param {{days?: number, signer?: Signer}} [params] - Lifetime in days (30 by default) and the transaction source
289
- * (the default signer by default)
290
- * @return {Promise<number>} - Ledger sequence both entries live until, at least
291
- */
292
- async keepalive({days, signer} = {}) {
293
- const client = await this.contractClient(signer)
294
- return client.keepalive(days)
295
- }
296
-
297
- /**
298
- * Stop following the contract state and tracked accounts
299
- */
300
- close() {
301
- this.stopFallback()
302
- this.unsubscribeContract?.()
303
- for (const account of [...this.accounts.values()]) {
304
- account.close()
305
- }
306
- this.stream.close()
307
- this.connecting = undefined
308
- }
309
-
310
- /**
311
- * Contract client signing with the given account
312
- * @param {Signer} [signer] - The default signer if omitted
313
- * @return {Promise<AxisContractClient>}
314
- * @internal
315
- */
316
- async contractClient(signer = this.signer) {
317
- if (!signer?.publicKey || !signer.signTransaction)
318
- throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')
319
- if (!this.rpcUrl)
320
- throw new Error('The `rpcUrl` option is required to submit transactions')
321
- await this.getContractId()
322
- const cached = this.clients.get(signer.publicKey)
323
- if (cached && cached.signTransaction === signer.signTransaction)
324
- return cached.client
325
- const client = new AxisContractClient({
326
- publicKey: signer.publicKey,
327
- signTransaction: signer.signTransaction,
328
- rpcUrl: this.rpcUrl,
329
- contractId: this.contractId,
330
- networkPassphrase: this.networkPassphrase,
331
- fee: this.fee
332
- })
333
- this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})
334
- return client
335
- }
336
-
337
- /**
338
- * @param {AxisAccount} account
339
- * @internal
340
- */
341
- releaseAccount(account) {
342
- if (this.accounts.get(account.address) === account) {
343
- this.accounts.delete(account.address)
344
- }
345
- }
346
-
347
- /**
348
- * Apply a contract state snapshot
349
- * @param {ContractInfo} data
350
- * @private
351
- */
352
- applyContractSnapshot(data) {
353
- this.checkContractAddress(data.address)
354
- this.loadedAt = Date.now()
355
- const frozen = data.frozen === true
356
- if (frozen !== this.frozen) {
357
- this.frozen = frozen
358
- this.emit('frozen', frozen)
359
- }
360
- if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {
361
- this.config = data.config
362
- this.emit('config', data.config)
363
- }
364
- for (const record of data.markets || []) {
365
- const key = pairKey(record.base, record.quote)
366
- const market = this.markets.get(key)
367
- if (!market) {
368
- const created = new AxisMarket(this, record)
369
- this.markets.set(key, created)
370
- this.emit('market', {market: created, created: true})
371
- } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {
372
- market.update(record)
373
- this.emit('market', {market, created: false})
374
- }
375
- }
376
- this.emit('change')
377
- }
378
-
379
- /**
380
- * Take the contract address reported by the AXIS API, or check it against the explicitly set
381
- * @param {string} [address]
382
- * @throws {Error} - If the API tracks another contract or the address is unknown
383
- * @private
384
- */
385
- checkContractAddress(address) {
386
- if (!address) {
387
- if (!this.contractId)
388
- throw new Error('The AXIS API does not report the contract address: set the `contractId` option')
389
- return
390
- }
391
- if (!this.contractId) {
392
- this.setContractId(address)
393
- } else if (address !== this.contractId)
394
- throw new Error(`The AXIS API tracks contract ${address}, not ${this.contractId}`)
395
- }
396
-
397
- /**
398
- * @param {string} contractId
399
- * @private
400
- */
401
- setContractId(contractId) {
402
- this.contractId = contractId
403
- if (this.tokenBalances) {
404
- this.tokenBalances.spender = contractId
405
- }
406
- }
407
-
408
- /**
409
- * @param {number} ledger
410
- * @private
411
- */
412
- applyLedger(ledger) {
413
- this.ledgerTime = Date.now()
414
- if (ledger > this.ledger) {
415
- this.ledger = ledger
416
- this.emit('ledger', ledger)
417
- }
418
- }
419
-
420
- /**
421
- * Poll the contract state over REST while the push connection is down
422
- * @private
423
- */
424
- startFallback() {
425
- if (this.fallbackTimer || !this.connecting)
426
- return
427
- this.fallbackTimer = setInterval(() => {
428
- this.api.getContract()
429
- .then(data => this.applyContractSnapshot(data))
430
- .catch(() => {
431
- //retried on the next tick
432
- })
433
- }, this.fallbackPollInterval)
434
- }
435
-
436
- /**
437
- * @private
438
- */
439
- stopFallback() {
440
- clearInterval(this.fallbackTimer)
441
- this.fallbackTimer = undefined
442
- }
443
- }
444
-
445
- /**
446
- * Derive the push API endpoint from the REST API URL
447
- * @param {string} apiUrl
448
- * @return {string}
449
- */
450
- export function toWsUrl(apiUrl) {
451
- return apiUrl.replace(/^http/i, 'ws').replace(/\/+$/, '') + '/ws'
452
- }
453
-
454
- /**
455
- * @typedef {{}} AxisOptions
456
- * @property {string} apiUrl - AXIS REST API URL
457
- * @property {string} [contractId] - AXIS contract address, by default pulled from the AXIS API
458
- * @property {string} [wsUrl] - AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)
459
- * @property {string} [rpcUrl] - Stellar RPC URL
460
- * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)
461
- * @property {string} [fee] - Transaction fee
462
- * @property {Signer} [signer] - Default signer settings for contract operations
463
- * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds
464
- * @property {typeof WebSocket} [WebSocket] - WebSocket implementation
465
- */
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
+ this.api = new AxisApiClient(apiUrl)
33
+ this.stream = new AxisStreamClient(wsUrl || toWsUrl(this.api.serverUrl), {WebSocket})
34
+ this.rpcUrl = rpcUrl
35
+ this.contractId = contractId
36
+ this.networkPassphrase = networkPassphrase
37
+ this.fee = fee
38
+ this.signer = signer
39
+ this.fallbackPollInterval = fallbackPollInterval
40
+ this.tokenBalances = rpcUrl ? new TokenBalance({rpcUrl, networkPassphrase, spender: contractId}) : undefined
41
+ this.nativeAsset = Asset.native().contractId(networkPassphrase)
42
+ this.stream.on('open', () => {
43
+ this.stopFallback()
44
+ this.emit('connection', true)
45
+ })
46
+ this.stream.on('close', () => {
47
+ this.startFallback()
48
+ this.emit('connection', false)
49
+ })
50
+ }
51
+
52
+ /**
53
+ * AXIS REST API client
54
+ * @type {AxisApiClient}
55
+ * @readonly
56
+ */
57
+ api
58
+ /**
59
+ * AXIS contract address
60
+ * @type {string|undefined}
61
+ * @readonly
62
+ */
63
+ contractId
64
+ /**
65
+ * AXIS API WebSocket client
66
+ * @type {AxisStreamClient}
67
+ * @readonly
68
+ */
69
+ stream
70
+ /**
71
+ * Token balance wrappers
72
+ * @type {TokenBalance}
73
+ * @readonly
74
+ */
75
+ tokenBalances
76
+ /**
77
+ * Contract address of the native XLM token
78
+ * @type {string}
79
+ * @readonly
80
+ */
81
+ nativeAsset
82
+ /**
83
+ * Last known ledger
84
+ * @type {number}
85
+ */
86
+ ledger = 0
87
+ /**
88
+ * Last updated UNIX milliseconds
89
+ * @type {number}
90
+ */
91
+ ledgerTime = 0
92
+ /**
93
+ * Whether trading is suspended
94
+ * @type {boolean}
95
+ */
96
+ frozen = false
97
+ /**
98
+ * Contract configuration
99
+ * @type {ContractInfoConfig}
100
+ */
101
+ config
102
+ /**
103
+ * Available AXIS markets
104
+ * @type {Map<string, AxisMarket>}
105
+ * @readonly
106
+ */
107
+ markets = new Map()
108
+ /**
109
+ * 24h ticker entries
110
+ * @type {Map<string, TickerEntry>}
111
+ * @readonly
112
+ */
113
+ tickers = new Map() //TODO: move inside AxisMarket
114
+ /**
115
+ * Tracked accounts
116
+ * @type {Map<string, AxisAccount>}
117
+ * @private
118
+ */
119
+ accounts = new Map()
120
+ /**
121
+ * Contract clients by signer
122
+ * @type {Map<string, {signTransaction: function, client: AxisContractClient}>}
123
+ * @private
124
+ */
125
+ clients = new Map() //TODO: check if we can use a single AxisContractClient instance instead
126
+ /**
127
+ * @type {Promise<Axis>}
128
+ * @private
129
+ */
130
+ connecting
131
+
132
+ /**
133
+ * Whether the contract state loaded
134
+ * @return {boolean}
135
+ */
136
+ get loaded() {
137
+ return !!this.loadedAt
138
+ }
139
+
140
+ /**
141
+ * Load the contract state and track its changes
142
+ * @return {Promise<Axis>}
143
+ */
144
+ connect() {
145
+ if (!this.connecting) {
146
+ this.connecting = new Promise((resolve, reject) => {
147
+ //works with the push API, or the REST API if the push connection is not available
148
+ let settled = false
149
+ const done = () => {
150
+ if (!settled) {
151
+ settled = true
152
+ resolve(this)
153
+ }
154
+ }
155
+ const fail = e => {
156
+ if (!settled) {
157
+ settled = true
158
+ this.connecting = undefined
159
+ this.unsubscribeContract?.()
160
+ reject(e)
161
+ }
162
+ }
163
+ this.unsubscribeContract = this.stream.subscribe('contract', {}, message => {
164
+ if (message.ledger) {
165
+ this.applyLedger(message.ledger)
166
+ }
167
+ if (message.type === 'contract') {
168
+ try {
169
+ this.applyContractSnapshot(message.data)
170
+ } catch (e) {
171
+ return fail(e) //a snapshot of another contract is ignored after connecting
172
+ }
173
+ done()
174
+ }
175
+ })
176
+ //do not wait for a push connection that may never open
177
+ this.api.getContract()
178
+ .then(data => {
179
+ if (!this.loaded) {
180
+ this.applyContractSnapshot(data)
181
+ }
182
+ done()
183
+ }, e => {
184
+ if (!settled && !this.stream.connected) {
185
+ this.startFallback()
186
+ fail(e)
187
+ }
188
+ })
189
+ .catch(fail)
190
+ })
191
+ }
192
+ return this.connecting
193
+ }
194
+
195
+ /**
196
+ * AXIS contract address
197
+ * @return {Promise<string>}
198
+ */
199
+ async getContractId() {
200
+ if (!this.contractId) {
201
+ await this.connect()
202
+ }
203
+ return this.contractId
204
+ }
205
+
206
+ /**
207
+ * Current ledger sequence
208
+ * @return {Promise<number>}
209
+ */
210
+ async getLedger() {
211
+ if (this.ledger && this.stream.connected && Date.now() - this.ledgerTime < LEDGER_STALE_THRESHOLD)
212
+ return this.ledger
213
+ if (this.tokenBalances)
214
+ return this.tokenBalances.getLatestLedger()
215
+ if (this.ledger)
216
+ return this.ledger
217
+ throw new Error('The current ledger is unknown: connect to the AXIS API or set the `rpcUrl` option')
218
+ }
219
+
220
+ /**
221
+ * Get market of the asset pair
222
+ * @param {string} asset1 - Token contract address
223
+ * @param {string} asset2 - Token contract address
224
+ * @return {AxisMarket|undefined}
225
+ */
226
+ getMarket(asset1, asset2) {
227
+ return this.markets.get(pairKey(asset1, asset2)) //TODO: accept also stellar classic asset format CODE:ISSUER and convert it to contract address automatically
228
+ }
229
+
230
+ /**
231
+ * Get live order by id
232
+ * @param {bigint|string} id - Order id
233
+ * @return {Promise<AccountOrder|undefined>} - Undefined if not found (filled, removed, expired)
234
+ */
235
+ async getOrder(id) {
236
+ const key = id.toString()
237
+ for (const account of this.accounts.values()) {
238
+ const order = account.orders.get(key)
239
+ if (order)
240
+ return order
241
+ }
242
+ try {
243
+ return parseApiOrder(await this.api.getOrder(key))
244
+ } catch (e) {
245
+ if (e instanceof AxisApiError && e.status === 404)
246
+ return undefined
247
+ throw e
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Trader wrapper tracking the orders and allowances for an account (one instance per account address)
253
+ * @param {string} address - Trader address
254
+ * @param {{signTransaction?: SignTransactionCallback, approvalTtl?: number}} [options] - Transaction signing callback and lifetime of the allowances granted by trading calls, in ledgers
255
+ * @return {AxisAccount}
256
+ */
257
+ account(address, {signTransaction, approvalTtl} = {}) {
258
+ let account = this.accounts.get(address)
259
+ if (!account) {
260
+ account = new AxisAccount(this, address, {signTransaction, approvalTtl})
261
+ this.accounts.set(address, account)
262
+ account.start()
263
+ } else {
264
+ if (signTransaction) {
265
+ account.signTransaction = signTransaction
266
+ }
267
+ if (approvalTtl) {
268
+ account.approvalTtl = approvalTtl
269
+ }
270
+ }
271
+ return account
272
+ }
273
+
274
+ /**
275
+ * Stream the 24h ticker of every market
276
+ * Sends a full snapshot, then updates caused by trades
277
+ * @param {function(Ticker24hResult): void} [callback]
278
+ * @return {function(): void} - Unsubscribe function
279
+ */
280
+ subscribeTicker(callback) {
281
+ return this.stream.subscribe('ticker', {}, message => {
282
+ if (message.type !== 'ticker')
283
+ return
284
+ for (const entry of message.data.ticker) {
285
+ this.tickers.set(entry.symbol, entry)
286
+ }
287
+ callback?.(message.data)
288
+ })
289
+ }
290
+
291
+ /**
292
+ * Extend the contract instance and code lifetime with an `ExtendFootprintTTL` operation, restoring them first if archived
293
+ * @param {{days?: number, signer?: Signer}} [params] - Lifetime in days (30 by default) and the transaction source
294
+ * (the default signer by default)
295
+ * @return {Promise<number>} - Ledger sequence both entries live until, at least
296
+ */
297
+ async keepalive({days, signer} = {}) {
298
+ const client = await this.contractClient(signer)
299
+ return client.keepalive(days)
300
+ }
301
+
302
+ /**
303
+ * Stop following the contract state and tracked accounts
304
+ */
305
+ close() {
306
+ this.stopFallback()
307
+ this.unsubscribeContract?.()
308
+ for (const account of [...this.accounts.values()]) {
309
+ account.close()
310
+ }
311
+ this.stream.close()
312
+ this.connecting = undefined
313
+ }
314
+
315
+ /**
316
+ * Contract client signing with the given account
317
+ * @param {Signer} [signer] - The default signer if omitted
318
+ * @return {Promise<AxisContractClient>}
319
+ * @internal
320
+ */
321
+ async contractClient(signer = this.signer) {
322
+ if (!signer?.publicKey || !signer.signTransaction)
323
+ throw new Error('A signer ({publicKey, signTransaction}) is required to submit transactions')
324
+ if (!this.rpcUrl)
325
+ throw new Error('The `rpcUrl` option is required to submit transactions')
326
+ await this.getContractId()
327
+ const cached = this.clients.get(signer.publicKey)
328
+ if (cached && cached.signTransaction === signer.signTransaction)
329
+ return cached.client
330
+ const client = new AxisContractClient({
331
+ publicKey: signer.publicKey,
332
+ signTransaction: signer.signTransaction,
333
+ rpcUrl: this.rpcUrl,
334
+ contractId: this.contractId,
335
+ networkPassphrase: this.networkPassphrase,
336
+ fee: this.fee
337
+ })
338
+ this.clients.set(signer.publicKey, {signTransaction: signer.signTransaction, client})
339
+ return client
340
+ }
341
+
342
+ /**
343
+ * @param {AxisAccount} account
344
+ * @internal
345
+ */
346
+ releaseAccount(account) {
347
+ if (this.accounts.get(account.address) === account) {
348
+ this.accounts.delete(account.address)
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Apply a contract state snapshot
354
+ * @param {ContractInfo} data
355
+ * @private
356
+ */
357
+ applyContractSnapshot(data) {
358
+ this.checkContractAddress(data.address)
359
+ this.loadedAt = Date.now()
360
+ const frozen = data.frozen === true
361
+ if (frozen !== this.frozen) {
362
+ this.frozen = frozen
363
+ this.emit('frozen', frozen)
364
+ }
365
+ if (data.config && JSON.stringify(data.config) !== JSON.stringify(this.config)) {
366
+ this.config = data.config
367
+ this.emit('config', data.config)
368
+ }
369
+ for (const record of data.markets || []) {
370
+ const key = pairKey(record.base, record.quote)
371
+ const market = this.markets.get(key)
372
+ if (!market) {
373
+ const created = new AxisMarket(this, record)
374
+ this.markets.set(key, created)
375
+ this.emit('market', {market: created, created: true})
376
+ } else if (record.refreshed && market.refreshed !== parseApiDate(record.refreshed)) {
377
+ market.update(record)
378
+ this.emit('market', {market, created: false})
379
+ }
380
+ }
381
+ this.emit('change')
382
+ }
383
+
384
+ /**
385
+ * Take the contract address reported by the AXIS API, or check it against the explicitly set
386
+ * @param {string} [address]
387
+ * @throws {Error} - If the API tracks another contract or the address is unknown
388
+ * @private
389
+ */
390
+ checkContractAddress(address) {
391
+ if (!address) {
392
+ if (!this.contractId)
393
+ throw new Error('The AXIS API does not report the contract address: set the `contractId` option')
394
+ return
395
+ }
396
+ if (!this.contractId) {
397
+ this.setContractId(address)
398
+ } else if (address !== this.contractId)
399
+ throw new Error(`The AXIS API tracks contract ${address}, not ${this.contractId}`)
400
+ }
401
+
402
+ /**
403
+ * @param {string} contractId
404
+ * @private
405
+ */
406
+ setContractId(contractId) {
407
+ this.contractId = contractId
408
+ if (this.tokenBalances) {
409
+ this.tokenBalances.spender = contractId
410
+ }
411
+ }
412
+
413
+ /**
414
+ * @param {number} ledger
415
+ * @private
416
+ */
417
+ applyLedger(ledger) {
418
+ this.ledgerTime = Date.now()
419
+ if (ledger > this.ledger) {
420
+ this.ledger = ledger
421
+ this.emit('ledger', ledger)
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Poll the contract state over REST while the push connection is down
427
+ * @private
428
+ */
429
+ startFallback() {
430
+ if (this.fallbackTimer || !this.connecting)
431
+ return
432
+ this.fallbackTimer = setInterval(() => {
433
+ this.api.getContract()
434
+ .then(data => this.applyContractSnapshot(data))
435
+ .catch(() => {
436
+ //retried on the next tick
437
+ })
438
+ }, this.fallbackPollInterval)
439
+ }
440
+
441
+ /**
442
+ * @private
443
+ */
444
+ stopFallback() {
445
+ clearInterval(this.fallbackTimer)
446
+ this.fallbackTimer = undefined
447
+ }
448
+ }
449
+
450
+ /**
451
+ * Derive the push API endpoint from the REST API URL
452
+ * @param {string} apiUrl
453
+ * @return {string}
454
+ */
455
+ export function toWsUrl(apiUrl) {
456
+ return apiUrl.replace(/^http/i, 'ws').replace(/\/+$/, '') + '/ws'
457
+ }
458
+
459
+ /**
460
+ * @typedef {{}} AxisOptions
461
+ * @property {string} apiUrl - AXIS REST API URL
462
+ * @property {string} [contractId] - AXIS contract address, by default pulled from the AXIS API
463
+ * @property {string} [wsUrl] - AXIS API push channel URL (`<apiUrl>/ws` with the `ws(s)` scheme by default)
464
+ * @property {string} [rpcUrl] - Stellar RPC URL
465
+ * @property {string} [networkPassphrase] - Network passphrase (Pubnet by default)
466
+ * @property {string} [fee] - Transaction fee
467
+ * @property {Signer} [signer] - Default signer settings for contract operations
468
+ * @property {number} [fallbackPollInterval] - REST polling period while the push connection is down, in milliseconds
469
+ * @property {typeof WebSocket} [WebSocket] - WebSocket implementation
470
+ */