@alpha-arcade/sdk 0.3.1 → 0.3.5
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 +164 -2
- package/dist/index.cjs +332 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +181 -2
- package/dist/index.d.ts +181 -2
- package/dist/index.js +331 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
TypeScript SDK for trading on **Alpha Market** — Algorand prediction markets.
|
|
4
4
|
|
|
5
|
-
Place orders, manage positions, read orderbooks, and build automated trading bots
|
|
5
|
+
Place orders, manage positions, read orderbooks from the API or chain, and build automated trading bots.
|
|
6
6
|
|
|
7
7
|
## Installation
|
|
8
8
|
|
|
@@ -246,7 +246,7 @@ for (const pos of positions) {
|
|
|
246
246
|
|
|
247
247
|
#### `getOrderbook(marketAppId)`
|
|
248
248
|
|
|
249
|
-
Fetches the full on-chain orderbook.
|
|
249
|
+
Fetches the full on-chain orderbook for a single market app.
|
|
250
250
|
|
|
251
251
|
```typescript
|
|
252
252
|
const book = await client.getOrderbook(123456789);
|
|
@@ -263,6 +263,24 @@ if (book.yes.bids.length > 0) {
|
|
|
263
263
|
}
|
|
264
264
|
```
|
|
265
265
|
|
|
266
|
+
#### `getFullOrderbookFromApi(marketId)`
|
|
267
|
+
|
|
268
|
+
Fetches the full processed orderbook snapshot for a market from the Alpha REST API. Requires `apiKey`.
|
|
269
|
+
|
|
270
|
+
This returns the same shape as websocket `orderbook_changed.orderbook`: a record keyed by `marketAppId`, where each value includes:
|
|
271
|
+
- top-level aggregated `bids`, `asks`, and `spread`
|
|
272
|
+
- detailed `yes` and `no` bid/ask orders with `escrowAppId` and `owner`
|
|
273
|
+
|
|
274
|
+
```typescript
|
|
275
|
+
const snapshot = await client.getFullOrderbookFromApi('market-uuid-here');
|
|
276
|
+
|
|
277
|
+
for (const [appId, book] of Object.entries(snapshot)) {
|
|
278
|
+
console.log(`App ${appId}: spread=${book.spread}`);
|
|
279
|
+
console.log('Top-level bids:', book.bids);
|
|
280
|
+
console.log('Detailed YES bids:', book.yes.bids);
|
|
281
|
+
}
|
|
282
|
+
```
|
|
283
|
+
|
|
266
284
|
#### `getOpenOrders(marketAppId, walletAddress?)`
|
|
267
285
|
|
|
268
286
|
Gets open orders for a wallet on a specific market (from on-chain data).
|
|
@@ -337,6 +355,150 @@ for (const m of rewardMarkets) {
|
|
|
337
355
|
|
|
338
356
|
---
|
|
339
357
|
|
|
358
|
+
### WebSocket Streams
|
|
359
|
+
|
|
360
|
+
Real-time data streams via WebSocket. No API key or auth required. Replaces polling with push-based updates.
|
|
361
|
+
|
|
362
|
+
The SDK connects to the public platform websocket at `wss://wss.platform.alphaarcade.com`. The first
|
|
363
|
+
subscription is sent in the connection query string, and any later subscribe or unsubscribe calls use the
|
|
364
|
+
server's control-message envelope:
|
|
365
|
+
|
|
366
|
+
```json
|
|
367
|
+
{
|
|
368
|
+
"id": "request-id",
|
|
369
|
+
"method": "SUBSCRIBE",
|
|
370
|
+
"params": [
|
|
371
|
+
{ "stream": "get-orderbook", "slug": "will-btc-hit-100k" }
|
|
372
|
+
]
|
|
373
|
+
}
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
Supported public streams:
|
|
377
|
+
|
|
378
|
+
- `get-live-markets`
|
|
379
|
+
- `get-market` with `slug`
|
|
380
|
+
- `get-orderbook` with `slug`
|
|
381
|
+
- `get-wallet-orders` with `wallet`
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
import { AlphaWebSocket } from '@alpha-arcade/sdk';
|
|
385
|
+
|
|
386
|
+
// Node.js 22+ and browsers — native WebSocket, nothing extra needed
|
|
387
|
+
const ws = new AlphaWebSocket();
|
|
388
|
+
|
|
389
|
+
// Node.js < 22 — install `ws` and pass it in:
|
|
390
|
+
// npm install ws
|
|
391
|
+
import WebSocket from 'ws';
|
|
392
|
+
const ws = new AlphaWebSocket({ WebSocket });
|
|
393
|
+
|
|
394
|
+
// Subscribe to orderbook updates (~5s snapshots)
|
|
395
|
+
const unsub = ws.subscribeOrderbook('will-btc-hit-100k', (event) => {
|
|
396
|
+
console.log('Orderbook:', event.orderbook);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
// Unsubscribe when done
|
|
400
|
+
unsub();
|
|
401
|
+
|
|
402
|
+
// Close the connection
|
|
403
|
+
ws.close();
|
|
404
|
+
```
|
|
405
|
+
|
|
406
|
+
#### `subscribeLiveMarkets(callback)`
|
|
407
|
+
|
|
408
|
+
Receive incremental diffs whenever market probabilities change.
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
ws.subscribeLiveMarkets((event) => {
|
|
412
|
+
console.log('Markets changed at', event.ts, event);
|
|
413
|
+
});
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
#### `subscribeMarket(slug, callback)`
|
|
417
|
+
|
|
418
|
+
Receive change events for a single market. Uses the market **slug** (not `marketAppId`) — see note on `subscribeOrderbook` below.
|
|
419
|
+
|
|
420
|
+
```typescript
|
|
421
|
+
ws.subscribeMarket('will-btc-hit-100k', (event) => {
|
|
422
|
+
console.log('Market update:', event);
|
|
423
|
+
});
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
#### `subscribeOrderbook(slug, callback)`
|
|
427
|
+
|
|
428
|
+
Receive full orderbook snapshots on every change (~5s interval). The payload matches `getFullOrderbookFromApi(marketId)`.
|
|
429
|
+
|
|
430
|
+
**Note:** The WebSocket API uses market **slugs** (URL-friendly names like `"will-btc-hit-100k"`), not `marketAppId` numbers. You can get a market's slug from the `slug` field on `Market` objects returned by `getLiveMarkets()` or `getMarket()`.
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
ws.subscribeOrderbook('will-btc-hit-100k', (event) => {
|
|
434
|
+
// Top-level bids/asks use decimal prices (cents)
|
|
435
|
+
// Nested yes/no use raw microunit prices with escrowAppId and owner
|
|
436
|
+
for (const [appId, book] of Object.entries(event.orderbook)) {
|
|
437
|
+
console.log(`App ${appId}: spread=${book.spread}`);
|
|
438
|
+
console.log(' Bids:', book.bids);
|
|
439
|
+
console.log(' Yes bids:', book.yes.bids);
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
```
|
|
443
|
+
|
|
444
|
+
#### `subscribeWalletOrders(wallet, callback)`
|
|
445
|
+
|
|
446
|
+
Receive updates when orders for a wallet are created or modified.
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
ws.subscribeWalletOrders('MMU6X...', (event) => {
|
|
450
|
+
console.log('Wallet orders changed:', event);
|
|
451
|
+
});
|
|
452
|
+
```
|
|
453
|
+
|
|
454
|
+
#### Unsubscribing
|
|
455
|
+
|
|
456
|
+
Each `subscribe*` method returns an unsubscribe function. Call it to stop receiving events for that stream:
|
|
457
|
+
|
|
458
|
+
```typescript
|
|
459
|
+
const unsub = ws.subscribeOrderbook('my-market', (event) => { /* ... */ });
|
|
460
|
+
|
|
461
|
+
// Later, stop listening
|
|
462
|
+
unsub();
|
|
463
|
+
```
|
|
464
|
+
|
|
465
|
+
#### Control Methods
|
|
466
|
+
|
|
467
|
+
```typescript
|
|
468
|
+
// List active subscriptions on this connection
|
|
469
|
+
const subs = await ws.listSubscriptions();
|
|
470
|
+
|
|
471
|
+
// Query server properties (`heartbeat` or `limits`)
|
|
472
|
+
const props = await ws.getProperty('heartbeat');
|
|
473
|
+
```
|
|
474
|
+
|
|
475
|
+
#### Configuration
|
|
476
|
+
|
|
477
|
+
```typescript
|
|
478
|
+
import WebSocket from 'ws'; // Only needed on Node.js < 22
|
|
479
|
+
|
|
480
|
+
const ws = new AlphaWebSocket({
|
|
481
|
+
WebSocket, // Pass `ws` on Node.js < 22 (not needed in browsers or Node 22+)
|
|
482
|
+
url: 'wss://custom-endpoint.example.com', // Override default URL
|
|
483
|
+
reconnect: true, // Auto-reconnect (default: true)
|
|
484
|
+
maxReconnectAttempts: 10, // Give up after 10 retries (default: Infinity)
|
|
485
|
+
heartbeatIntervalMs: 60_000, // Ping interval in ms (default: 60000)
|
|
486
|
+
});
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
#### Connection Details
|
|
490
|
+
|
|
491
|
+
| Setting | Value |
|
|
492
|
+
|---------|-------|
|
|
493
|
+
| Heartbeat | 60s (auto-handled) |
|
|
494
|
+
| Idle timeout | 180s |
|
|
495
|
+
| Rate limit | 5 messages/sec/connection |
|
|
496
|
+
| Reconnect | Exponential backoff (1s → 30s max) |
|
|
497
|
+
|
|
498
|
+
The client automatically responds to server pings, sends keepalive pings, and reconnects with exponential backoff on unexpected disconnects. All active subscriptions are restored after reconnect.
|
|
499
|
+
|
|
500
|
+
---
|
|
501
|
+
|
|
340
502
|
### Utility Functions
|
|
341
503
|
|
|
342
504
|
These are exported for advanced users:
|
package/dist/index.cjs
CHANGED
|
@@ -2125,6 +2125,7 @@ var calculateMatchingOrders = (orderbook, isBuying, isYes, quantity, price, slip
|
|
|
2125
2125
|
|
|
2126
2126
|
// src/constants.ts
|
|
2127
2127
|
var DEFAULT_API_BASE_URL = "https://platform.alphaarcade.com/api";
|
|
2128
|
+
var DEFAULT_WSS_BASE_URL = "wss://wss.platform.alphaarcade.com";
|
|
2128
2129
|
var DEFAULT_MARKET_CREATOR_ADDRESS = "5P5Y6HTWUNG2E3VXBQDZN3ENZD3JPAIR5PKT3LOYJAPAUKOLFD6KANYTRY";
|
|
2129
2130
|
|
|
2130
2131
|
// src/modules/orderbook.ts
|
|
@@ -2265,6 +2266,18 @@ var getWalletOrdersFromApi = async (config, walletAddress) => {
|
|
|
2265
2266
|
}
|
|
2266
2267
|
return allOrders;
|
|
2267
2268
|
};
|
|
2269
|
+
var getFullOrderbookFromApi = async (config, marketId) => {
|
|
2270
|
+
if (!config.apiKey) {
|
|
2271
|
+
throw new Error("apiKey is required for API-based orderbook fetching. Retrieve an API key from the Alpha Arcade platform via the Account page and pass it to the client.");
|
|
2272
|
+
}
|
|
2273
|
+
const baseUrl = config.apiBaseUrl ?? DEFAULT_API_BASE_URL;
|
|
2274
|
+
const url = `${baseUrl}/get-full-orderbook?marketId=${encodeURIComponent(marketId)}`;
|
|
2275
|
+
const response = await fetch(url, { headers: { "x-api-key": config.apiKey } });
|
|
2276
|
+
if (!response.ok) {
|
|
2277
|
+
throw new Error(`Alpha API error: ${response.status} ${response.statusText}`);
|
|
2278
|
+
}
|
|
2279
|
+
return response.json();
|
|
2280
|
+
};
|
|
2268
2281
|
|
|
2269
2282
|
// src/modules/trading.ts
|
|
2270
2283
|
var extractEscrowAppId = async (algodClient, indexerClient, targetTxId) => {
|
|
@@ -3271,6 +3284,19 @@ var AlphaClient = class {
|
|
|
3271
3284
|
async getOrderbook(marketAppId) {
|
|
3272
3285
|
return getOrderbook(this.config, marketAppId);
|
|
3273
3286
|
}
|
|
3287
|
+
/**
|
|
3288
|
+
* Fetches the full processed orderbook snapshot for a market from the Alpha REST API.
|
|
3289
|
+
*
|
|
3290
|
+
* Returns the same shape as websocket `orderbook_changed.orderbook`: a record keyed by
|
|
3291
|
+
* `marketAppId`, where each value includes aggregated bids/asks plus detailed yes/no orders.
|
|
3292
|
+
* Requires `apiKey`.
|
|
3293
|
+
*
|
|
3294
|
+
* @param marketId - The Alpha market UUID
|
|
3295
|
+
* @returns Full processed market orderbook keyed by marketAppId
|
|
3296
|
+
*/
|
|
3297
|
+
async getFullOrderbookFromApi(marketId) {
|
|
3298
|
+
return getFullOrderbookFromApi(this.config, marketId);
|
|
3299
|
+
}
|
|
3274
3300
|
/**
|
|
3275
3301
|
* Gets open orders for a specific wallet on a market.
|
|
3276
3302
|
*
|
|
@@ -3366,9 +3392,315 @@ var AlphaClient = class {
|
|
|
3366
3392
|
}
|
|
3367
3393
|
};
|
|
3368
3394
|
|
|
3395
|
+
// src/websocket.ts
|
|
3396
|
+
var WS_OPEN = 1;
|
|
3397
|
+
var resolveWebSocket = (provided) => {
|
|
3398
|
+
if (provided) return provided;
|
|
3399
|
+
if (typeof globalThis !== "undefined" && globalThis.WebSocket) {
|
|
3400
|
+
return globalThis.WebSocket;
|
|
3401
|
+
}
|
|
3402
|
+
throw new Error(
|
|
3403
|
+
'No WebSocket implementation found. On Node.js < 22, install the "ws" package and pass it: new AlphaWebSocket({ WebSocket: require("ws") })'
|
|
3404
|
+
);
|
|
3405
|
+
};
|
|
3406
|
+
var AlphaWebSocket = class {
|
|
3407
|
+
url;
|
|
3408
|
+
reconnectEnabled;
|
|
3409
|
+
maxReconnectAttempts;
|
|
3410
|
+
heartbeatIntervalMs;
|
|
3411
|
+
WebSocketImpl;
|
|
3412
|
+
ws = null;
|
|
3413
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
3414
|
+
pendingRequests = /* @__PURE__ */ new Map();
|
|
3415
|
+
lastOrderbookVersionBySubscription = /* @__PURE__ */ new Map();
|
|
3416
|
+
heartbeatTimer = null;
|
|
3417
|
+
reconnectTimer = null;
|
|
3418
|
+
reconnectAttempts = 0;
|
|
3419
|
+
intentionallyClosed = false;
|
|
3420
|
+
connectPromise = null;
|
|
3421
|
+
constructor(config) {
|
|
3422
|
+
this.url = config?.url ?? DEFAULT_WSS_BASE_URL;
|
|
3423
|
+
this.reconnectEnabled = config?.reconnect ?? true;
|
|
3424
|
+
this.maxReconnectAttempts = config?.maxReconnectAttempts ?? Infinity;
|
|
3425
|
+
this.heartbeatIntervalMs = config?.heartbeatIntervalMs ?? 6e4;
|
|
3426
|
+
this.WebSocketImpl = resolveWebSocket(config?.WebSocket);
|
|
3427
|
+
}
|
|
3428
|
+
/** Whether the WebSocket is currently open and connected */
|
|
3429
|
+
get connected() {
|
|
3430
|
+
return this.ws?.readyState === WS_OPEN;
|
|
3431
|
+
}
|
|
3432
|
+
// ============================================
|
|
3433
|
+
// Subscribe Methods
|
|
3434
|
+
// ============================================
|
|
3435
|
+
/**
|
|
3436
|
+
* Subscribe to live market probability updates (incremental diffs).
|
|
3437
|
+
* @returns An unsubscribe function
|
|
3438
|
+
*/
|
|
3439
|
+
subscribeLiveMarkets(callback) {
|
|
3440
|
+
return this.subscribe("get-live-markets", {}, "markets_changed", callback);
|
|
3441
|
+
}
|
|
3442
|
+
/**
|
|
3443
|
+
* Subscribe to change events for a single market.
|
|
3444
|
+
* @param slug - The market slug
|
|
3445
|
+
* @returns An unsubscribe function
|
|
3446
|
+
*/
|
|
3447
|
+
subscribeMarket(slug, callback) {
|
|
3448
|
+
return this.subscribe("get-market", { slug }, "market_changed", callback);
|
|
3449
|
+
}
|
|
3450
|
+
/**
|
|
3451
|
+
* Subscribe to full orderbook snapshots (~5s interval on changes).
|
|
3452
|
+
* @param slug - The market slug
|
|
3453
|
+
* @returns An unsubscribe function
|
|
3454
|
+
*/
|
|
3455
|
+
subscribeOrderbook(slug, callback) {
|
|
3456
|
+
return this.subscribe("get-orderbook", { slug }, "orderbook_changed", callback);
|
|
3457
|
+
}
|
|
3458
|
+
/**
|
|
3459
|
+
* Subscribe to wallet order updates.
|
|
3460
|
+
* @param wallet - The wallet address
|
|
3461
|
+
* @returns An unsubscribe function
|
|
3462
|
+
*/
|
|
3463
|
+
subscribeWalletOrders(wallet, callback) {
|
|
3464
|
+
return this.subscribe("get-wallet-orders", { wallet }, "wallet_orders_changed", callback);
|
|
3465
|
+
}
|
|
3466
|
+
// ============================================
|
|
3467
|
+
// Control Methods
|
|
3468
|
+
// ============================================
|
|
3469
|
+
/** Query the server for the list of active subscriptions on this connection */
|
|
3470
|
+
listSubscriptions() {
|
|
3471
|
+
return this.sendRequest({ method: "LIST_SUBSCRIPTIONS" });
|
|
3472
|
+
}
|
|
3473
|
+
/** Query a server property (e.g. "heartbeat", "limits") */
|
|
3474
|
+
getProperty(property) {
|
|
3475
|
+
return this.sendRequest({ method: "GET_PROPERTY", params: [property] });
|
|
3476
|
+
}
|
|
3477
|
+
// ============================================
|
|
3478
|
+
// Lifecycle
|
|
3479
|
+
// ============================================
|
|
3480
|
+
/** Open the WebSocket connection. Called automatically on first subscribe. */
|
|
3481
|
+
connect() {
|
|
3482
|
+
if (this.connectPromise) return this.connectPromise;
|
|
3483
|
+
this.connectPromise = this.doConnect();
|
|
3484
|
+
return this.connectPromise;
|
|
3485
|
+
}
|
|
3486
|
+
/** Close the connection and clean up all resources */
|
|
3487
|
+
close() {
|
|
3488
|
+
this.intentionallyClosed = true;
|
|
3489
|
+
this.clearTimers();
|
|
3490
|
+
this.subscriptions.clear();
|
|
3491
|
+
for (const [, req] of this.pendingRequests) {
|
|
3492
|
+
clearTimeout(req.timer);
|
|
3493
|
+
req.reject(new Error("WebSocket closed"));
|
|
3494
|
+
}
|
|
3495
|
+
this.pendingRequests.clear();
|
|
3496
|
+
if (this.ws) {
|
|
3497
|
+
this.ws.close();
|
|
3498
|
+
this.ws = null;
|
|
3499
|
+
}
|
|
3500
|
+
this.connectPromise = null;
|
|
3501
|
+
}
|
|
3502
|
+
// ============================================
|
|
3503
|
+
// Internal
|
|
3504
|
+
// ============================================
|
|
3505
|
+
buildStreamKey(stream, params) {
|
|
3506
|
+
const parts = [stream, ...Object.entries(params).sort().map(([k, v]) => `${k}=${v}`)];
|
|
3507
|
+
return parts.join("&");
|
|
3508
|
+
}
|
|
3509
|
+
buildQueryString() {
|
|
3510
|
+
const subs = [...this.subscriptions.values()];
|
|
3511
|
+
if (subs.length === 0) return "";
|
|
3512
|
+
const first = subs[0];
|
|
3513
|
+
const params = new URLSearchParams({ stream: first.stream, ...first.params });
|
|
3514
|
+
return "?" + params.toString();
|
|
3515
|
+
}
|
|
3516
|
+
subscribe(stream, params, eventType, callback) {
|
|
3517
|
+
const key = this.buildStreamKey(stream, params);
|
|
3518
|
+
this.subscriptions.set(key, { stream, params, callback, eventType });
|
|
3519
|
+
if (this.connected) {
|
|
3520
|
+
this.sendSubscribe(stream, params);
|
|
3521
|
+
} else {
|
|
3522
|
+
this.connect();
|
|
3523
|
+
}
|
|
3524
|
+
return () => {
|
|
3525
|
+
this.subscriptions.delete(key);
|
|
3526
|
+
this.lastOrderbookVersionBySubscription.delete(key);
|
|
3527
|
+
if (this.connected) {
|
|
3528
|
+
this.sendUnsubscribe(stream, params);
|
|
3529
|
+
}
|
|
3530
|
+
};
|
|
3531
|
+
}
|
|
3532
|
+
async doConnect() {
|
|
3533
|
+
this.intentionallyClosed = false;
|
|
3534
|
+
return new Promise((resolve, reject) => {
|
|
3535
|
+
const qs = this.buildQueryString();
|
|
3536
|
+
const ws = new this.WebSocketImpl(this.url + qs);
|
|
3537
|
+
ws.onopen = () => {
|
|
3538
|
+
this.ws = ws;
|
|
3539
|
+
this.reconnectAttempts = 0;
|
|
3540
|
+
this.startHeartbeat();
|
|
3541
|
+
const subs = [...this.subscriptions.values()];
|
|
3542
|
+
for (const sub of subs) {
|
|
3543
|
+
this.sendSubscribe(sub.stream, sub.params);
|
|
3544
|
+
}
|
|
3545
|
+
resolve();
|
|
3546
|
+
};
|
|
3547
|
+
ws.onmessage = (event) => {
|
|
3548
|
+
this.handleMessage(event.data);
|
|
3549
|
+
};
|
|
3550
|
+
ws.onclose = () => {
|
|
3551
|
+
this.ws = null;
|
|
3552
|
+
this.connectPromise = null;
|
|
3553
|
+
this.stopHeartbeat();
|
|
3554
|
+
if (!this.intentionallyClosed) {
|
|
3555
|
+
this.scheduleReconnect();
|
|
3556
|
+
}
|
|
3557
|
+
};
|
|
3558
|
+
ws.onerror = (err) => {
|
|
3559
|
+
if (!this.ws) {
|
|
3560
|
+
reject(new Error("WebSocket connection failed"));
|
|
3561
|
+
}
|
|
3562
|
+
};
|
|
3563
|
+
});
|
|
3564
|
+
}
|
|
3565
|
+
handleMessage(raw) {
|
|
3566
|
+
let msg;
|
|
3567
|
+
try {
|
|
3568
|
+
msg = JSON.parse(raw);
|
|
3569
|
+
} catch {
|
|
3570
|
+
return;
|
|
3571
|
+
}
|
|
3572
|
+
if (msg.type === "ping") {
|
|
3573
|
+
this.send({ method: "PONG" });
|
|
3574
|
+
return;
|
|
3575
|
+
}
|
|
3576
|
+
const responseId = typeof msg.id === "string" ? msg.id : typeof msg.requestId === "string" ? msg.requestId : null;
|
|
3577
|
+
if (responseId && this.pendingRequests.has(responseId)) {
|
|
3578
|
+
const req = this.pendingRequests.get(responseId);
|
|
3579
|
+
this.pendingRequests.delete(responseId);
|
|
3580
|
+
clearTimeout(req.timer);
|
|
3581
|
+
req.resolve(msg);
|
|
3582
|
+
return;
|
|
3583
|
+
}
|
|
3584
|
+
const eventType = msg.type;
|
|
3585
|
+
if (!eventType) return;
|
|
3586
|
+
for (const [key, sub] of this.subscriptions.entries()) {
|
|
3587
|
+
if (!this.matchesSubscriptionMessage(sub, msg)) {
|
|
3588
|
+
continue;
|
|
3589
|
+
}
|
|
3590
|
+
if (!this.shouldDispatchSubscriptionMessage(key, sub, msg)) {
|
|
3591
|
+
continue;
|
|
3592
|
+
}
|
|
3593
|
+
try {
|
|
3594
|
+
sub.callback(msg);
|
|
3595
|
+
} catch {
|
|
3596
|
+
}
|
|
3597
|
+
}
|
|
3598
|
+
}
|
|
3599
|
+
matchesSubscriptionMessage(sub, msg) {
|
|
3600
|
+
if (sub.eventType !== msg.type) return false;
|
|
3601
|
+
if (msg.type === "orderbook_changed") {
|
|
3602
|
+
const messageMarketId = typeof msg.marketId === "string" ? msg.marketId : "";
|
|
3603
|
+
const messageSlug = typeof msg.slug === "string" ? msg.slug : "";
|
|
3604
|
+
const subscriptionMarketId = typeof sub.params.marketId === "string" ? sub.params.marketId : "";
|
|
3605
|
+
const subscriptionSlug = typeof sub.params.slug === "string" ? sub.params.slug : "";
|
|
3606
|
+
if (subscriptionMarketId) return subscriptionMarketId === messageMarketId;
|
|
3607
|
+
if (subscriptionSlug && messageSlug) return subscriptionSlug === messageSlug;
|
|
3608
|
+
if (subscriptionSlug || subscriptionMarketId) return false;
|
|
3609
|
+
}
|
|
3610
|
+
if (msg.type === "wallet_orders_changed") {
|
|
3611
|
+
const messageWallet = typeof msg.wallet === "string" ? msg.wallet : "";
|
|
3612
|
+
const subscriptionWallet = typeof sub.params.wallet === "string" ? sub.params.wallet : "";
|
|
3613
|
+
if (subscriptionWallet) return subscriptionWallet === messageWallet;
|
|
3614
|
+
return false;
|
|
3615
|
+
}
|
|
3616
|
+
return true;
|
|
3617
|
+
}
|
|
3618
|
+
shouldDispatchSubscriptionMessage(key, sub, msg) {
|
|
3619
|
+
if (sub.eventType !== "orderbook_changed") {
|
|
3620
|
+
return true;
|
|
3621
|
+
}
|
|
3622
|
+
const version = Number(msg.version ?? 0);
|
|
3623
|
+
if (!Number.isFinite(version)) {
|
|
3624
|
+
return true;
|
|
3625
|
+
}
|
|
3626
|
+
const lastVersion = this.lastOrderbookVersionBySubscription.get(key) ?? 0;
|
|
3627
|
+
if (version < lastVersion) {
|
|
3628
|
+
return false;
|
|
3629
|
+
}
|
|
3630
|
+
this.lastOrderbookVersionBySubscription.set(key, version);
|
|
3631
|
+
return true;
|
|
3632
|
+
}
|
|
3633
|
+
sendSubscribe(stream, params) {
|
|
3634
|
+
this.send({ method: "SUBSCRIBE", params: [{ stream, ...params }] });
|
|
3635
|
+
}
|
|
3636
|
+
sendUnsubscribe(stream, params) {
|
|
3637
|
+
this.send({ method: "UNSUBSCRIBE", params: [{ stream, ...params }] });
|
|
3638
|
+
}
|
|
3639
|
+
sendRequest(payload, timeoutMs = 1e4) {
|
|
3640
|
+
const requestId = crypto.randomUUID();
|
|
3641
|
+
return new Promise((resolve, reject) => {
|
|
3642
|
+
const timer = setTimeout(() => {
|
|
3643
|
+
this.pendingRequests.delete(requestId);
|
|
3644
|
+
reject(new Error("Request timed out"));
|
|
3645
|
+
}, timeoutMs);
|
|
3646
|
+
this.pendingRequests.set(requestId, { resolve, reject, timer });
|
|
3647
|
+
if (!this.connected) {
|
|
3648
|
+
this.connect().then(() => {
|
|
3649
|
+
this.send({ ...payload, id: requestId });
|
|
3650
|
+
}).catch(reject);
|
|
3651
|
+
} else {
|
|
3652
|
+
this.send({ ...payload, id: requestId });
|
|
3653
|
+
}
|
|
3654
|
+
});
|
|
3655
|
+
}
|
|
3656
|
+
send(data) {
|
|
3657
|
+
if (this.ws?.readyState === WS_OPEN) {
|
|
3658
|
+
this.ws.send(JSON.stringify(data));
|
|
3659
|
+
}
|
|
3660
|
+
}
|
|
3661
|
+
// ============================================
|
|
3662
|
+
// Heartbeat
|
|
3663
|
+
// ============================================
|
|
3664
|
+
startHeartbeat() {
|
|
3665
|
+
this.stopHeartbeat();
|
|
3666
|
+
this.heartbeatTimer = setInterval(() => {
|
|
3667
|
+
this.send({ method: "PING" });
|
|
3668
|
+
}, this.heartbeatIntervalMs);
|
|
3669
|
+
}
|
|
3670
|
+
stopHeartbeat() {
|
|
3671
|
+
if (this.heartbeatTimer) {
|
|
3672
|
+
clearInterval(this.heartbeatTimer);
|
|
3673
|
+
this.heartbeatTimer = null;
|
|
3674
|
+
}
|
|
3675
|
+
}
|
|
3676
|
+
// ============================================
|
|
3677
|
+
// Reconnect
|
|
3678
|
+
// ============================================
|
|
3679
|
+
scheduleReconnect() {
|
|
3680
|
+
if (!this.reconnectEnabled) return;
|
|
3681
|
+
if (this.reconnectAttempts >= this.maxReconnectAttempts) return;
|
|
3682
|
+
const delay = Math.min(1e3 * 2 ** this.reconnectAttempts, 3e4);
|
|
3683
|
+
this.reconnectAttempts++;
|
|
3684
|
+
this.reconnectTimer = setTimeout(() => {
|
|
3685
|
+
this.reconnectTimer = null;
|
|
3686
|
+
this.connect().catch(() => {
|
|
3687
|
+
});
|
|
3688
|
+
}, delay);
|
|
3689
|
+
}
|
|
3690
|
+
clearTimers() {
|
|
3691
|
+
this.stopHeartbeat();
|
|
3692
|
+
if (this.reconnectTimer) {
|
|
3693
|
+
clearTimeout(this.reconnectTimer);
|
|
3694
|
+
this.reconnectTimer = null;
|
|
3695
|
+
}
|
|
3696
|
+
}
|
|
3697
|
+
};
|
|
3698
|
+
|
|
3369
3699
|
exports.AlphaClient = AlphaClient;
|
|
3700
|
+
exports.AlphaWebSocket = AlphaWebSocket;
|
|
3370
3701
|
exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
|
|
3371
3702
|
exports.DEFAULT_MARKET_CREATOR_ADDRESS = DEFAULT_MARKET_CREATOR_ADDRESS;
|
|
3703
|
+
exports.DEFAULT_WSS_BASE_URL = DEFAULT_WSS_BASE_URL;
|
|
3372
3704
|
exports.calculateFee = calculateFee;
|
|
3373
3705
|
exports.calculateFeeFromTotal = calculateFeeFromTotal;
|
|
3374
3706
|
exports.calculateMatchingOrders = calculateMatchingOrders;
|