@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,47 @@
1
+ import {xdr, Address, hash} from '@stellar/stellar-sdk'
2
+
3
+ const U64_MAX = (1n << 64n) - 1n
4
+
5
+ /**
6
+ * Compute the id of the order `owner` creates with `nonce`.
7
+ * Mirrors the contract: the first 16 bytes of `sha256(xdr(ScVec[owner: Address, nonce: u64]))`
8
+ * interpreted as a big-endian `u128` (the full 128 bits, no mask).
9
+ * @param {string} owner - Order owner address (account or contract)
10
+ * @param {bigint|number|string} nonce - Client-chosen u64 nonce
11
+ * @return {bigint} - u128 order id
12
+ */
13
+ export function orderId(owner, nonce) {
14
+ nonce = BigInt(nonce)
15
+ if (nonce < 0n || nonce > U64_MAX)
16
+ throw new RangeError('Nonce must fit u64')
17
+ const payload = xdr.ScVal.scvVec([
18
+ Address.fromString(owner).toScVal(),
19
+ xdr.ScVal.scvU64(nonce)
20
+ ]).toXDR()
21
+ const digest = hash(payload)
22
+ let id = 0n
23
+ for (let i = 0; i < 16; i++) {
24
+ id = (id << 8n) | BigInt(digest[i])
25
+ }
26
+ return id
27
+ }
28
+
29
+ /**
30
+ * Generate a u64 order nonce: wall clock (in milliseconds) shifted left by 22 bits plus 22 random bits.
31
+ * The clock part fits 42 bits until the year 2109, so the nonce never overflows u64; the random part makes
32
+ * collisions among the orders an account creates within the same millisecond negligible.
33
+ * Internal to the client - consumers never supply or observe nonces, `buy`/`sell` generate one per call.
34
+ * @return {bigint}
35
+ * @internal
36
+ */
37
+ export function generateNonce() {
38
+ return (BigInt(Date.now()) << 22n) | BigInt(randomBits22())
39
+ }
40
+
41
+ function randomBits22() {
42
+ const crypto = globalThis.crypto
43
+ if (crypto?.getRandomValues) {
44
+ return crypto.getRandomValues(new Uint32Array(1))[0] & 0x3fffff
45
+ }
46
+ return Math.floor(Math.random() * 0x400000)
47
+ }
@@ -0,0 +1,327 @@
1
+ import {Emitter} from './emitter.js'
2
+
3
+ /**
4
+ * WebSocket client of the Aggregator push API
5
+ *
6
+ * Emits `open`, `close` and `error` (server errors not tied to a subscription).
7
+ */
8
+ export class AxisStreamClient extends Emitter {
9
+ /**
10
+ * @param {string} url - WebSocket endpoint, e.g. `wss://api.axis.markets/ws`
11
+ * @param {StreamClientOptions} [options]
12
+ */
13
+ constructor(url, {WebSocket: WebSocketImpl, pingInterval = 20_000, minReconnectDelay = 1_000, maxReconnectDelay = 30_000} = {}) {
14
+ super()
15
+ if (!url || typeof url !== 'string')
16
+ throw new TypeError('WebSocket URL is required')
17
+ this.url = url
18
+ this.WebSocket = WebSocketImpl || globalThis.WebSocket
19
+ if (!this.WebSocket)
20
+ throw new Error('WebSocket is not available in this environment, pass the `WebSocket` option')
21
+ this.pingInterval = pingInterval
22
+ this.minReconnectDelay = minReconnectDelay
23
+ this.maxReconnectDelay = maxReconnectDelay
24
+ }
25
+
26
+ /**
27
+ * WebSocket endpoint
28
+ * @type {string}
29
+ * @readonly
30
+ */
31
+ url
32
+ /**
33
+ * Active subscriptions
34
+ * @type {Set<StreamSubscription>}
35
+ * @private
36
+ */
37
+ subscriptions = new Set()
38
+ /**
39
+ * Subscriptions by the server topic
40
+ * @type {Map<string, Set<StreamSubscription>>}
41
+ * @private
42
+ */
43
+ topics = new Map()
44
+ /**
45
+ * Subscriptions waiting for their snapshot, by request id
46
+ * @type {Map<number, StreamSubscription>}
47
+ * @private
48
+ */
49
+ requests = new Map()
50
+ /**
51
+ * @type {number}
52
+ * @private
53
+ */
54
+ nextId = 1
55
+ /**
56
+ * @type {WebSocket|undefined}
57
+ * @private
58
+ */
59
+ socket
60
+ /**
61
+ * @type {number}
62
+ * @private
63
+ */
64
+ failures = 0
65
+ /**
66
+ * @type {boolean}
67
+ * @private
68
+ */
69
+ closed = false
70
+
71
+ /**
72
+ * Whether the connection is open
73
+ * @return {boolean}
74
+ */
75
+ get connected() {
76
+ return !!this.socket && this.socket.readyState === 1
77
+ }
78
+
79
+ /**
80
+ * Subscribe to a channel; connects on the first subscription
81
+ * @param {'contract'|'ticker'|'account'|'trades'|'depth'|'candles'} channel
82
+ * @param {{address?: string, market?: string, depth?: number, step?: string, resolution?: number|string, limit?: number}} params -
83
+ * Channel parameters
84
+ * @param {function(StreamMessage): void} handler - Receives the snapshot (again after every reconnect), the
85
+ * changes, and `{type: 'error'}` if the server rejects the subscription
86
+ * @return {function(): void} - Unsubscribe function
87
+ */
88
+ subscribe(channel, params, handler) {
89
+ /** @type {StreamSubscription} */
90
+ const sub = {channel, params: params || {}, handler, topic: undefined}
91
+ this.subscriptions.add(sub)
92
+ this.closed = false
93
+ if (this.connected) {
94
+ this.sendSubscribe(sub)
95
+ } else {
96
+ this.connect()
97
+ }
98
+ return () => this.unsubscribe(sub)
99
+ }
100
+
101
+ /**
102
+ * Close the connection and drop every subscription
103
+ */
104
+ close() {
105
+ this.closed = true
106
+ this.subscriptions.clear()
107
+ this.topics.clear()
108
+ this.requests.clear()
109
+ clearTimeout(this.reconnectTimer)
110
+ this.stopPing()
111
+ if (this.socket) {
112
+ const socket = this.socket
113
+ this.socket = undefined
114
+ socket.close()
115
+ }
116
+ }
117
+
118
+ /**
119
+ * @param {StreamSubscription} sub
120
+ * @private
121
+ */
122
+ unsubscribe(sub) {
123
+ if (!this.subscriptions.delete(sub))
124
+ return
125
+ const {topic} = sub
126
+ if (topic) {
127
+ const subs = this.topics.get(topic)
128
+ subs?.delete(sub)
129
+ if (subs && !subs.size) {
130
+ this.topics.delete(topic)
131
+ if (this.connected && ![...this.subscriptions].some(s => s.topic === topic)) {
132
+ this.send({op: 'unsubscribe', channel: sub.channel, ...sub.params})
133
+ }
134
+ }
135
+ }
136
+ for (const [id, pending] of this.requests) {
137
+ if (pending === sub) {
138
+ this.requests.delete(id)
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * @private
145
+ */
146
+ connect() {
147
+ if (this.socket || this.closed)
148
+ return
149
+ clearTimeout(this.reconnectTimer)
150
+ let socket
151
+ try {
152
+ socket = new this.WebSocket(this.url)
153
+ } catch (e) {
154
+ this.scheduleReconnect()
155
+ return
156
+ }
157
+ this.socket = socket
158
+ socket.onopen = () => {
159
+ if (this.socket !== socket)
160
+ return
161
+ this.failures = 0
162
+ this.lastMessage = Date.now()
163
+ this.startPing()
164
+ for (const sub of this.subscriptions) {
165
+ this.sendSubscribe(sub)
166
+ }
167
+ this.emit('open')
168
+ }
169
+ socket.onmessage = e => {
170
+ if (this.socket !== socket)
171
+ return
172
+ this.lastMessage = Date.now()
173
+ let message
174
+ try {
175
+ message = JSON.parse(typeof e.data === 'string' ? e.data : e.data.toString())
176
+ } catch (err) {
177
+ return
178
+ }
179
+ this.route(message)
180
+ }
181
+ socket.onclose = () => {
182
+ if (this.socket !== socket)
183
+ return
184
+ this.socket = undefined
185
+ this.stopPing()
186
+ //topics are per connection
187
+ this.topics.clear()
188
+ this.requests.clear()
189
+ for (const sub of this.subscriptions) {
190
+ sub.topic = undefined
191
+ }
192
+ this.emit('close')
193
+ this.scheduleReconnect()
194
+ }
195
+ socket.onerror = () => {
196
+ //followed by close
197
+ }
198
+ }
199
+
200
+ /**
201
+ * @private
202
+ */
203
+ scheduleReconnect() {
204
+ if (this.closed || !this.subscriptions.size)
205
+ return
206
+ const delay = Math.min(this.maxReconnectDelay, this.minReconnectDelay * 2 ** this.failures)
207
+ this.failures++
208
+ this.reconnectTimer = setTimeout(() => this.connect(), delay)
209
+ }
210
+
211
+ /**
212
+ * @private
213
+ */
214
+ startPing() {
215
+ this.stopPing()
216
+ this.pingTimer = setInterval(() => {
217
+ //no traffic for two periods: the connection is dead even if it was not closed
218
+ if (Date.now() - this.lastMessage > this.pingInterval * 2) {
219
+ this.socket?.close()
220
+ return
221
+ }
222
+ this.send({op: 'ping'})
223
+ }, this.pingInterval)
224
+ }
225
+
226
+ /**
227
+ * @private
228
+ */
229
+ stopPing() {
230
+ clearInterval(this.pingTimer)
231
+ this.pingTimer = undefined
232
+ }
233
+
234
+ /**
235
+ * @param {StreamSubscription} sub
236
+ * @private
237
+ */
238
+ sendSubscribe(sub) {
239
+ const id = this.nextId++
240
+ this.requests.set(id, sub)
241
+ this.send({op: 'subscribe', id, channel: sub.channel, ...sub.params})
242
+ }
243
+
244
+ /**
245
+ * @param {{}} message
246
+ * @private
247
+ */
248
+ send(message) {
249
+ if (this.connected) {
250
+ this.socket.send(JSON.stringify(message))
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Deliver a server message to its subscriptions
256
+ * @param {StreamMessage} message
257
+ * @private
258
+ */
259
+ route(message) {
260
+ if (message.type === 'pong' || message.type === 'unsubscribed')
261
+ return
262
+ if (message.id !== undefined && this.requests.has(message.id)) {
263
+ //subscription response: snapshot (learn the topic) or rejection
264
+ const sub = this.requests.get(message.id)
265
+ this.requests.delete(message.id)
266
+ if (message.type === 'error') {
267
+ this.subscriptions.delete(sub)
268
+ return deliver(sub, message)
269
+ }
270
+ if (message.topic) {
271
+ sub.topic = message.topic
272
+ let subs = this.topics.get(message.topic)
273
+ if (!subs) {
274
+ subs = new Set()
275
+ this.topics.set(message.topic, subs)
276
+ }
277
+ subs.add(sub)
278
+ }
279
+ return deliver(sub, message)
280
+ }
281
+ if (message.topic) {
282
+ for (const sub of this.topics.get(message.topic) || []) {
283
+ deliver(sub, message)
284
+ }
285
+ return
286
+ }
287
+ if (message.type === 'error') {
288
+ this.emit('error', new Error(message.error))
289
+ }
290
+ }
291
+ }
292
+
293
+ /**
294
+ * @param {StreamSubscription} sub
295
+ * @param {StreamMessage} message
296
+ */
297
+ function deliver(sub, message) {
298
+ try {
299
+ sub.handler(message)
300
+ } catch (e) {
301
+ console.error(`Unhandled error in the "${sub.channel}" subscription handler`, e)
302
+ }
303
+ }
304
+
305
+ /**
306
+ * @typedef {{}} StreamClientOptions
307
+ * @property {typeof WebSocket} [WebSocket] - WebSocket implementation (the global one by default)
308
+ * @property {number} [pingInterval] - Application-level ping period, in milliseconds (20 s by default)
309
+ * @property {number} [minReconnectDelay] - First reconnect delay, doubled after each failure (1 s by default)
310
+ * @property {number} [maxReconnectDelay] - Reconnect delay cap (30 s by default)
311
+ */
312
+
313
+ /**
314
+ * @typedef {{}} StreamMessage - Server message; `type` names the payload, `topic` the subscription it belongs to
315
+ * @property {string} type
316
+ * @property {string} [topic]
317
+ * @property {number} [id]
318
+ */
319
+
320
+ /**
321
+ * @typedef {{}} StreamSubscription
322
+ * @property {string} channel
323
+ * @property {{}} params
324
+ * @property {function(StreamMessage): void} handler
325
+ * @property {string} [topic]
326
+ * @internal
327
+ */
@@ -0,0 +1,81 @@
1
+ import {Account, Address, Contract, Keypair, TransactionBuilder, scValToNative, rpc, xdr} from '@stellar/stellar-sdk'
2
+
3
+ /**
4
+ * Token state for allowance calculation, token balances, and current ledger
5
+ */
6
+ export class TokenBalance {
7
+ /**
8
+ * @param {{rpcUrl: string, networkPassphrase: string, spender: string, server?: rpc.Server}} options - `spender`
9
+ * is the AXIS contract
10
+ */
11
+ constructor({rpcUrl, networkPassphrase, spender, server}) {
12
+ this.server = server || new rpc.Server(rpcUrl, {allowHttp: rpcUrl.startsWith('http://')})
13
+ this.networkPassphrase = networkPassphrase
14
+ this.spender = spender
15
+ }
16
+
17
+ /**
18
+ * Allowance `owner` granted to the AXIS contract on a token, 0 when expired
19
+ * @param {string} token - Token contract address
20
+ * @param {string} owner - Token holder address
21
+ * @return {Promise<bigint>}
22
+ * @throws {Error} - If the simulation fails
23
+ */
24
+ async getAllowance(token, owner) {
25
+ const retval = await this.load(token, 'allowance', [new Address(owner).toScVal(), new Address(this.spender).toScVal()], owner)
26
+ return toBigInt(retval)
27
+ }
28
+
29
+ /**
30
+ * Token balance of an account
31
+ * @param {string} token - Token contract address
32
+ * @param {string} owner - Token holder address
33
+ * @return {Promise<bigint>} - 0 if the account holds no balance entry
34
+ */
35
+ async getBalance(token, owner) {
36
+ try {
37
+ return toBigInt(await this.load(token, 'balance', [new Address(owner).toScVal()], owner))
38
+ } catch (e) {
39
+ return 0n
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Latest closed ledger sequence
45
+ * @return {Promise<number>}
46
+ */
47
+ async getLatestLedger() {
48
+ const {sequence} = await this.server.getLatestLedger()
49
+ return sequence
50
+ }
51
+
52
+ /**
53
+ * @param {string} token
54
+ * @param {string} method
55
+ * @param {xdr.ScVal[]} args
56
+ * @param {string} source - Transaction source address
57
+ * @return {Promise<xdr.ScVal>}
58
+ * @private
59
+ */
60
+ async load(token, method, args, source) {
61
+ //a contract address cannot be a transaction source
62
+ const sourceAccount = source.startsWith('G') ? source : Keypair.random().publicKey()
63
+ const tx = new TransactionBuilder(new Account(sourceAccount, '0'), {fee: '100', networkPassphrase: this.networkPassphrase})
64
+ .addOperation(new Contract(token).call(method, ...args))
65
+ .setTimeout(30)
66
+ .build()
67
+ const sim = await this.server.simulateTransaction(tx)
68
+ if (rpc.Api.isSimulationError(sim))
69
+ throw new Error(`Token ${method} simulation failed for ${token}: ${sim.error}`)
70
+ return sim.result.retval
71
+ }
72
+ }
73
+
74
+ /**
75
+ * @param {xdr.ScVal} retval
76
+ * @return {bigint}
77
+ */
78
+ function toBigInt(retval) {
79
+ const value = scValToNative(retval)
80
+ return typeof value === 'bigint' ? value : BigInt(value ?? 0)
81
+ }