@alpha-arcade/sdk 0.3.0 → 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 +467 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +217 -2
- package/dist/index.d.ts +217 -2
- package/dist/index.js +466 -3
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
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) => {
|
|
@@ -2514,6 +2527,89 @@ var proposeMatch = async (config, params) => {
|
|
|
2514
2527
|
confirmedRound: Number(result.confirmedRound)
|
|
2515
2528
|
};
|
|
2516
2529
|
};
|
|
2530
|
+
var processMatch = async (config, params) => {
|
|
2531
|
+
const { algodClient, signer, activeAddress, usdcAssetId } = config;
|
|
2532
|
+
const { marketAppId, makerEscrowAppId, takerEscrowAppId } = params;
|
|
2533
|
+
const [marketState, makerAppInfo, takerAppInfo] = await Promise.all([
|
|
2534
|
+
getMarketGlobalState(algodClient, marketAppId),
|
|
2535
|
+
algodClient.getApplicationByID(makerEscrowAppId).do(),
|
|
2536
|
+
algodClient.getApplicationByID(takerEscrowAppId).do()
|
|
2537
|
+
]);
|
|
2538
|
+
const marketFeeAddress = marketState.fee_address;
|
|
2539
|
+
const yesAssetId = marketState.yes_asset_id;
|
|
2540
|
+
const noAssetId = marketState.no_asset_id;
|
|
2541
|
+
const makerState = decodeGlobalState(
|
|
2542
|
+
makerAppInfo.params?.globalState ?? makerAppInfo.params?.["global-state"] ?? []
|
|
2543
|
+
);
|
|
2544
|
+
const takerState = decodeGlobalState(
|
|
2545
|
+
takerAppInfo.params?.globalState ?? takerAppInfo.params?.["global-state"] ?? []
|
|
2546
|
+
);
|
|
2547
|
+
const makerOwner = makerState.owner ?? "";
|
|
2548
|
+
const takerOwner = takerState.owner ?? "";
|
|
2549
|
+
const makerRemaining = (makerState.quantity ?? 0) - (makerState.quantity_filled ?? 0);
|
|
2550
|
+
const takerRemaining = (takerState.quantity ?? 0) - (takerState.quantity_filled ?? 0);
|
|
2551
|
+
const matchedQuantity = Math.min(makerRemaining, takerRemaining);
|
|
2552
|
+
if (matchedQuantity <= 0) {
|
|
2553
|
+
throw new Error("processMatch: no quantity left to match on maker or taker escrow.");
|
|
2554
|
+
}
|
|
2555
|
+
const signerAccount = { signer, addr: activeAddress };
|
|
2556
|
+
const makerEscrowClient = new EscrowAppClient(
|
|
2557
|
+
{ resolveBy: "id", id: makerEscrowAppId, sender: signerAccount },
|
|
2558
|
+
algodClient
|
|
2559
|
+
);
|
|
2560
|
+
const takerEscrowClient = new EscrowAppClient(
|
|
2561
|
+
{ resolveBy: "id", id: takerEscrowAppId, sender: signerAccount },
|
|
2562
|
+
algodClient
|
|
2563
|
+
);
|
|
2564
|
+
const marketClient = new MarketAppClient(
|
|
2565
|
+
{ resolveBy: "id", id: marketAppId, sender: signerAccount },
|
|
2566
|
+
algodClient
|
|
2567
|
+
);
|
|
2568
|
+
const atc = new algosdk2.AtomicTransactionComposer();
|
|
2569
|
+
const assets = [usdcAssetId, yesAssetId, noAssetId];
|
|
2570
|
+
const sendParamsWithFee = { skipSending: true, fee: algokit4__namespace.microAlgos(3e3) };
|
|
2571
|
+
const sendParamsNoop = { skipSending: true, fee: algokit4__namespace.microAlgos(1e3) };
|
|
2572
|
+
const matchMakerTxn = await makerEscrowClient.matchMaker(
|
|
2573
|
+
{ taker: takerEscrowAppId, matchQuantity: matchedQuantity },
|
|
2574
|
+
{
|
|
2575
|
+
assets,
|
|
2576
|
+
apps: [marketAppId],
|
|
2577
|
+
accounts: [takerOwner, marketFeeAddress],
|
|
2578
|
+
sendParams: sendParamsWithFee
|
|
2579
|
+
}
|
|
2580
|
+
);
|
|
2581
|
+
atc.addTransaction({ txn: matchMakerTxn.transaction, signer });
|
|
2582
|
+
const matchTakerTxn = await takerEscrowClient.matchTaker(
|
|
2583
|
+
{ maker: makerEscrowAppId },
|
|
2584
|
+
{
|
|
2585
|
+
assets,
|
|
2586
|
+
apps: [marketAppId],
|
|
2587
|
+
accounts: [makerOwner, marketFeeAddress],
|
|
2588
|
+
sendParams: sendParamsWithFee
|
|
2589
|
+
}
|
|
2590
|
+
);
|
|
2591
|
+
atc.addTransaction({ txn: matchTakerTxn.transaction, signer });
|
|
2592
|
+
const processMatchTxn = await marketClient.processPotentialMatch(
|
|
2593
|
+
{ maker: makerEscrowAppId, taker: takerEscrowAppId },
|
|
2594
|
+
{
|
|
2595
|
+
assets,
|
|
2596
|
+
accounts: [makerOwner, takerOwner, marketFeeAddress],
|
|
2597
|
+
sendParams: sendParamsNoop
|
|
2598
|
+
}
|
|
2599
|
+
);
|
|
2600
|
+
atc.addTransaction({ txn: processMatchTxn.transaction, signer });
|
|
2601
|
+
const doNoopTxn = await marketClient.doNoop(
|
|
2602
|
+
{ callNumber: 1 },
|
|
2603
|
+
{ sendParams: sendParamsNoop }
|
|
2604
|
+
);
|
|
2605
|
+
atc.addTransaction({ txn: doNoopTxn.transaction, signer });
|
|
2606
|
+
const result = await atc.execute(algodClient, 4);
|
|
2607
|
+
return {
|
|
2608
|
+
success: true,
|
|
2609
|
+
txIds: result.txIDs,
|
|
2610
|
+
confirmedRound: Number(result.confirmedRound)
|
|
2611
|
+
};
|
|
2612
|
+
};
|
|
2517
2613
|
var amendOrder = async (config, params) => {
|
|
2518
2614
|
const { algodClient, signer, activeAddress, usdcAssetId } = config;
|
|
2519
2615
|
const { marketAppId, escrowAppId, price, quantity, slippage = 0 } = params;
|
|
@@ -2570,10 +2666,47 @@ var amendOrder = async (config, params) => {
|
|
|
2570
2666
|
);
|
|
2571
2667
|
atc.addTransaction({ txn: amendCall.transaction, signer });
|
|
2572
2668
|
const result = await atc.execute(algodClient, 4);
|
|
2669
|
+
const allTxIds = [...result.txIDs];
|
|
2670
|
+
let lastConfirmedRound = Number(result.confirmedRound);
|
|
2671
|
+
const orderbook = await getOrderbook(config, marketAppId);
|
|
2672
|
+
let matchingOrders = calculateMatchingOrders(orderbook, isBuy, position === 1, quantity, price, slippage);
|
|
2673
|
+
matchingOrders = matchingOrders.filter((m) => m.escrowAppId !== escrowAppId);
|
|
2674
|
+
if (matchingOrders.length > 0) {
|
|
2675
|
+
let quantityLeft = quantity;
|
|
2676
|
+
const matchedQuantities = [];
|
|
2677
|
+
const matchedPrices = [];
|
|
2678
|
+
for (const m of matchingOrders) {
|
|
2679
|
+
if (quantityLeft <= 0) break;
|
|
2680
|
+
try {
|
|
2681
|
+
const matchResult = await processMatch(config, {
|
|
2682
|
+
marketAppId,
|
|
2683
|
+
makerEscrowAppId: m.escrowAppId,
|
|
2684
|
+
takerEscrowAppId: escrowAppId
|
|
2685
|
+
});
|
|
2686
|
+
allTxIds.push(...matchResult.txIds);
|
|
2687
|
+
lastConfirmedRound = matchResult.confirmedRound;
|
|
2688
|
+
const q = Math.min(m.quantity, quantityLeft);
|
|
2689
|
+
matchedQuantities.push(q);
|
|
2690
|
+
matchedPrices.push((m.price ?? price) * q);
|
|
2691
|
+
quantityLeft -= q;
|
|
2692
|
+
} catch (err) {
|
|
2693
|
+
console.log(`Error matching order: ${JSON.stringify(err)}`);
|
|
2694
|
+
break;
|
|
2695
|
+
}
|
|
2696
|
+
}
|
|
2697
|
+
const totalMatchedQuantity = matchedQuantities.reduce((a, b) => a + b, 0);
|
|
2698
|
+
const matchedPrice = totalMatchedQuantity > 0 ? Math.round(matchedPrices.reduce((a, b) => a + b, 0) / totalMatchedQuantity) : void 0;
|
|
2699
|
+
return {
|
|
2700
|
+
success: true,
|
|
2701
|
+
txIds: allTxIds,
|
|
2702
|
+
confirmedRound: lastConfirmedRound,
|
|
2703
|
+
...totalMatchedQuantity > 0 && { matchedQuantity: totalMatchedQuantity, matchedPrice }
|
|
2704
|
+
};
|
|
2705
|
+
}
|
|
2573
2706
|
return {
|
|
2574
2707
|
success: true,
|
|
2575
|
-
txIds:
|
|
2576
|
-
confirmedRound:
|
|
2708
|
+
txIds: allTxIds,
|
|
2709
|
+
confirmedRound: lastConfirmedRound
|
|
2577
2710
|
};
|
|
2578
2711
|
};
|
|
2579
2712
|
var splitShares = async (config, params) => {
|
|
@@ -3056,6 +3189,19 @@ var AlphaClient = class {
|
|
|
3056
3189
|
async proposeMatch(params) {
|
|
3057
3190
|
return proposeMatch(this.config, params);
|
|
3058
3191
|
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Matches two existing limit orders (no create-escrow in the group).
|
|
3194
|
+
*
|
|
3195
|
+
* Calls the market app's process_potential_match(maker, taker). Use this
|
|
3196
|
+
* after amending an order: the amended order is the taker (pays the fee),
|
|
3197
|
+
* the counterparty is the maker.
|
|
3198
|
+
*
|
|
3199
|
+
* @param params - Process match params (marketAppId, makerEscrowAppId, takerEscrowAppId)
|
|
3200
|
+
* @returns Whether the match succeeded
|
|
3201
|
+
*/
|
|
3202
|
+
async processMatch(params) {
|
|
3203
|
+
return processMatch(this.config, params);
|
|
3204
|
+
}
|
|
3059
3205
|
/**
|
|
3060
3206
|
* Amends (edits) an existing unfilled order in-place.
|
|
3061
3207
|
*
|
|
@@ -3138,6 +3284,19 @@ var AlphaClient = class {
|
|
|
3138
3284
|
async getOrderbook(marketAppId) {
|
|
3139
3285
|
return getOrderbook(this.config, marketAppId);
|
|
3140
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
|
+
}
|
|
3141
3300
|
/**
|
|
3142
3301
|
* Gets open orders for a specific wallet on a market.
|
|
3143
3302
|
*
|
|
@@ -3233,9 +3392,315 @@ var AlphaClient = class {
|
|
|
3233
3392
|
}
|
|
3234
3393
|
};
|
|
3235
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
|
+
|
|
3236
3699
|
exports.AlphaClient = AlphaClient;
|
|
3700
|
+
exports.AlphaWebSocket = AlphaWebSocket;
|
|
3237
3701
|
exports.DEFAULT_API_BASE_URL = DEFAULT_API_BASE_URL;
|
|
3238
3702
|
exports.DEFAULT_MARKET_CREATOR_ADDRESS = DEFAULT_MARKET_CREATOR_ADDRESS;
|
|
3703
|
+
exports.DEFAULT_WSS_BASE_URL = DEFAULT_WSS_BASE_URL;
|
|
3239
3704
|
exports.calculateFee = calculateFee;
|
|
3240
3705
|
exports.calculateFeeFromTotal = calculateFeeFromTotal;
|
|
3241
3706
|
exports.calculateMatchingOrders = calculateMatchingOrders;
|