@axis-markets/client 0.8.0 → 0.8.2

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,409 +1,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
- 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
- */
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
+ */