@xapy/orderbook 0.1.24 → 0.1.25
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/README.md +2 -0
- package/dist/exchanges/binance/index.d.cts +1 -1
- package/dist/exchanges/binance/index.d.ts +1 -1
- package/dist/exchanges/bingx/index.d.cts +1 -1
- package/dist/exchanges/bingx/index.d.ts +1 -1
- package/dist/exchanges/bitget/index.d.cts +1 -1
- package/dist/exchanges/bitget/index.d.ts +1 -1
- package/dist/exchanges/bybit/index.d.cts +1 -1
- package/dist/exchanges/bybit/index.d.ts +1 -1
- package/dist/exchanges/coinex/index.d.cts +1 -1
- package/dist/exchanges/coinex/index.d.ts +1 -1
- package/dist/exchanges/deribit/index.d.cts +1 -1
- package/dist/exchanges/deribit/index.d.ts +1 -1
- package/dist/exchanges/edgex/index.cjs +648 -0
- package/dist/exchanges/edgex/index.cjs.map +1 -0
- package/dist/exchanges/edgex/index.d.cts +62 -0
- package/dist/exchanges/edgex/index.d.ts +62 -0
- package/dist/exchanges/edgex/index.js +642 -0
- package/dist/exchanges/edgex/index.js.map +1 -0
- package/dist/exchanges/gate/index.d.cts +1 -1
- package/dist/exchanges/gate/index.d.ts +1 -1
- package/dist/exchanges/grvt/index.d.cts +1 -1
- package/dist/exchanges/grvt/index.d.ts +1 -1
- package/dist/exchanges/huobi/index.d.cts +1 -1
- package/dist/exchanges/huobi/index.d.ts +1 -1
- package/dist/exchanges/hyperliquid/index.d.cts +1 -1
- package/dist/exchanges/hyperliquid/index.d.ts +1 -1
- package/dist/exchanges/kucoin/index.d.cts +1 -1
- package/dist/exchanges/kucoin/index.d.ts +1 -1
- package/dist/exchanges/lighter/index.cjs +664 -0
- package/dist/exchanges/lighter/index.cjs.map +1 -0
- package/dist/exchanges/lighter/index.d.cts +58 -0
- package/dist/exchanges/lighter/index.d.ts +58 -0
- package/dist/exchanges/lighter/index.js +658 -0
- package/dist/exchanges/lighter/index.js.map +1 -0
- package/dist/exchanges/okx/index.d.cts +1 -1
- package/dist/exchanges/okx/index.d.ts +1 -1
- package/dist/index.cjs +511 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +510 -4
- package/dist/index.js.map +1 -1
- package/dist/{stream-Con47OAp.d.cts → stream-CrvepB6m.d.cts} +1 -1
- package/dist/{stream-Con47OAp.d.ts → stream-CrvepB6m.d.ts} +1 -1
- package/package.json +24 -2
|
@@ -0,0 +1,658 @@
|
|
|
1
|
+
// src/core/symbol.ts
|
|
2
|
+
function parseSymbol(symbol) {
|
|
3
|
+
const [pair, settle] = symbol.split(":");
|
|
4
|
+
const parts = (pair ?? "").split("/");
|
|
5
|
+
const base = parts[0]?.toUpperCase();
|
|
6
|
+
const quote = parts[1]?.toUpperCase();
|
|
7
|
+
if (!base || !quote) {
|
|
8
|
+
throw new Error(
|
|
9
|
+
`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
|
|
10
|
+
);
|
|
11
|
+
}
|
|
12
|
+
if (settle && settle.toUpperCase() !== quote) {
|
|
13
|
+
throw new Error(
|
|
14
|
+
`unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
|
|
15
|
+
);
|
|
16
|
+
}
|
|
17
|
+
return {
|
|
18
|
+
base,
|
|
19
|
+
quote,
|
|
20
|
+
market: settle ? "perpetual" : "spot",
|
|
21
|
+
pair: `${base}/${quote}`
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// src/transport/http.ts
|
|
26
|
+
async function httpJson(req) {
|
|
27
|
+
const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
|
|
30
|
+
try {
|
|
31
|
+
const res = await fetch(url, {
|
|
32
|
+
method: req.method ?? "GET",
|
|
33
|
+
headers: req.headers,
|
|
34
|
+
body: req.body,
|
|
35
|
+
signal: controller.signal
|
|
36
|
+
});
|
|
37
|
+
if (!res.ok) {
|
|
38
|
+
const text = await res.text().catch(() => "");
|
|
39
|
+
throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
|
|
40
|
+
}
|
|
41
|
+
return await res.json();
|
|
42
|
+
} finally {
|
|
43
|
+
clearTimeout(timer);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// src/core/errors.ts
|
|
48
|
+
var ExchangeError = class extends Error {
|
|
49
|
+
constructor(exchange, message, cause) {
|
|
50
|
+
super(
|
|
51
|
+
`[${exchange}] ${message}`,
|
|
52
|
+
cause === void 0 ? void 0 : { cause }
|
|
53
|
+
);
|
|
54
|
+
this.exchange = exchange;
|
|
55
|
+
this.name = "ExchangeError";
|
|
56
|
+
}
|
|
57
|
+
exchange;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
// src/exchanges/lighter/markets.ts
|
|
61
|
+
var LIGHTER_REST = "https://mainnet.zklighter.elliot.ai";
|
|
62
|
+
var cache = null;
|
|
63
|
+
var inflight = null;
|
|
64
|
+
var key = (name, market) => `${market}:${name.toUpperCase()}`;
|
|
65
|
+
async function fetchMarkets(opts) {
|
|
66
|
+
const res = await httpJson({
|
|
67
|
+
url: `${LIGHTER_REST}/api/v1/orderBooks`,
|
|
68
|
+
timeoutMs: opts.timeoutMs,
|
|
69
|
+
transformUrl: opts.transformUrl
|
|
70
|
+
});
|
|
71
|
+
const rows = res.order_books ?? [];
|
|
72
|
+
if (rows.length === 0) {
|
|
73
|
+
throw new ExchangeError(
|
|
74
|
+
"lighter",
|
|
75
|
+
res.message ? `${res.code}: ${res.message}` : "empty orderBooks response"
|
|
76
|
+
);
|
|
77
|
+
}
|
|
78
|
+
const map = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const row of rows) {
|
|
80
|
+
map.set(key(row.symbol, row.market_type === "spot" ? "spot" : "perpetual"), row);
|
|
81
|
+
}
|
|
82
|
+
return map;
|
|
83
|
+
}
|
|
84
|
+
function loadMarkets(opts) {
|
|
85
|
+
inflight ??= fetchMarkets(opts).then(
|
|
86
|
+
(m) => {
|
|
87
|
+
cache = m;
|
|
88
|
+
inflight = null;
|
|
89
|
+
return m;
|
|
90
|
+
},
|
|
91
|
+
(err) => {
|
|
92
|
+
inflight = null;
|
|
93
|
+
throw err;
|
|
94
|
+
}
|
|
95
|
+
);
|
|
96
|
+
return inflight;
|
|
97
|
+
}
|
|
98
|
+
async function resolveLighterMarket(name, market, opts) {
|
|
99
|
+
const k = key(name, market);
|
|
100
|
+
const hit = cache?.get(k);
|
|
101
|
+
const meta = hit ?? (await loadMarkets(opts)).get(k);
|
|
102
|
+
if (!meta) {
|
|
103
|
+
throw new ExchangeError(
|
|
104
|
+
"lighter",
|
|
105
|
+
`unknown ${market} market "${name}" \u2014 not listed on lighter`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
if (meta.status && meta.status !== "active") {
|
|
109
|
+
throw new ExchangeError(
|
|
110
|
+
"lighter",
|
|
111
|
+
`market "${name}" is ${meta.status} \u2014 no book is published for it`
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
return meta;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// src/exchanges/lighter/symbols.ts
|
|
118
|
+
function toLighterSymbol(symbol, market) {
|
|
119
|
+
const [base, quote] = symbol.split("/");
|
|
120
|
+
if (!base || !quote) {
|
|
121
|
+
throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
|
|
122
|
+
}
|
|
123
|
+
if (quote.toUpperCase() !== "USDC") {
|
|
124
|
+
throw new Error(`lighter only supports USDC-quoted pairs; got "${quote}"`);
|
|
125
|
+
}
|
|
126
|
+
return market === "perpetual" ? base.toUpperCase() : `${base.toUpperCase()}/${quote.toUpperCase()}`;
|
|
127
|
+
}
|
|
128
|
+
function fromLighterSymbol(name) {
|
|
129
|
+
return name.includes("/") ? name.toUpperCase() : `${name.toUpperCase()}/USDC`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/exchanges/lighter/rest.ts
|
|
133
|
+
var MAX_ORDERS = 250;
|
|
134
|
+
function usToMs(us) {
|
|
135
|
+
return Number.isFinite(us) && us > 0 ? Math.floor(us / 1e3) : Date.now();
|
|
136
|
+
}
|
|
137
|
+
function aggregate(orders, side, capped) {
|
|
138
|
+
const byPrice = /* @__PURE__ */ new Map();
|
|
139
|
+
for (const o of orders ?? []) {
|
|
140
|
+
const price = Number(o.price);
|
|
141
|
+
const size = Number(o.remaining_base_amount);
|
|
142
|
+
if (!Number.isFinite(price) || !Number.isFinite(size)) continue;
|
|
143
|
+
byPrice.set(price, (byPrice.get(price) ?? 0) + size);
|
|
144
|
+
}
|
|
145
|
+
const levels = [];
|
|
146
|
+
for (const [price, size] of byPrice) levels.push({ price, size });
|
|
147
|
+
levels.sort((a, b) => side === "bid" ? b.price - a.price : a.price - b.price);
|
|
148
|
+
if (capped) levels.pop();
|
|
149
|
+
return levels;
|
|
150
|
+
}
|
|
151
|
+
async function fetchLighterOrderbook(opts) {
|
|
152
|
+
const name = toLighterSymbol(opts.symbol, opts.market);
|
|
153
|
+
const meta = await resolveLighterMarket(name, opts.market, opts);
|
|
154
|
+
const res = await httpJson({
|
|
155
|
+
url: `${LIGHTER_REST}/api/v1/orderBookOrders?market_id=${meta.market_id}&limit=${MAX_ORDERS}`,
|
|
156
|
+
timeoutMs: opts.timeoutMs,
|
|
157
|
+
transformUrl: opts.transformUrl
|
|
158
|
+
});
|
|
159
|
+
if (!res.asks && !res.bids) {
|
|
160
|
+
throw new ExchangeError(
|
|
161
|
+
"lighter",
|
|
162
|
+
res.message ? `${res.code}: ${res.message}` : "empty orderbook response"
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
const depth = opts.depth ?? 50;
|
|
166
|
+
const bids = aggregate(res.bids, "bid", res.total_bids === MAX_ORDERS);
|
|
167
|
+
const asks = aggregate(res.asks, "ask", res.total_asks === MAX_ORDERS);
|
|
168
|
+
const timestamp = Date.now();
|
|
169
|
+
return {
|
|
170
|
+
exchange: "lighter",
|
|
171
|
+
symbol: fromLighterSymbol(name),
|
|
172
|
+
market: opts.market,
|
|
173
|
+
bids: bids.slice(0, depth),
|
|
174
|
+
asks: asks.slice(0, depth),
|
|
175
|
+
timestamp,
|
|
176
|
+
// The L3 endpoint publishes no sequence of its own — the WS `nonce` chain
|
|
177
|
+
// is where ordering is enforced.
|
|
178
|
+
sequence: timestamp
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/core/book-merger.ts
|
|
183
|
+
var BookMerger = class {
|
|
184
|
+
bids = /* @__PURE__ */ new Map();
|
|
185
|
+
// price -> size
|
|
186
|
+
asks = /* @__PURE__ */ new Map();
|
|
187
|
+
sequence = -1;
|
|
188
|
+
timestamp = 0;
|
|
189
|
+
hasSnapshot = false;
|
|
190
|
+
apply(event) {
|
|
191
|
+
if (event.kind === "snapshot") {
|
|
192
|
+
this.bids.clear();
|
|
193
|
+
this.asks.clear();
|
|
194
|
+
for (const { price, size } of event.bids) {
|
|
195
|
+
if (size > 0) this.bids.set(price, size);
|
|
196
|
+
}
|
|
197
|
+
for (const { price, size } of event.asks) {
|
|
198
|
+
if (size > 0) this.asks.set(price, size);
|
|
199
|
+
}
|
|
200
|
+
this.sequence = event.sequence;
|
|
201
|
+
this.timestamp = event.timestamp;
|
|
202
|
+
this.hasSnapshot = true;
|
|
203
|
+
return this.emit();
|
|
204
|
+
}
|
|
205
|
+
if (!this.hasSnapshot) {
|
|
206
|
+
return { ok: false, reason: "no-snapshot" };
|
|
207
|
+
}
|
|
208
|
+
if (event.sequence <= this.sequence) {
|
|
209
|
+
return this.emit();
|
|
210
|
+
}
|
|
211
|
+
if (event.prevSequence !== void 0) {
|
|
212
|
+
if (event.prevSequence !== this.sequence) {
|
|
213
|
+
return {
|
|
214
|
+
ok: false,
|
|
215
|
+
reason: "gap",
|
|
216
|
+
expected: this.sequence,
|
|
217
|
+
received: event.prevSequence
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
} else if (event.sequence !== this.sequence + 1) {
|
|
221
|
+
return {
|
|
222
|
+
ok: false,
|
|
223
|
+
reason: "gap",
|
|
224
|
+
expected: this.sequence + 1,
|
|
225
|
+
received: event.sequence
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
for (const { price, size } of event.bids) {
|
|
229
|
+
if (size === 0) this.bids.delete(price);
|
|
230
|
+
else this.bids.set(price, size);
|
|
231
|
+
}
|
|
232
|
+
for (const { price, size } of event.asks) {
|
|
233
|
+
if (size === 0) this.asks.delete(price);
|
|
234
|
+
else this.asks.set(price, size);
|
|
235
|
+
}
|
|
236
|
+
this.sequence = event.sequence;
|
|
237
|
+
this.timestamp = event.timestamp;
|
|
238
|
+
return this.emit();
|
|
239
|
+
}
|
|
240
|
+
reset() {
|
|
241
|
+
this.bids.clear();
|
|
242
|
+
this.asks.clear();
|
|
243
|
+
this.sequence = -1;
|
|
244
|
+
this.timestamp = 0;
|
|
245
|
+
this.hasSnapshot = false;
|
|
246
|
+
}
|
|
247
|
+
/** Returns true once the merger has a usable book. */
|
|
248
|
+
isReady() {
|
|
249
|
+
return this.hasSnapshot;
|
|
250
|
+
}
|
|
251
|
+
emit() {
|
|
252
|
+
const bids = [];
|
|
253
|
+
for (const [price, size] of this.bids) bids.push({ price, size });
|
|
254
|
+
bids.sort((a, b) => b.price - a.price);
|
|
255
|
+
const asks = [];
|
|
256
|
+
for (const [price, size] of this.asks) asks.push({ price, size });
|
|
257
|
+
asks.sort((a, b) => a.price - b.price);
|
|
258
|
+
return {
|
|
259
|
+
ok: true,
|
|
260
|
+
bids,
|
|
261
|
+
asks,
|
|
262
|
+
sequence: this.sequence,
|
|
263
|
+
timestamp: this.timestamp
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
// src/core/event-emitter.ts
|
|
269
|
+
var TypedEmitter = class {
|
|
270
|
+
listeners = /* @__PURE__ */ new Map();
|
|
271
|
+
on(event, fn) {
|
|
272
|
+
let set = this.listeners.get(event);
|
|
273
|
+
if (!set) {
|
|
274
|
+
set = /* @__PURE__ */ new Set();
|
|
275
|
+
this.listeners.set(event, set);
|
|
276
|
+
}
|
|
277
|
+
set.add(fn);
|
|
278
|
+
return this;
|
|
279
|
+
}
|
|
280
|
+
off(event, fn) {
|
|
281
|
+
this.listeners.get(event)?.delete(fn);
|
|
282
|
+
return this;
|
|
283
|
+
}
|
|
284
|
+
emit(event, ...args) {
|
|
285
|
+
const set = this.listeners.get(event);
|
|
286
|
+
if (!set || set.size === 0) return false;
|
|
287
|
+
for (const fn of set) fn(...args);
|
|
288
|
+
return true;
|
|
289
|
+
}
|
|
290
|
+
removeAllListeners() {
|
|
291
|
+
this.listeners.clear();
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
|
|
295
|
+
// src/core/stream.ts
|
|
296
|
+
var OrderbookStream = class extends TypedEmitter {
|
|
297
|
+
constructor(onClose) {
|
|
298
|
+
super();
|
|
299
|
+
this.onClose = onClose;
|
|
300
|
+
}
|
|
301
|
+
onClose;
|
|
302
|
+
closed = false;
|
|
303
|
+
close() {
|
|
304
|
+
if (this.closed) return;
|
|
305
|
+
this.closed = true;
|
|
306
|
+
this.onClose();
|
|
307
|
+
this.removeAllListeners();
|
|
308
|
+
}
|
|
309
|
+
/** Yields each maintained book as it becomes available. */
|
|
310
|
+
async *iter() {
|
|
311
|
+
const queue = [];
|
|
312
|
+
let resolveNext = null;
|
|
313
|
+
let pendingError = null;
|
|
314
|
+
let ended = false;
|
|
315
|
+
const onUpdate = (b) => {
|
|
316
|
+
queue.push(b);
|
|
317
|
+
resolveNext?.();
|
|
318
|
+
};
|
|
319
|
+
const onError = (e) => {
|
|
320
|
+
pendingError = e;
|
|
321
|
+
resolveNext?.();
|
|
322
|
+
};
|
|
323
|
+
const onClose = () => {
|
|
324
|
+
ended = true;
|
|
325
|
+
resolveNext?.();
|
|
326
|
+
};
|
|
327
|
+
this.on("update", onUpdate);
|
|
328
|
+
this.on("error", onError);
|
|
329
|
+
this.on("disconnected", onClose);
|
|
330
|
+
try {
|
|
331
|
+
while (true) {
|
|
332
|
+
if (pendingError) throw pendingError;
|
|
333
|
+
const next = queue.shift();
|
|
334
|
+
if (next) {
|
|
335
|
+
yield next;
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
if (ended || this.closed) return;
|
|
339
|
+
await new Promise((r) => {
|
|
340
|
+
resolveNext = r;
|
|
341
|
+
});
|
|
342
|
+
resolveNext = null;
|
|
343
|
+
}
|
|
344
|
+
} finally {
|
|
345
|
+
this.off("update", onUpdate);
|
|
346
|
+
this.off("error", onError);
|
|
347
|
+
this.off("disconnected", onClose);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
// src/core/reconnect.ts
|
|
353
|
+
var Backoff = class _Backoff {
|
|
354
|
+
attempt = 0;
|
|
355
|
+
opts;
|
|
356
|
+
constructor(opts) {
|
|
357
|
+
this.opts = opts;
|
|
358
|
+
}
|
|
359
|
+
static withDefaults(opts = {}) {
|
|
360
|
+
return new _Backoff({
|
|
361
|
+
initialMs: opts.initialMs ?? 500,
|
|
362
|
+
maxMs: opts.maxMs ?? 3e4,
|
|
363
|
+
factor: opts.factor ?? 2,
|
|
364
|
+
jitter: opts.jitter ?? 0.3,
|
|
365
|
+
maxAttempts: opts.maxAttempts ?? 0
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
next() {
|
|
369
|
+
if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
|
|
370
|
+
return null;
|
|
371
|
+
}
|
|
372
|
+
this.attempt += 1;
|
|
373
|
+
const base = Math.min(
|
|
374
|
+
this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
|
|
375
|
+
this.opts.maxMs
|
|
376
|
+
);
|
|
377
|
+
const jitterRange = base * this.opts.jitter;
|
|
378
|
+
const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
|
|
379
|
+
return { wait, attempt: this.attempt };
|
|
380
|
+
}
|
|
381
|
+
reset() {
|
|
382
|
+
this.attempt = 0;
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
|
|
386
|
+
|
|
387
|
+
// src/transport/ws.ts
|
|
388
|
+
function toError(value, fallback = "unknown error") {
|
|
389
|
+
if (value instanceof Error) {
|
|
390
|
+
return value.message ? value : new Error(`${value.name}: ${fallback}`);
|
|
391
|
+
}
|
|
392
|
+
if (typeof value === "string" && value) return new Error(value);
|
|
393
|
+
return new Error(fallback);
|
|
394
|
+
}
|
|
395
|
+
function normalizeWsError(ev) {
|
|
396
|
+
const detail = ev?.message || (ev?.error instanceof Error ? ev.error.message : void 0) || (typeof ev?.error === "string" ? ev.error : void 0);
|
|
397
|
+
return new Error(detail ? `WebSocket error: ${detail}` : "WebSocket error");
|
|
398
|
+
}
|
|
399
|
+
function describeClose(ev) {
|
|
400
|
+
if (ev?.reason) return ev.reason;
|
|
401
|
+
return ev?.code === void 0 ? "closed" : `closed (code ${ev.code})`;
|
|
402
|
+
}
|
|
403
|
+
var cachedCtor = null;
|
|
404
|
+
async function getWebSocketCtor() {
|
|
405
|
+
if (cachedCtor) return cachedCtor;
|
|
406
|
+
if (hasNativeWebSocket) {
|
|
407
|
+
cachedCtor = globalThis.WebSocket;
|
|
408
|
+
return cachedCtor;
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
const mod = await import('ws');
|
|
412
|
+
const ctor = mod.default ?? mod.WebSocket;
|
|
413
|
+
if (!ctor) throw new Error("missing default export");
|
|
414
|
+
cachedCtor = ctor;
|
|
415
|
+
return cachedCtor;
|
|
416
|
+
} catch (err) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
"WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
var WSClient = class extends TypedEmitter {
|
|
423
|
+
constructor(cfg) {
|
|
424
|
+
super();
|
|
425
|
+
this.cfg = cfg;
|
|
426
|
+
this.backoff = Backoff.withDefaults(cfg.reconnect);
|
|
427
|
+
}
|
|
428
|
+
cfg;
|
|
429
|
+
ws = null;
|
|
430
|
+
backoff;
|
|
431
|
+
closed = false;
|
|
432
|
+
pingTimer = null;
|
|
433
|
+
async connect() {
|
|
434
|
+
if (this.closed) return;
|
|
435
|
+
const WS = await getWebSocketCtor();
|
|
436
|
+
const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
|
|
437
|
+
const ws = new WS(url);
|
|
438
|
+
ws.binaryType = "arraybuffer";
|
|
439
|
+
this.ws = ws;
|
|
440
|
+
ws.onopen = async () => {
|
|
441
|
+
this.backoff.reset();
|
|
442
|
+
this.startPing();
|
|
443
|
+
this.emit("open");
|
|
444
|
+
try {
|
|
445
|
+
await this.cfg.onOpen?.({
|
|
446
|
+
send: (d) => ws.send(d),
|
|
447
|
+
close: () => this.close()
|
|
448
|
+
});
|
|
449
|
+
} catch (err) {
|
|
450
|
+
this.emit("error", toError(err, "onOpen handler failed"));
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
ws.onmessage = (e) => {
|
|
454
|
+
let result;
|
|
455
|
+
try {
|
|
456
|
+
result = this.cfg.onMessage(e.data);
|
|
457
|
+
} catch (err) {
|
|
458
|
+
this.emit("error", toError(err, "onMessage handler failed"));
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
if (result && typeof result.catch === "function") {
|
|
462
|
+
result.catch(
|
|
463
|
+
(err) => this.emit("error", toError(err, "onMessage handler failed"))
|
|
464
|
+
);
|
|
465
|
+
}
|
|
466
|
+
};
|
|
467
|
+
ws.onerror = (e) => {
|
|
468
|
+
this.emit("error", normalizeWsError(e));
|
|
469
|
+
};
|
|
470
|
+
ws.onclose = (e) => {
|
|
471
|
+
this.stopPing();
|
|
472
|
+
const reason = describeClose(e);
|
|
473
|
+
this.emit("close", reason);
|
|
474
|
+
if (!this.closed) this.scheduleReconnect();
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
send(data) {
|
|
478
|
+
this.ws?.send(data);
|
|
479
|
+
}
|
|
480
|
+
close() {
|
|
481
|
+
this.closed = true;
|
|
482
|
+
this.stopPing();
|
|
483
|
+
try {
|
|
484
|
+
this.ws?.close();
|
|
485
|
+
} catch {
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
startPing() {
|
|
489
|
+
if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
|
|
490
|
+
this.stopPing();
|
|
491
|
+
this.pingTimer = setInterval(() => {
|
|
492
|
+
try {
|
|
493
|
+
this.ws?.send(this.cfg.pingPayload());
|
|
494
|
+
} catch {
|
|
495
|
+
}
|
|
496
|
+
}, this.cfg.pingIntervalMs);
|
|
497
|
+
}
|
|
498
|
+
stopPing() {
|
|
499
|
+
if (this.pingTimer) {
|
|
500
|
+
clearInterval(this.pingTimer);
|
|
501
|
+
this.pingTimer = null;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
scheduleReconnect() {
|
|
505
|
+
const next = this.backoff.next();
|
|
506
|
+
if (!next) {
|
|
507
|
+
this.emit("error", new Error("max reconnect attempts exceeded"));
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
this.emit("reconnecting", next.attempt, next.wait);
|
|
511
|
+
setTimeout(() => {
|
|
512
|
+
this.connect().catch((e) => this.emit("error", toError(e, "reconnect failed")));
|
|
513
|
+
}, next.wait);
|
|
514
|
+
}
|
|
515
|
+
};
|
|
516
|
+
|
|
517
|
+
// src/exchanges/lighter/ws.ts
|
|
518
|
+
var WS_URL = "wss://mainnet.zklighter.elliot.ai/stream";
|
|
519
|
+
var PING_INTERVAL_MS = 6e4;
|
|
520
|
+
var toLevels = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
|
|
521
|
+
function streamLighterOrderbook(opts) {
|
|
522
|
+
const name = toLighterSymbol(opts.symbol, opts.market);
|
|
523
|
+
const symbol = fromLighterSymbol(name);
|
|
524
|
+
const marketId = resolveLighterMarket(name, opts.market, opts).then(
|
|
525
|
+
(m) => m.market_id
|
|
526
|
+
);
|
|
527
|
+
marketId.catch(() => {
|
|
528
|
+
});
|
|
529
|
+
const merger = new BookMerger();
|
|
530
|
+
let ws = null;
|
|
531
|
+
let sock = null;
|
|
532
|
+
let channel = null;
|
|
533
|
+
let recovering = false;
|
|
534
|
+
const stream = new OrderbookStream(() => ws?.close());
|
|
535
|
+
const send = (type) => {
|
|
536
|
+
if (channel) sock?.send(JSON.stringify({ type, channel }));
|
|
537
|
+
};
|
|
538
|
+
const emit = (r) => {
|
|
539
|
+
const book = {
|
|
540
|
+
exchange: "lighter",
|
|
541
|
+
symbol,
|
|
542
|
+
market: opts.market,
|
|
543
|
+
bids: r.bids,
|
|
544
|
+
asks: r.asks,
|
|
545
|
+
timestamp: r.timestamp,
|
|
546
|
+
sequence: r.sequence
|
|
547
|
+
};
|
|
548
|
+
stream.emit("update", book);
|
|
549
|
+
};
|
|
550
|
+
const resync = () => {
|
|
551
|
+
if (recovering) return;
|
|
552
|
+
recovering = true;
|
|
553
|
+
merger.reset();
|
|
554
|
+
send("unsubscribe");
|
|
555
|
+
send("subscribe");
|
|
556
|
+
};
|
|
557
|
+
const buildEvent = (msg, snapshot) => {
|
|
558
|
+
const ob = msg.order_book ?? {};
|
|
559
|
+
const bids = toLevels(ob.bids);
|
|
560
|
+
const asks = toLevels(ob.asks);
|
|
561
|
+
const timestamp = msg.timestamp ?? usToMs(ob.last_updated_at);
|
|
562
|
+
const sequence = Number(ob.nonce ?? 0);
|
|
563
|
+
return snapshot ? { kind: "snapshot", bids, asks, sequence, timestamp } : {
|
|
564
|
+
kind: "delta",
|
|
565
|
+
bids,
|
|
566
|
+
asks,
|
|
567
|
+
sequence,
|
|
568
|
+
prevSequence: Number(ob.begin_nonce ?? 0),
|
|
569
|
+
timestamp
|
|
570
|
+
};
|
|
571
|
+
};
|
|
572
|
+
const handleBook = (msg, snapshot) => {
|
|
573
|
+
if (snapshot) recovering = false;
|
|
574
|
+
else if (recovering) return;
|
|
575
|
+
const r = merger.apply(buildEvent(msg, snapshot));
|
|
576
|
+
if (r.ok) {
|
|
577
|
+
emit(r);
|
|
578
|
+
} else if (r.reason === "gap" || r.reason === "no-snapshot") {
|
|
579
|
+
resync();
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
const onMessage = (raw) => {
|
|
583
|
+
if (typeof raw !== "string") return;
|
|
584
|
+
let msg;
|
|
585
|
+
try {
|
|
586
|
+
msg = JSON.parse(raw);
|
|
587
|
+
} catch {
|
|
588
|
+
return;
|
|
589
|
+
}
|
|
590
|
+
if (msg.error) {
|
|
591
|
+
stream.emit(
|
|
592
|
+
"error",
|
|
593
|
+
new ExchangeError("lighter", `${msg.error.code}: ${msg.error.message}`)
|
|
594
|
+
);
|
|
595
|
+
return;
|
|
596
|
+
}
|
|
597
|
+
if (!msg.order_book) return;
|
|
598
|
+
if (msg.channel && channel && msg.channel !== channel.replace("/", ":")) {
|
|
599
|
+
return;
|
|
600
|
+
}
|
|
601
|
+
if (msg.type === "subscribed/order_book") handleBook(msg, true);
|
|
602
|
+
else if (msg.type === "update/order_book") handleBook(msg, false);
|
|
603
|
+
};
|
|
604
|
+
ws = new WSClient({
|
|
605
|
+
url: WS_URL,
|
|
606
|
+
onOpen: async (handle) => {
|
|
607
|
+
sock = handle;
|
|
608
|
+
merger.reset();
|
|
609
|
+
recovering = false;
|
|
610
|
+
channel = `order_book/${await marketId}`;
|
|
611
|
+
send("subscribe");
|
|
612
|
+
},
|
|
613
|
+
onMessage,
|
|
614
|
+
pingIntervalMs: PING_INTERVAL_MS,
|
|
615
|
+
pingPayload: () => JSON.stringify({ type: "ping" })
|
|
616
|
+
});
|
|
617
|
+
ws.on("open", () => stream.emit("connected"));
|
|
618
|
+
ws.on("close", (r) => stream.emit("disconnected", r));
|
|
619
|
+
ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
|
|
620
|
+
ws.on("error", (e) => stream.emit("error", e));
|
|
621
|
+
ws.connect().catch((e) => stream.emit("error", e));
|
|
622
|
+
return stream;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
// src/exchanges/lighter/index.ts
|
|
626
|
+
var LighterClient = class {
|
|
627
|
+
exchange = "lighter";
|
|
628
|
+
transformUrl;
|
|
629
|
+
timeoutMs;
|
|
630
|
+
constructor(opts = {}) {
|
|
631
|
+
this.transformUrl = opts.transformUrl;
|
|
632
|
+
this.timeoutMs = opts.timeoutMs;
|
|
633
|
+
}
|
|
634
|
+
fetchOrderbook(symbol, opts = {}) {
|
|
635
|
+
const { pair, market } = parseSymbol(symbol);
|
|
636
|
+
return fetchLighterOrderbook({
|
|
637
|
+
symbol: pair,
|
|
638
|
+
market,
|
|
639
|
+
depth: opts.depth,
|
|
640
|
+
timeoutMs: this.timeoutMs,
|
|
641
|
+
transformUrl: this.transformUrl
|
|
642
|
+
});
|
|
643
|
+
}
|
|
644
|
+
streamOrderbook(symbol, opts = {}) {
|
|
645
|
+
const { pair, market } = parseSymbol(symbol);
|
|
646
|
+
return streamLighterOrderbook({
|
|
647
|
+
symbol: pair,
|
|
648
|
+
market,
|
|
649
|
+
depth: opts.depth,
|
|
650
|
+
transformUrl: this.transformUrl,
|
|
651
|
+
timeoutMs: this.timeoutMs
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
};
|
|
655
|
+
|
|
656
|
+
export { LighterClient, fetchLighterOrderbook, fromLighterSymbol, streamLighterOrderbook, toLighterSymbol };
|
|
657
|
+
//# sourceMappingURL=index.js.map
|
|
658
|
+
//# sourceMappingURL=index.js.map
|