@metamask-previews/perps-controller 24.1.0-preview-1a6714ed3 → 24.1.0-preview-4ba073b3a
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/CHANGELOG.md +95 -0
- package/README.md +115 -5
- package/dist/PerpsController-method-action-types.d.ts +2 -2
- package/dist/PerpsController-method-action-types.js.map +1 -1
- package/dist/PerpsController.d.ts +19 -6
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +302 -64
- package/dist/PerpsController.js.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.d.ts +13 -2
- package/dist/aggregation/SubscriptionMultiplexer.d.ts.map +1 -1
- package/dist/aggregation/SubscriptionMultiplexer.js +27 -13
- package/dist/aggregation/SubscriptionMultiplexer.js.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.ts +2 -0
- package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
- package/dist/constants/hyperLiquidConfig.js +2 -0
- package/dist/constants/hyperLiquidConfig.js.map +1 -1
- package/dist/constants/lighterConfig.d.ts +17 -0
- package/dist/constants/lighterConfig.d.ts.map +1 -1
- package/dist/constants/lighterConfig.js +31 -8
- package/dist/constants/lighterConfig.js.map +1 -1
- package/dist/errors.d.ts +16 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +13 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +7 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/perpsErrorCodes.d.ts +3 -0
- package/dist/perpsErrorCodes.d.ts.map +1 -1
- package/dist/perpsErrorCodes.js +4 -0
- package/dist/perpsErrorCodes.js.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts +33 -1
- package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
- package/dist/providers/AggregatedPerpsProvider.js +688 -41
- package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts +2 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +410 -132
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts +9 -2
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +334 -111
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/services/AccountService.d.ts.map +1 -1
- package/dist/services/AccountService.js +14 -1
- package/dist/services/AccountService.js.map +1 -1
- package/dist/services/DepositService.d.ts +8 -1
- package/dist/services/DepositService.d.ts.map +1 -1
- package/dist/services/DepositService.js +47 -6
- package/dist/services/DepositService.js.map +1 -1
- package/dist/services/HyperLiquidClientService.d.ts +1 -1
- package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
- package/dist/services/HyperLiquidClientService.js +5 -2
- package/dist/services/HyperLiquidClientService.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts +19 -14
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +612 -191
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/HyperLiquidWalletService.d.ts +7 -0
- package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
- package/dist/services/HyperLiquidWalletService.js +16 -0
- package/dist/services/HyperLiquidWalletService.js.map +1 -1
- package/dist/services/LighterClientService.d.ts.map +1 -1
- package/dist/services/LighterClientService.js +3 -1
- package/dist/services/LighterClientService.js.map +1 -1
- package/dist/services/RewardsIntegrationService.d.ts +2 -1
- package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
- package/dist/services/RewardsIntegrationService.js +9 -2
- package/dist/services/RewardsIntegrationService.js.map +1 -1
- package/dist/services/ServiceContext.d.ts +3 -3
- package/dist/services/ServiceContext.d.ts.map +1 -1
- package/dist/services/ServiceContext.js.map +1 -1
- package/dist/services/TradingService.d.ts.map +1 -1
- package/dist/services/TradingService.js +340 -88
- package/dist/services/TradingService.js.map +1 -1
- package/dist/types/index.d.ts +321 -14
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/types/lighter-types.d.ts +1 -1
- package/dist/types/lighter-types.d.ts.map +1 -1
- package/dist/types/lighter-types.js.map +1 -1
- package/dist/utils/accountAggregation.d.ts +58 -0
- package/dist/utils/accountAggregation.d.ts.map +1 -0
- package/dist/utils/accountAggregation.js +117 -0
- package/dist/utils/accountAggregation.js.map +1 -0
- package/dist/utils/accountUtils.d.ts +18 -0
- package/dist/utils/accountUtils.d.ts.map +1 -1
- package/dist/utils/accountUtils.js +69 -66
- package/dist/utils/accountUtils.js.map +1 -1
- package/dist/utils/batchOperationStatus.d.ts +18 -0
- package/dist/utils/batchOperationStatus.d.ts.map +1 -0
- package/dist/utils/batchOperationStatus.js +26 -0
- package/dist/utils/batchOperationStatus.js.map +1 -0
- package/dist/utils/cancelOrders.d.ts +32 -0
- package/dist/utils/cancelOrders.d.ts.map +1 -0
- package/dist/utils/cancelOrders.js +53 -0
- package/dist/utils/cancelOrders.js.map +1 -0
- package/dist/utils/closePositions.d.ts +24 -0
- package/dist/utils/closePositions.d.ts.map +1 -0
- package/dist/utils/closePositions.js +20 -0
- package/dist/utils/closePositions.js.map +1 -0
- package/dist/utils/feeSupport.d.ts +9 -0
- package/dist/utils/feeSupport.d.ts.map +1 -0
- package/dist/utils/feeSupport.js +11 -0
- package/dist/utils/feeSupport.js.map +1 -0
- package/dist/utils/hyperLiquidAdapter.d.ts +9 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +37 -1
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.d.ts +46 -0
- package/dist/utils/hyperLiquidPositionPreview.d.ts.map +1 -1
- package/dist/utils/hyperLiquidPositionPreview.js +98 -6
- package/dist/utils/hyperLiquidPositionPreview.js.map +1 -1
- package/dist/utils/index.d.ts +5 -0
- package/dist/utils/index.d.ts.map +1 -1
- package/dist/utils/index.js +3 -0
- package/dist/utils/index.js.map +1 -1
- package/dist/utils/lighterAdapter.d.ts +2 -1
- package/dist/utils/lighterAdapter.d.ts.map +1 -1
- package/dist/utils/lighterAdapter.js +32 -16
- package/dist/utils/lighterAdapter.js.map +1 -1
- package/dist/utils/orderBookGrouping.d.ts +38 -0
- package/dist/utils/orderBookGrouping.d.ts.map +1 -0
- package/dist/utils/orderBookGrouping.js +101 -0
- package/dist/utils/orderBookGrouping.js.map +1 -0
- package/dist/utils/orderTypes.d.ts +2 -0
- package/dist/utils/orderTypes.d.ts.map +1 -1
- package/dist/utils/orderTypes.js +11 -4
- package/dist/utils/orderTypes.js.map +1 -1
- package/dist/utils/perpsClientCopy.d.ts +33 -0
- package/dist/utils/perpsClientCopy.d.ts.map +1 -0
- package/dist/utils/perpsClientCopy.js +509 -0
- package/dist/utils/perpsClientCopy.js.map +1 -0
- package/dist/utils/standaloneInfoClient.d.ts +20 -3
- package/dist/utils/standaloneInfoClient.d.ts.map +1 -1
- package/dist/utils/standaloneInfoClient.js +35 -10
- package/dist/utils/standaloneInfoClient.js.map +1 -1
- package/dist/utils/subscriptionFeeWaiver.d.ts.map +1 -1
- package/dist/utils/subscriptionFeeWaiver.js +5 -3
- package/dist/utils/subscriptionFeeWaiver.js.map +1 -1
- package/docs/README.md +1 -0
- package/docs/architecture.md +16 -12
- package/docs/client-contract.md +89 -0
- package/docs/contracts/events.md +1 -1
- package/docs/tpsl.md +1 -0
- package/package.json +2 -2
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
* - Support aggregation modes: 'merge' (all prices) or 'best_price' (best price per symbol)
|
|
8
8
|
* - Cache latest updates per provider per symbol for aggregation
|
|
9
9
|
*/
|
|
10
|
-
import type { PerpsProviderType, PerpsProvider, PerpsLogger, PriceUpdate, Position, AccountState, SubscribeOrderFillsParams, SubscribeOrdersParams } from '../types/index.js';
|
|
10
|
+
import type { PerpsProviderType, PerpsProvider, PerpsLogger, PriceUpdate, Position, AccountState, SubscribeOrderFillsParams, SubscribeOrdersParams, SubscribeAccountParams } from '../types/index.js';
|
|
11
11
|
/**
|
|
12
12
|
* Options for constructing SubscriptionMultiplexer
|
|
13
13
|
*/
|
|
@@ -73,9 +73,15 @@ export type MultiplexedOrdersParams = {
|
|
|
73
73
|
* Parameters for multiplexed account subscriptions
|
|
74
74
|
*/
|
|
75
75
|
export type MultiplexedAccountParams = {
|
|
76
|
+
/** Keep healthy venue streams when setup fails; the next emission excludes the failed venue. */
|
|
77
|
+
onError?: (error: Error, providerId: PerpsProviderType) => void;
|
|
78
|
+
/** Optional account identity forwarded to every provider. */
|
|
79
|
+
accountId?: SubscribeAccountParams['accountId'];
|
|
80
|
+
/** Ask every provider for a complete account or `null`, never a partial one. */
|
|
81
|
+
requireCompleteAccount?: boolean;
|
|
76
82
|
/** Provider instances to subscribe through */
|
|
77
83
|
providers: [PerpsProviderType, PerpsProvider][];
|
|
78
|
-
/** Callback to receive account updates (one per provider) */
|
|
84
|
+
/** Callback to receive account updates (one entry per provider with data) */
|
|
79
85
|
callback: (accounts: AccountState[]) => void;
|
|
80
86
|
};
|
|
81
87
|
/**
|
|
@@ -148,6 +154,11 @@ export declare class SubscriptionMultiplexer {
|
|
|
148
154
|
/**
|
|
149
155
|
* Subscribe to account updates from multiple providers.
|
|
150
156
|
*
|
|
157
|
+
* Each subscription owns its cache: a venue's latest state is visible only
|
|
158
|
+
* to that subscription, so one subscription's cleanup never erases another
|
|
159
|
+
* subscription's venue data, and a subscription starts empty regardless of
|
|
160
|
+
* other live account streams.
|
|
161
|
+
*
|
|
151
162
|
* @param params - Subscription parameters
|
|
152
163
|
* @returns Unsubscribe function
|
|
153
164
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionMultiplexer.d.ts","sourceRoot":"","sources":["../../src/aggregation/SubscriptionMultiplexer.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EACV,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,WAAW,EACX,QAAQ,EAER,YAAY,EAGZ,yBAAyB,EACzB,qBAAqB,
|
|
1
|
+
{"version":3,"file":"SubscriptionMultiplexer.d.ts","sourceRoot":"","sources":["../../src/aggregation/SubscriptionMultiplexer.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EACV,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,WAAW,EACX,QAAQ,EAER,YAAY,EAGZ,yBAAyB,EACzB,qBAAqB,EACrB,sBAAsB,EACvB,MAAM,mBAAmB,CAAC;AAG3B;;GAEG;AACH,MAAM,MAAM,8BAA8B,GAAG;IAC3C,yDAAyD;IACzD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,oBAAoB,GAAG,OAAO,GAAG,YAAY,CAAC;AAE1D;;GAEG;AACH,MAAM,MAAM,uBAAuB,GAAG;IACpC,8BAA8B;IAC9B,OAAO,EAAE,MAAM,EAAE,CAAC;IAClB,8CAA8C;IAC9C,SAAS,EAAE,CAAC,iBAAiB,EAAE,aAAa,CAAC,EAAE,CAAC;IAChD,mDAAmD;IACnD,QAAQ,EAAE,CAAC,MAAM,EAAE,WAAW,EAAE,KAAK,IAAI,CAAC;IAC1C,yFAAyF;IACzF,eAAe,CAAC,EAAE,oBAAoB,CAAC;IACvC,wCAAwC;IACxC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8BAA8B;IAC9B,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,gDAAgD;IAChD,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,0BAA0B,GAAG;IACvC,8CAA8C;IAC9C,SAAS,EAAE,CAAC,iBAAiB,EAAE,aAAa,CAAC,EAAE,CAAC;IAChD,sDAAsD;IACtD,QAAQ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CAAC,MAAM,EAAE,uBAAuB,GAAG,MAAM,IAAI,CA2E7D;IAED;;;;;OAKG;IACH,oBAAoB,CAAC,MAAM,EAAE,0BAA0B,GAAG,MAAM,IAAI,CAkDnE;IAED;;;;;OAKG;IACH,qBAAqB,CAAC,MAAM,EAAE,2BAA2B,GAAG,MAAM,IAAI,CA6CrE;IAED;;;;;OAKG;IACH,iBAAiB,CAAC,MAAM,EAAE,uBAAuB,GAAG,MAAM,IAAI,CAkD7D;IAED;;;;;;;;;;OAUG;IACH,kBAAkB,CAAC,MAAM,EAAE,wBAAwB,GAAG,MAAM,IAAI,CAuE/D;IA8FD;;OAEG;IACH,UAAU,IAAI,IAAI,CAIjB;IAED;;;;;;OAMG;IACH,cAAc,CACZ,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,iBAAiB,GAC5B,WAAW,GAAG,SAAS,CAEzB;IAED;;;;;OAKG;IACH,2BAA2B,CACzB,MAAM,EAAE,MAAM,GACb,GAAG,CAAC,iBAAiB,EAAE,WAAW,CAAC,GAAG,SAAS,CAEjD;CACF"}
|
|
@@ -60,11 +60,6 @@ export class SubscriptionMultiplexer {
|
|
|
60
60
|
* Map<providerId, Order[]>
|
|
61
61
|
*/
|
|
62
62
|
#orderCache = new Map();
|
|
63
|
-
/**
|
|
64
|
-
* Cache of latest account state per provider
|
|
65
|
-
* Map<providerId, AccountState>
|
|
66
|
-
*/
|
|
67
|
-
#accountCache = new Map();
|
|
68
63
|
/**
|
|
69
64
|
* Create a new SubscriptionMultiplexer.
|
|
70
65
|
*
|
|
@@ -289,18 +284,34 @@ export class SubscriptionMultiplexer {
|
|
|
289
284
|
/**
|
|
290
285
|
* Subscribe to account updates from multiple providers.
|
|
291
286
|
*
|
|
287
|
+
* Each subscription owns its cache: a venue's latest state is visible only
|
|
288
|
+
* to that subscription, so one subscription's cleanup never erases another
|
|
289
|
+
* subscription's venue data, and a subscription starts empty regardless of
|
|
290
|
+
* other live account streams.
|
|
291
|
+
*
|
|
292
292
|
* @param params - Subscription parameters
|
|
293
293
|
* @returns Unsubscribe function
|
|
294
294
|
*/
|
|
295
295
|
subscribeToAccount(params) {
|
|
296
296
|
const { providers, callback } = params;
|
|
297
297
|
const unsubscribers = [];
|
|
298
|
+
// Per-subscription cache: latest state per venue for THIS subscription.
|
|
299
|
+
const accountCache = new Map();
|
|
298
300
|
for (const [providerId, provider] of providers) {
|
|
299
301
|
try {
|
|
300
302
|
const subscribeParams = {
|
|
303
|
+
...(params.accountId !== undefined && {
|
|
304
|
+
accountId: params.accountId,
|
|
305
|
+
}),
|
|
306
|
+
...(params.requireCompleteAccount === true && {
|
|
307
|
+
requireCompleteAccount: true,
|
|
308
|
+
}),
|
|
301
309
|
callback: (account) => {
|
|
302
310
|
if (account === null) {
|
|
303
|
-
|
|
311
|
+
// The venue's balance is no longer known. Drop its previous
|
|
312
|
+
// value: it must not stay in the aggregate as current, and it
|
|
313
|
+
// must not become a zero.
|
|
314
|
+
accountCache.delete(providerId);
|
|
304
315
|
}
|
|
305
316
|
else {
|
|
306
317
|
// Tag account with providerId and cache
|
|
@@ -308,10 +319,10 @@ export class SubscriptionMultiplexer {
|
|
|
308
319
|
...account,
|
|
309
320
|
providerId,
|
|
310
321
|
};
|
|
311
|
-
|
|
322
|
+
accountCache.set(providerId, taggedAccount);
|
|
312
323
|
}
|
|
313
|
-
// Emit
|
|
314
|
-
const allAccounts = Array.from(
|
|
324
|
+
// Emit this subscription's cached account states
|
|
325
|
+
const allAccounts = Array.from(accountCache.values());
|
|
315
326
|
callback(allAccounts);
|
|
316
327
|
},
|
|
317
328
|
};
|
|
@@ -330,15 +341,19 @@ export class SubscriptionMultiplexer {
|
|
|
330
341
|
data: { subscribedCount: unsubscribers.length },
|
|
331
342
|
},
|
|
332
343
|
});
|
|
344
|
+
if (params.onError) {
|
|
345
|
+
accountCache.delete(providerId);
|
|
346
|
+
params.onError(ensureError(error, 'SubscriptionMultiplexer.subscribeToAccount'), providerId);
|
|
347
|
+
callback(Array.from(accountCache.values()));
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
333
350
|
unsubscribers.forEach((unsub) => unsub());
|
|
334
351
|
throw error;
|
|
335
352
|
}
|
|
336
353
|
}
|
|
337
354
|
return () => {
|
|
338
355
|
unsubscribers.forEach((unsub) => unsub());
|
|
339
|
-
|
|
340
|
-
this.#accountCache.delete(providerId);
|
|
341
|
-
});
|
|
356
|
+
// The cache is per-subscription: nothing shared to clear.
|
|
342
357
|
};
|
|
343
358
|
}
|
|
344
359
|
/**
|
|
@@ -428,7 +443,6 @@ export class SubscriptionMultiplexer {
|
|
|
428
443
|
this.#priceCache.clear();
|
|
429
444
|
this.#positionCache.clear();
|
|
430
445
|
this.#orderCache.clear();
|
|
431
|
-
this.#accountCache.clear();
|
|
432
446
|
}
|
|
433
447
|
/**
|
|
434
448
|
* Get cached price for a symbol from a specific provider.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SubscriptionMultiplexer.js","sourceRoot":"","sources":["../../src/aggregation/SubscriptionMultiplexer.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAe9D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AA+ErD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,MAAM,OAAO,uBAAuB;IAClC;;OAEG;IACM,OAAO,CAAe;IAE/B;;;OAGG;IACM,WAAW,GAClB,IAAI,GAAG,EAAE,CAAC;IAEZ;;;OAGG;IACM,cAAc,GAAuC,IAAI,GAAG,EAAE,CAAC;IAExE;;;OAGG;IACM,WAAW,GAAoC,IAAI,GAAG,EAAE,CAAC;IAElE;;;OAGG;IACM,aAAa,GAAyC,IAAI,GAAG,EAAE,CAAC;IAEzE;;;;OAIG;IACH,YAAY,OAAwC;QAClD,IAAI,CAAC,OAAO,GAAG,OAAO,EAAE,MAAM,CAAC;IACjC,CAAC;IAED;;;;;OAKG;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AE,CAAC;oBACxD,cAAc,GAAG,WAAW,CAAC;oBAC7B,SAAS,GAAG,KAAK,CAAC;gBACpB,CAAC;YACH,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;;;OAIG;IACH,mBAAmB;QACjB,MAAM,YAAY,GAAe,EAAE,CAAC;QACpC,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;YACxC,YAAY,CAAC,IAAI,CAAC,GAAG,SAAS,CAAC,CAAC;QAClC,CAAC,CAAC,CAAC;QACH,OAAO,YAAY,CAAC;IACtB,CAAC;IAED;;;;OAIG;IACH,gBAAgB;QACd,MAAM,SAAS,GAAY,EAAE,CAAC;QAC9B,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAClC,SAAS,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,CAAC;QAC5B,CAAC,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,CAAC;IAC7B,CAAC;IAED;;;;;;OAMG;IACH,cAAc,CACZ,MAAc,EACd,UAA6B;QAE7B,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACvD,CAAC;IAED;;;;;OAKG;IACH,2BAA2B,CACzB,MAAc;QAEd,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;CACF","sourcesContent":["/**\n * SubscriptionMultiplexer - Manages WebSocket subscriptions across multiple providers\n *\n * Responsibilities:\n * - Manage subscriptions to multiple providers simultaneously\n * - Tag all updates with providerId so UI can differentiate sources\n * - Support aggregation modes: 'merge' (all prices) or 'best_price' (best price per symbol)\n * - Cache latest updates per provider per symbol for aggregation\n */\n\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport type {\n PerpsProviderType,\n PerpsProvider,\n PerpsLogger,\n PriceUpdate,\n Position,\n Order,\n AccountState,\n SubscribePricesParams,\n SubscribePositionsParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribeAccountParams,\n} from '../types/index.js';\nimport { ensureError } from '../utils/errorUtils.js';\n\n/**\n * Options for constructing SubscriptionMultiplexer\n */\nexport type SubscriptionMultiplexerOptions = {\n /** Optional logger for error reporting (e.g., Sentry) */\n logger?: PerpsLogger;\n};\n\n/**\n * Aggregation mode for price subscriptions\n */\nexport type PriceAggregationMode = 'merge' | 'best_price';\n\n/**\n * Parameters for multiplexed price subscriptions\n */\nexport type MultiplexedPricesParams = {\n /** Symbols to subscribe to */\n symbols: string[];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated price updates */\n callback: (prices: PriceUpdate[]) => void;\n /** Aggregation mode: 'merge' returns all prices, 'best_price' returns best per symbol */\n aggregationMode?: PriceAggregationMode;\n /** Optional throttle in milliseconds */\n throttleMs?: number;\n /** Include order book data */\n includeOrderBook?: boolean;\n /** Include market data (funding, OI, volume) */\n includeMarketData?: boolean;\n};\n\n/**\n * Parameters for multiplexed position subscriptions\n */\nexport type MultiplexedPositionsParams = {\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated position updates */\n callback: (positions: Position[]) => void;\n};\n\n/**\n * Parameters for multiplexed order fill subscriptions\n */\nexport type MultiplexedOrderFillsParams = {\n /** Report provider errors without emitting a fabricated empty snapshot. */\n onError?: SubscribeOrderFillsParams['onError'];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated order fill updates */\n callback: SubscribeOrderFillsParams['callback'];\n};\n\n/**\n * Parameters for multiplexed order subscriptions\n */\nexport type MultiplexedOrdersParams = {\n /** Report provider errors without emitting a fabricated empty snapshot. */\n onError?: SubscribeOrdersParams['onError'];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated order updates */\n callback: SubscribeOrdersParams['callback'];\n};\n\n/**\n * Parameters for multiplexed account subscriptions\n */\nexport type MultiplexedAccountParams = {\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive account updates (one per provider) */\n callback: (accounts: AccountState[]) => void;\n};\n\n/**\n * SubscriptionMultiplexer manages real-time data subscriptions across\n * multiple perps providers.\n *\n * Key features:\n * - Subscribes to all providers simultaneously\n * - Tags all updates with source providerId\n * - Caches latest values for aggregation\n * - Supports different aggregation modes for prices\n *\n * @example\n * ```typescript\n * const mux = new SubscriptionMultiplexer();\n *\n * const unsubscribe = mux.subscribeToPrices({\n * symbols: ['BTC', 'ETH'],\n * providers: [\n * ['hyperliquid', hlProvider],\n * ['lighter', lighterProvider],\n * ],\n * callback: (prices) => {\n * // prices have providerId injected\n * prices.forEach(p => console.log(`${p.providerId}: ${p.symbol} = ${p.price}`));\n * },\n * aggregationMode: 'merge',\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\nexport class SubscriptionMultiplexer {\n /**\n * Optional logger for error reporting\n */\n readonly #logger?: PerpsLogger;\n\n /**\n * Cache of latest prices per symbol per provider\n * Map<symbol, Map<providerId, PriceUpdate>>\n */\n readonly #priceCache: Map<string, Map<PerpsProviderType, PriceUpdate>> =\n new Map();\n\n /**\n * Cache of latest positions per provider\n * Map<providerId, Position[]>\n */\n readonly #positionCache: Map<PerpsProviderType, Position[]> = new Map();\n\n /**\n * Cache of latest orders per provider\n * Map<providerId, Order[]>\n */\n readonly #orderCache: Map<PerpsProviderType, Order[]> = new Map();\n\n /**\n * Cache of latest account state per provider\n * Map<providerId, AccountState>\n */\n readonly #accountCache: Map<PerpsProviderType, AccountState> = new Map();\n\n /**\n * Create a new SubscriptionMultiplexer.\n *\n * @param options - Optional configuration including logger for error reporting\n */\n constructor(options?: SubscriptionMultiplexerOptions) {\n this.#logger = options?.logger;\n }\n\n /**\n * Subscribe to price updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToPrices(params: MultiplexedPricesParams): () => void {\n const {\n symbols,\n providers,\n callback,\n aggregationMode = 'merge',\n throttleMs,\n includeOrderBook,\n includeMarketData,\n } = params;\n\n const unsubscribers: (() => void)[] = [];\n\n // Subscribe to each provider with defensive error handling\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribePricesParams = {\n symbols,\n callback: (updates) => {\n // Tag and cache each update\n updates.forEach((update) => {\n const taggedUpdate: PriceUpdate = { ...update, providerId };\n\n // Initialize symbol cache if needed\n if (!this.#priceCache.has(update.symbol)) {\n this.#priceCache.set(update.symbol, new Map());\n }\n const symbolCache = this.#priceCache.get(update.symbol);\n if (symbolCache) {\n symbolCache.set(providerId, taggedUpdate);\n }\n });\n\n // Aggregate and emit based on mode\n const aggregated = this.#aggregatePrices(symbols, aggregationMode);\n callback(aggregated);\n },\n throttleMs,\n includeOrderBook,\n includeMarketData,\n };\n\n const unsub = provider.subscribeToPrices(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n // Log to Sentry before cleanup\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToPrices'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToPrices',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n\n // Clean up any subscriptions created before the failure\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n // Return combined unsubscribe function\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n // Optionally clear cache for these symbols\n symbols.forEach((symbol) => {\n this.#priceCache.delete(symbol);\n });\n };\n }\n\n /**\n * Subscribe to position updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToPositions(params: MultiplexedPositionsParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribePositionsParams = {\n callback: (positions) => {\n // Tag positions with providerId and cache\n const taggedPositions = positions.map((pos) => ({\n ...pos,\n providerId,\n }));\n this.#positionCache.set(providerId, taggedPositions);\n\n // Emit aggregated positions from all providers\n const allPositions = this.#aggregatePositions();\n callback(allPositions);\n },\n };\n\n const unsub = provider.subscribeToPositions(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToPositions'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToPositions',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n // Clear position cache for these providers\n providers.forEach(([providerId]) => {\n this.#positionCache.delete(providerId);\n });\n };\n }\n\n /**\n * Subscribe to order fill updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToOrderFills(params: MultiplexedOrderFillsParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeOrderFillsParams = {\n onError: (error) => params.onError?.(error, providerId),\n callback: (fills, isSnapshot) => {\n // Tag fills with providerId\n const taggedFills = fills.map((fill) => ({\n ...fill,\n providerId,\n }));\n\n // For fills, we don't aggregate - emit immediately with tags\n callback(taggedFills, isSnapshot, providerId);\n },\n };\n\n const unsub = provider.subscribeToOrderFills(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToOrderFills'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToOrderFills',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribe to order updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToOrders(params: MultiplexedOrdersParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeOrdersParams = {\n onError: (error) => params.onError?.(error, providerId),\n callback: (orders) => {\n // Tag orders with providerId and cache\n const taggedOrders = orders.map((order) => ({\n ...order,\n providerId,\n }));\n this.#orderCache.set(providerId, taggedOrders);\n\n // Emit aggregated orders from all providers\n const allOrders = this.#aggregateOrders();\n callback(allOrders, providerId);\n },\n };\n\n const unsub = provider.subscribeToOrders(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToOrders'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToOrders',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n providers.forEach(([providerId]) => {\n this.#orderCache.delete(providerId);\n });\n };\n }\n\n /**\n * Subscribe to account updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToAccount(params: MultiplexedAccountParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeAccountParams = {\n callback: (account) => {\n if (account === null) {\n this.#accountCache.delete(providerId);\n } else {\n // Tag account with providerId and cache\n const taggedAccount: AccountState = {\n ...account,\n providerId,\n };\n this.#accountCache.set(providerId, taggedAccount);\n }\n\n // Emit all cached account states\n const allAccounts = Array.from(this.#accountCache.values());\n callback(allAccounts);\n },\n };\n\n const unsub = provider.subscribeToAccount(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToAccount'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToAccount',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n providers.forEach(([providerId]) => {\n this.#accountCache.delete(providerId);\n });\n };\n }\n\n /**\n * Aggregate cached prices based on mode.\n *\n * @param symbols - Symbols to include in result\n * @param mode - Aggregation mode\n * @returns Aggregated price updates\n */\n #aggregatePrices(\n symbols: string[],\n mode: PriceAggregationMode,\n ): PriceUpdate[] {\n const result: PriceUpdate[] = [];\n\n symbols.forEach((symbol) => {\n const providerPrices = this.#priceCache.get(symbol);\n if (!providerPrices || providerPrices.size === 0) {\n return;\n }\n\n if (mode === 'merge') {\n // Return all prices (one per provider)\n providerPrices.forEach((price) => {\n result.push(price);\n });\n } else {\n // 'best_price': Return the best price across providers\n const best = this.#findBestPrice(providerPrices);\n if (best) {\n result.push(best);\n }\n }\n });\n\n return result;\n }\n\n /**\n * Find the best price from multiple provider prices.\n * \"Best\" is defined as the price with the smallest spread.\n *\n * @param providerPrices - Map of provider prices for a symbol\n * @returns Best price update or undefined\n */\n #findBestPrice(\n providerPrices: Map<PerpsProviderType, PriceUpdate>,\n ): PriceUpdate | undefined {\n let bestPrice: PriceUpdate | undefined;\n let smallestSpread = Infinity;\n\n providerPrices.forEach((price) => {\n if (price.spread === undefined) {\n // No spread info - just use the first one\n bestPrice ??= price;\n } else {\n // If spread is available, use it to determine best\n const spreadValue = parseFloat(price.spread);\n if (!isNaN(spreadValue) && spreadValue < smallestSpread) {\n smallestSpread = spreadValue;\n bestPrice = price;\n }\n }\n });\n\n return bestPrice;\n }\n\n /**\n * Aggregate positions from all providers.\n *\n * @returns All cached positions\n */\n #aggregatePositions(): Position[] {\n const allPositions: Position[] = [];\n this.#positionCache.forEach((positions) => {\n allPositions.push(...positions);\n });\n return allPositions;\n }\n\n /**\n * Aggregate orders from all providers.\n *\n * @returns All cached orders\n */\n #aggregateOrders(): Order[] {\n const allOrders: Order[] = [];\n this.#orderCache.forEach((orders) => {\n allOrders.push(...orders);\n });\n return allOrders;\n }\n\n /**\n * Clear all cached data.\n */\n clearCache(): void {\n this.#priceCache.clear();\n this.#positionCache.clear();\n this.#orderCache.clear();\n this.#accountCache.clear();\n }\n\n /**\n * Get cached price for a symbol from a specific provider.\n *\n * @param symbol - Market symbol\n * @param providerId - Provider ID\n * @returns Cached price update or undefined\n */\n getCachedPrice(\n symbol: string,\n providerId: PerpsProviderType,\n ): PriceUpdate | undefined {\n return this.#priceCache.get(symbol)?.get(providerId);\n }\n\n /**\n * Get all cached prices for a symbol.\n *\n * @param symbol - Market symbol\n * @returns Map of provider ID to price update\n */\n getAllCachedPricesForSymbol(\n symbol: string,\n ): Map<PerpsProviderType, PriceUpdate> | undefined {\n return this.#priceCache.get(symbol);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SubscriptionMultiplexer.js","sourceRoot":"","sources":["../../src/aggregation/SubscriptionMultiplexer.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAe9D,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAoFrD;;;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AED;;;;OAIG;IACH,gBAAgB;QACd,MAAM,SAAS,GAAY,EAAE,CAAC;QAC9B,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;YAClC,SAAS,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,CAAC;QAC5B,CAAC,CAAC,CAAC;QACH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED;;OAEG;IACH,UAAU;QACR,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;QACzB,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAC;QAC5B,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,CAAC;IAC3B,CAAC;IAED;;;;;;OAMG;IACH,cAAc,CACZ,MAAc,EACd,UAA6B;QAE7B,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC,CAAC;IACvD,CAAC;IAED;;;;;OAKG;IACH,2BAA2B,CACzB,MAAc;QAEd,OAAO,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IACtC,CAAC;CACF","sourcesContent":["/**\n * SubscriptionMultiplexer - Manages WebSocket subscriptions across multiple providers\n *\n * Responsibilities:\n * - Manage subscriptions to multiple providers simultaneously\n * - Tag all updates with providerId so UI can differentiate sources\n * - Support aggregation modes: 'merge' (all prices) or 'best_price' (best price per symbol)\n * - Cache latest updates per provider per symbol for aggregation\n */\n\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig.js';\nimport type {\n PerpsProviderType,\n PerpsProvider,\n PerpsLogger,\n PriceUpdate,\n Position,\n Order,\n AccountState,\n SubscribePricesParams,\n SubscribePositionsParams,\n SubscribeOrderFillsParams,\n SubscribeOrdersParams,\n SubscribeAccountParams,\n} from '../types/index.js';\nimport { ensureError } from '../utils/errorUtils.js';\n\n/**\n * Options for constructing SubscriptionMultiplexer\n */\nexport type SubscriptionMultiplexerOptions = {\n /** Optional logger for error reporting (e.g., Sentry) */\n logger?: PerpsLogger;\n};\n\n/**\n * Aggregation mode for price subscriptions\n */\nexport type PriceAggregationMode = 'merge' | 'best_price';\n\n/**\n * Parameters for multiplexed price subscriptions\n */\nexport type MultiplexedPricesParams = {\n /** Symbols to subscribe to */\n symbols: string[];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated price updates */\n callback: (prices: PriceUpdate[]) => void;\n /** Aggregation mode: 'merge' returns all prices, 'best_price' returns best per symbol */\n aggregationMode?: PriceAggregationMode;\n /** Optional throttle in milliseconds */\n throttleMs?: number;\n /** Include order book data */\n includeOrderBook?: boolean;\n /** Include market data (funding, OI, volume) */\n includeMarketData?: boolean;\n};\n\n/**\n * Parameters for multiplexed position subscriptions\n */\nexport type MultiplexedPositionsParams = {\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated position updates */\n callback: (positions: Position[]) => void;\n};\n\n/**\n * Parameters for multiplexed order fill subscriptions\n */\nexport type MultiplexedOrderFillsParams = {\n /** Report provider errors without emitting a fabricated empty snapshot. */\n onError?: SubscribeOrderFillsParams['onError'];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated order fill updates */\n callback: SubscribeOrderFillsParams['callback'];\n};\n\n/**\n * Parameters for multiplexed order subscriptions\n */\nexport type MultiplexedOrdersParams = {\n /** Report provider errors without emitting a fabricated empty snapshot. */\n onError?: SubscribeOrdersParams['onError'];\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive aggregated order updates */\n callback: SubscribeOrdersParams['callback'];\n};\n\n/**\n * Parameters for multiplexed account subscriptions\n */\nexport type MultiplexedAccountParams = {\n /** Keep healthy venue streams when setup fails; the next emission excludes the failed venue. */\n onError?: (error: Error, providerId: PerpsProviderType) => void;\n /** Optional account identity forwarded to every provider. */\n accountId?: SubscribeAccountParams['accountId'];\n /** Ask every provider for a complete account or `null`, never a partial one. */\n requireCompleteAccount?: boolean;\n /** Provider instances to subscribe through */\n providers: [PerpsProviderType, PerpsProvider][];\n /** Callback to receive account updates (one entry per provider with data) */\n callback: (accounts: AccountState[]) => void;\n};\n/**\n * SubscriptionMultiplexer manages real-time data subscriptions across\n * multiple perps providers.\n *\n * Key features:\n * - Subscribes to all providers simultaneously\n * - Tags all updates with source providerId\n * - Caches latest values for aggregation\n * - Supports different aggregation modes for prices\n *\n * @example\n * ```typescript\n * const mux = new SubscriptionMultiplexer();\n *\n * const unsubscribe = mux.subscribeToPrices({\n * symbols: ['BTC', 'ETH'],\n * providers: [\n * ['hyperliquid', hlProvider],\n * ['lighter', lighterProvider],\n * ],\n * callback: (prices) => {\n * // prices have providerId injected\n * prices.forEach(p => console.log(`${p.providerId}: ${p.symbol} = ${p.price}`));\n * },\n * aggregationMode: 'merge',\n * });\n *\n * // Later: clean up\n * unsubscribe();\n * ```\n */\nexport class SubscriptionMultiplexer {\n /**\n * Optional logger for error reporting\n */\n readonly #logger?: PerpsLogger;\n\n /**\n * Cache of latest prices per symbol per provider\n * Map<symbol, Map<providerId, PriceUpdate>>\n */\n readonly #priceCache: Map<string, Map<PerpsProviderType, PriceUpdate>> =\n new Map();\n\n /**\n * Cache of latest positions per provider\n * Map<providerId, Position[]>\n */\n readonly #positionCache: Map<PerpsProviderType, Position[]> = new Map();\n\n /**\n * Cache of latest orders per provider\n * Map<providerId, Order[]>\n */\n readonly #orderCache: Map<PerpsProviderType, Order[]> = new Map();\n\n /**\n * Create a new SubscriptionMultiplexer.\n *\n * @param options - Optional configuration including logger for error reporting\n */\n constructor(options?: SubscriptionMultiplexerOptions) {\n this.#logger = options?.logger;\n }\n\n /**\n * Subscribe to price updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToPrices(params: MultiplexedPricesParams): () => void {\n const {\n symbols,\n providers,\n callback,\n aggregationMode = 'merge',\n throttleMs,\n includeOrderBook,\n includeMarketData,\n } = params;\n\n const unsubscribers: (() => void)[] = [];\n\n // Subscribe to each provider with defensive error handling\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribePricesParams = {\n symbols,\n callback: (updates) => {\n // Tag and cache each update\n updates.forEach((update) => {\n const taggedUpdate: PriceUpdate = { ...update, providerId };\n\n // Initialize symbol cache if needed\n if (!this.#priceCache.has(update.symbol)) {\n this.#priceCache.set(update.symbol, new Map());\n }\n const symbolCache = this.#priceCache.get(update.symbol);\n if (symbolCache) {\n symbolCache.set(providerId, taggedUpdate);\n }\n });\n\n // Aggregate and emit based on mode\n const aggregated = this.#aggregatePrices(symbols, aggregationMode);\n callback(aggregated);\n },\n throttleMs,\n includeOrderBook,\n includeMarketData,\n };\n\n const unsub = provider.subscribeToPrices(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n // Log to Sentry before cleanup\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToPrices'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToPrices',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n\n // Clean up any subscriptions created before the failure\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n // Return combined unsubscribe function\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n // Optionally clear cache for these symbols\n symbols.forEach((symbol) => {\n this.#priceCache.delete(symbol);\n });\n };\n }\n\n /**\n * Subscribe to position updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToPositions(params: MultiplexedPositionsParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribePositionsParams = {\n callback: (positions) => {\n // Tag positions with providerId and cache\n const taggedPositions = positions.map((pos) => ({\n ...pos,\n providerId,\n }));\n this.#positionCache.set(providerId, taggedPositions);\n\n // Emit aggregated positions from all providers\n const allPositions = this.#aggregatePositions();\n callback(allPositions);\n },\n };\n\n const unsub = provider.subscribeToPositions(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToPositions'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToPositions',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n // Clear position cache for these providers\n providers.forEach(([providerId]) => {\n this.#positionCache.delete(providerId);\n });\n };\n }\n\n /**\n * Subscribe to order fill updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToOrderFills(params: MultiplexedOrderFillsParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeOrderFillsParams = {\n onError: (error) => params.onError?.(error, providerId),\n callback: (fills, isSnapshot) => {\n // Tag fills with providerId\n const taggedFills = fills.map((fill) => ({\n ...fill,\n providerId,\n }));\n\n // For fills, we don't aggregate - emit immediately with tags\n callback(taggedFills, isSnapshot, providerId);\n },\n };\n\n const unsub = provider.subscribeToOrderFills(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToOrderFills'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToOrderFills',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n };\n }\n\n /**\n * Subscribe to order updates from multiple providers.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToOrders(params: MultiplexedOrdersParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeOrdersParams = {\n onError: (error) => params.onError?.(error, providerId),\n callback: (orders) => {\n // Tag orders with providerId and cache\n const taggedOrders = orders.map((order) => ({\n ...order,\n providerId,\n }));\n this.#orderCache.set(providerId, taggedOrders);\n\n // Emit aggregated orders from all providers\n const allOrders = this.#aggregateOrders();\n callback(allOrders, providerId);\n },\n };\n\n const unsub = provider.subscribeToOrders(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToOrders'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToOrders',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n providers.forEach(([providerId]) => {\n this.#orderCache.delete(providerId);\n });\n };\n }\n\n /**\n * Subscribe to account updates from multiple providers.\n *\n * Each subscription owns its cache: a venue's latest state is visible only\n * to that subscription, so one subscription's cleanup never erases another\n * subscription's venue data, and a subscription starts empty regardless of\n * other live account streams.\n *\n * @param params - Subscription parameters\n * @returns Unsubscribe function\n */\n subscribeToAccount(params: MultiplexedAccountParams): () => void {\n const { providers, callback } = params;\n const unsubscribers: (() => void)[] = [];\n // Per-subscription cache: latest state per venue for THIS subscription.\n const accountCache: Map<PerpsProviderType, AccountState> = new Map();\n\n for (const [providerId, provider] of providers) {\n try {\n const subscribeParams: SubscribeAccountParams = {\n ...(params.accountId !== undefined && {\n accountId: params.accountId,\n }),\n ...(params.requireCompleteAccount === true && {\n requireCompleteAccount: true,\n }),\n callback: (account) => {\n if (account === null) {\n // The venue's balance is no longer known. Drop its previous\n // value: it must not stay in the aggregate as current, and it\n // must not become a zero.\n accountCache.delete(providerId);\n } else {\n // Tag account with providerId and cache\n const taggedAccount: AccountState = {\n ...account,\n providerId,\n };\n accountCache.set(providerId, taggedAccount);\n }\n\n // Emit this subscription's cached account states\n const allAccounts = Array.from(accountCache.values());\n callback(allAccounts);\n },\n };\n\n const unsub = provider.subscribeToAccount(subscribeParams);\n unsubscribers.push(unsub);\n } catch (error) {\n this.#logger?.error(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToAccount'),\n {\n tags: {\n feature: PERPS_CONSTANTS.FeatureName,\n provider: providerId,\n method: 'subscribeToAccount',\n },\n context: {\n name: 'SubscriptionMultiplexer',\n data: { subscribedCount: unsubscribers.length },\n },\n },\n );\n if (params.onError) {\n accountCache.delete(providerId);\n params.onError(\n ensureError(error, 'SubscriptionMultiplexer.subscribeToAccount'),\n providerId,\n );\n callback(Array.from(accountCache.values()));\n continue;\n }\n unsubscribers.forEach((unsub) => unsub());\n throw error;\n }\n }\n\n return () => {\n unsubscribers.forEach((unsub) => unsub());\n // The cache is per-subscription: nothing shared to clear.\n };\n }\n\n /**\n * Aggregate cached prices based on mode.\n *\n * @param symbols - Symbols to include in result\n * @param mode - Aggregation mode\n * @returns Aggregated price updates\n */\n #aggregatePrices(\n symbols: string[],\n mode: PriceAggregationMode,\n ): PriceUpdate[] {\n const result: PriceUpdate[] = [];\n\n symbols.forEach((symbol) => {\n const providerPrices = this.#priceCache.get(symbol);\n if (!providerPrices || providerPrices.size === 0) {\n return;\n }\n\n if (mode === 'merge') {\n // Return all prices (one per provider)\n providerPrices.forEach((price) => {\n result.push(price);\n });\n } else {\n // 'best_price': Return the best price across providers\n const best = this.#findBestPrice(providerPrices);\n if (best) {\n result.push(best);\n }\n }\n });\n\n return result;\n }\n\n /**\n * Find the best price from multiple provider prices.\n * \"Best\" is defined as the price with the smallest spread.\n *\n * @param providerPrices - Map of provider prices for a symbol\n * @returns Best price update or undefined\n */\n #findBestPrice(\n providerPrices: Map<PerpsProviderType, PriceUpdate>,\n ): PriceUpdate | undefined {\n let bestPrice: PriceUpdate | undefined;\n let smallestSpread = Infinity;\n\n providerPrices.forEach((price) => {\n if (price.spread === undefined) {\n // No spread info - just use the first one\n bestPrice ??= price;\n } else {\n // If spread is available, use it to determine best\n const spreadValue = parseFloat(price.spread);\n if (!isNaN(spreadValue) && spreadValue < smallestSpread) {\n smallestSpread = spreadValue;\n bestPrice = price;\n }\n }\n });\n\n return bestPrice;\n }\n\n /**\n * Aggregate positions from all providers.\n *\n * @returns All cached positions\n */\n #aggregatePositions(): Position[] {\n const allPositions: Position[] = [];\n this.#positionCache.forEach((positions) => {\n allPositions.push(...positions);\n });\n return allPositions;\n }\n\n /**\n * Aggregate orders from all providers.\n *\n * @returns All cached orders\n */\n #aggregateOrders(): Order[] {\n const allOrders: Order[] = [];\n this.#orderCache.forEach((orders) => {\n allOrders.push(...orders);\n });\n return allOrders;\n }\n\n /**\n * Clear all cached data.\n */\n clearCache(): void {\n this.#priceCache.clear();\n this.#positionCache.clear();\n this.#orderCache.clear();\n }\n\n /**\n * Get cached price for a symbol from a specific provider.\n *\n * @param symbol - Market symbol\n * @param providerId - Provider ID\n * @returns Cached price update or undefined\n */\n getCachedPrice(\n symbol: string,\n providerId: PerpsProviderType,\n ): PriceUpdate | undefined {\n return this.#priceCache.get(symbol)?.get(providerId);\n }\n\n /**\n * Get all cached prices for a symbol.\n *\n * @param symbol - Market symbol\n * @returns Map of provider ID to price update\n */\n getAllCachedPricesForSymbol(\n symbol: string,\n ): Map<PerpsProviderType, PriceUpdate> | undefined {\n return this.#priceCache.get(symbol);\n }\n}\n"]}
|
|
@@ -165,6 +165,8 @@ export declare const CAIP_ASSET_NAMESPACES: {
|
|
|
165
165
|
*/
|
|
166
166
|
export declare const HYPERLIQUID_CONFIG: {
|
|
167
167
|
readonly ExchangeName: 'HlPerp';
|
|
168
|
+
readonly DexDiscoveryInitialWaitMs: 5000;
|
|
169
|
+
readonly DexDiscoveryRetryDelayMs: 5000;
|
|
168
170
|
readonly OraclePriceDeviationLimit: 0.95;
|
|
169
171
|
};
|
|
170
172
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidConfig.d.ts","sourceRoot":"","sources":["../../src/constants/hyperLiquidConfig.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAGrE,OAAO,KAAK,EAEV,UAAU,EACX,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EAEV,oBAAoB,EACpB,uBAAuB,EACvB,oBAAoB,EACpB,0BAA0B,EAC1B,0BAA0B,EAC1B,qBAAqB,EACrB,cAAc,EACf,MAAM,yBAAyB,CAAC;AAajC,eAAO,MAAM,6BAA6B,EAAG,QAAiB,CAAC;AAC/D,eAAO,MAAM,yBAAyB,UAAU,CAAC;AACjD,eAAO,MAAM,yBAAyB,WAAW,CAAC;AAClD,eAAO,MAAM,8BAA8B,iBAAwC,CAAC;AACpF,eAAO,MAAM,8BAA8B,kBAAwC,CAAC;AAGpF,eAAO,MAAM,4BAA4B,UAAU,CAAC;AACpD,eAAO,MAAM,4BAA4B,UAAU,CAAC;AACpD,eAAO,MAAM,iCAAiC,EAAmB,WAAW,CAAC;AAC7E,eAAO,MAAM,iCAAiC,EAAmB,WAAW,CAAC;AAC7E,eAAO,MAAM,wBAAwB,gBAAgB,CAAC;AAEtD;;;;;GAKG;AACH,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,GACtB,MAAM,EAAE,CAIV;AAGD,eAAO,MAAM,WAAW,SAAS,CAAC;AAClC,eAAO,MAAM,SAAS,aAAa,CAAC;AACpC,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,cAAc,KAAK,CAAC;AAGjC,eAAO,MAAM,yBAAyB,YAAY,CAAC;AAGnD,eA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;;;GAoBG;AACH,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAwF9D,CAAC;AAEF;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAwI1D,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,uBAAuB,CACrC,MAAM,EAAE,MAAM,EACd,KAAK,GAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAA2B,GACtD,MAAM,CAER;AAED;;;;;;GAMG;AACH,eAAO,MAAM,mBAAmB;IAC9B;;;;OAIG;aACH,WAAW,EAAa,MAAM,EAAE;IAEhC;;;OAGG;aACH,eAAe;CACP,CAAC;AAEX;;;;;;;;;GASG;AACH,eAAO,MAAM,mBAAmB;IAC9B;;;;OAIG;aACH,eAAe;CACP,CAAC;AAEX;;;GAGG;AACH,eAAO,MAAM,8BAA8B,YACzC,QAAQ,EACR,gBAAgB,EAChB,SAAS,CACD,CAAC;AAEX;;;;;;;GAOG;AACH,wBAAgB,wBAAwB,CACtC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACpC,UAAU,IAAI,QAAQ,GAAG,IAAI,GAAG,SAAS,CAI3C;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB;IAC7B;;;OAGG;aACH,gBAAgB,EAAE,KAAK;IAEvB;;;OAGG;aACH,sBAAsB,EAAE,GAAG;IAE3B;;;OAGG;aACH,qBAAqB,EAAE,GAAG;CAClB,CAAC;AAGX,eAAO,MAAM,0BAA0B,KAAK,CAAC;AAC7C,eAAO,MAAM,0BAA0B,UAEtC,CAAC;AACF,eAAO,MAAM,gCAAgC,MAAM,CAAC"}
|
|
@@ -258,6 +258,8 @@ export const HYPERLIQUID_CONFIG = {
|
|
|
258
258
|
// Exchange name used in predicted funding data
|
|
259
259
|
// HyperLiquid uses 'HlPerp' as their perps exchange identifier
|
|
260
260
|
ExchangeName: 'HlPerp',
|
|
261
|
+
DexDiscoveryInitialWaitMs: 5000,
|
|
262
|
+
DexDiscoveryRetryDelayMs: 5000,
|
|
261
263
|
// Maximum allowed deviation of the market (mid) price from the oracle (reference)
|
|
262
264
|
// price before HyperLiquid rejects orders. HyperLiquid enforces "Order price cannot
|
|
263
265
|
// be more than 95% away from the reference price", which makes markets — most often
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hyperLiquidConfig.js","sourceRoot":"","sources":["../../src/constants/hyperLiquidConfig.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAenD,OAAO,EACL,iBAAiB,EACjB,oBAAoB,EACpB,mBAAmB,GACpB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACvB,eAAe,GAChB,MAAM,kBAAkB,CAAC;AAE1B,oBAAoB;AACpB,MAAM,CAAC,MAAM,6BAA6B,GAAG,QAAiB,CAAC;AAC/D,MAAM,CAAC,MAAM,yBAAyB,GAAG,OAAO,CAAC;AACjD,MAAM,CAAC,MAAM,yBAAyB,GAAG,QAAQ,CAAC;AAClD,MAAM,CAAC,MAAM,8BAA8B,GAAG,UAAU,yBAAyB,EAAE,CAAC;AACpF,MAAM,CAAC,MAAM,8BAA8B,GAAG,UAAU,yBAAyB,EAAE,CAAC;AAEpF,8BAA8B;AAC9B,MAAM,CAAC,MAAM,4BAA4B,GAAG,OAAO,CAAC,CAAC,iBAAiB;AACtE,MAAM,CAAC,MAAM,4BAA4B,GAAG,OAAO,CAAC,CAAC,2BAA2B;AAChF,MAAM,CAAC,MAAM,iCAAiC,GAAG,YAA2B,CAAC;AAC7E,MAAM,CAAC,MAAM,iCAAiC,GAAG,YAA2B,CAAC;AAC7E,MAAM,CAAC,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAEtD;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,KAAuB;IAEvB,MAAM,eAAe,GAA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ory } from '../types/index.js';\nimport type {\n DirectProviderOrderCapabilities,\n MarketType,\n} from '../types/index.js';\nimport type {\n HyperLiquidNetwork,\n HyperLiquidEndpoints,\n HyperLiquidAssetConfigs,\n BridgeContractConfig,\n HyperLiquidBridgeContracts,\n HyperLiquidTransportConfig,\n TradingDefaultsConfig,\n FeeRatesConfig,\n} from '../types/perps-types.js';\nimport {\n SCALE_ORDER_COUNT,\n STRATEGY_ORDER_TYPES,\n TRIGGER_ORDER_TYPES,\n} from '../utils/orderTypes.js';\nimport {\n CHASE_ORDER_CONFIG,\n HYPERLIQUID_TWAP_LIMITS,\n PROVIDER_CONFIG,\n} from './perpsConfig.js';\n\n// Network constants\nexport const ARBITRUM_MAINNET_CHAIN_ID_HEX = '0xa4b1' as const;\nexport const ARBITRUM_MAINNET_CHAIN_ID = '42161';\nexport const ARBITRUM_TESTNET_CHAIN_ID = '421614';\nexport const ARBITRUM_MAINNET_CAIP_CHAIN_ID = `eip155:${ARBITRUM_MAINNET_CHAIN_ID}`;\nexport const ARBITRUM_TESTNET_CAIP_CHAIN_ID = `eip155:${ARBITRUM_TESTNET_CHAIN_ID}`;\n\n// Hyperliquid chain constants\nexport const HYPERLIQUID_MAINNET_CHAIN_ID = '0x3e7'; // 999 in decimal\nexport const HYPERLIQUID_TESTNET_CHAIN_ID = '0x3e6'; // 998 in decimal (assumed)\nexport const HYPERLIQUID_MAINNET_CAIP_CHAIN_ID = 'eip155:999' as CaipChainId;\nexport const HYPERLIQUID_TESTNET_CAIP_CHAIN_ID = 'eip155:998' as CaipChainId;\nexport const HYPERLIQUID_NETWORK_NAME = 'Hyperliquid';\n\n/**\n * Return the canonical snapshot identity: main first, then unique DEX ids.\n *\n * @param dexes - DEX identifiers to canonicalize.\n * @returns The canonical DEX identifiers.\n */\nexport function canonicalizeHyperLiquidDexes(\n dexes: Iterable<string>,\n): string[] {\n const additionalDexes = new Set(dexes);\n additionalDexes.delete('main');\n return ['main', ...Array.from(additionalDexes).sort()];\n}\n\n// Token constants\nexport const USDC_SYMBOL = 'USDC';\nexport const USDC_NAME = 'USD Coin';\nexport const USDC_DECIMALS = 6;\nexport const TOKEN_DECIMALS = 18;\n\n// Network constants\nexport const ARBITRUM_SEPOLIA_CHAIN_ID = '0x66eee'; // 421614 in decimal\n\n// USDC token addresses\nexport const USDC_ETHEREUM_MAINNET_ADDRESS =\n '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';\nexport const USDC_ARBITRUM_MAINNET_ADDRESS =\n '0xaf88d065e77c8cC2239327C5EDb3A432268e5831';\n// USDC2: the token the Arbitrum Sepolia bridge credits (its usdcToken())\nexport const USDC_ARBITRUM_TESTNET_ADDRESS =\n '0x1baAbB04529D43a73232B713C0FE471f7c7334d5';\n\n// USDC token icon URL using MetaMask's official Token Icons API\n// Format: https://static.cx.metamask.io/api/v1/tokenIcons/{chainId}/{contractAddress}.png\n// This URL follows the same pattern used throughout MetaMask (bridges, swaps, etc.)\nexport const USDC_TOKEN_ICON_URL = `https://static.cx.metamask.io/api/v1/tokenIcons/1/${USDC_ETHEREUM_MAINNET_ADDRESS}.png`;\n\n// WebSocket endpoints\nexport const HYPERLIQUID_ENDPOINTS: HyperLiquidEndpoints = {\n mainnet: 'wss://api.hyperliquid.xyz/ws',\n testnet: 'wss://api.hyperliquid-testnet.xyz/ws',\n};\n\n// Asset icons base URL (HyperLiquid CDN - fallback source)\nexport const HYPERLIQUID_ASSET_ICONS_BASE_URL =\n 'https://app.hyperliquid.xyz/coins/';\n\n// MetaMask-hosted Perps asset icons (primary source)\n// Assets uploaded to: https://github.com/MetaMask/contract-metadata/tree/master/icons/eip155:999\n// HIP-3 assets use format: hip3:dex_SYMBOL.svg (e.g., hip3:xyz_AAPL.svg)\n// Regular assets use format: SYMBOL.svg (e.g., BTC.svg)\nexport const METAMASK_PERPS_ICONS_BASE_URL =\n 'https://raw.githubusercontent.com/MetaMask/contract-metadata/master/icons/eip155:999/';\n\n// Asset configurations for multichain abstraction\nexport const HYPERLIQUID_ASSET_CONFIGS: HyperLiquidAssetConfigs = {\n usdc: {\n mainnet: `${ARBITRUM_MAINNET_CAIP_CHAIN_ID}/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831/default`,\n testnet: `${ARBITRUM_TESTNET_CAIP_CHAIN_ID}/erc20:0x1baAbB04529D43a73232B713C0FE471f7c7334d5/default`,\n },\n};\n\n// HyperLiquid bridge contract addresses for direct USDC deposits\n// These are the official bridge contracts where USDC must be sent to credit user's HyperLiquid account\nexport const HYPERLIQUID_BRIDGE_CONTRACTS: HyperLiquidBridgeContracts = {\n mainnet: {\n chainId: ARBITRUM_MAINNET_CAIP_CHAIN_ID,\n contractAddress: '0x2df1c51e09aecf9cacb7bc98cb1742757f163df7',\n },\n testnet: {\n chainId: ARBITRUM_TESTNET_CAIP_CHAIN_ID,\n contractAddress: '0x08cfc1B6b2dCF36A1480b99353A354AA8AC56f89',\n },\n};\n\n// SDK transport configuration\nexport const HYPERLIQUID_TRANSPORT_CONFIG: HyperLiquidTransportConfig = {\n timeout: 10_000,\n keepAlive: { interval: 30_000 },\n reconnect: {\n maxRetries: 5,\n connectionTimeout: 10_000,\n },\n};\n\n// Trading configuration constants\nexport const TRADING_DEFAULTS: TradingDefaultsConfig = {\n leverage: 3, // 3x default leverage\n marginPercent: 10, // 10% fixed margin default\n takeProfitPercent: 0.3, // 30% take profit\n stopLossPercent: 0.1, // 10% stop loss\n amount: {\n mainnet: 10, // $10 minimum order size\n testnet: 10, // $10 minimum order size\n },\n};\n\n// Fee configuration\n// Note: These are base rates (Tier 0, no discounts)\n// Actual fees will be calculated based on user's volume tier and staking\nexport const FEE_RATES: FeeRatesConfig = {\n taker: 0.00045, // 0.045% - Market orders and aggressive limit orders\n maker: 0.00015, // 0.015% - Limit orders that add liquidity\n};\n\n/**\n * HIP-3 dynamic fee calculation configuration\n *\n * HIP-3 (builder-deployed) perpetual markets have variable fees based on:\n * 1. deployerFeeScale - Per-DEX fee multiplier (fetched from perpDexs API)\n * 2. growthMode - Per-asset 90% fee reduction (fetched from meta API)\n *\n * Fee Formula (from HyperLiquid docs):\n * - scaleIfHip3 = deployerFeeScale < 1 ? deployerFeeScale + 1 : deployerFeeScale * 2\n * - growthModeScale = growthMode ? 0.1 : 1\n * - finalRate = baseRate * scaleIfHip3 * growthModeScale\n *\n * Example: For xyz:TSLA with deployerFeeScale=1.0 and growthMode=\"enabled\":\n * - scaleIfHip3 = 1.0 * 2 = 2.0\n * - growthModeScale = 0.1 (90% reduction)\n * - Final multiplier = 2.0 * 0.1 = 0.2 (effectively 80% off standard 2x HIP-3 fees)\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees#fee-formula-for-developers\n * @see parseAssetName() in HyperLiquidProvider for HIP-3 asset detection\n */\nexport const HIP3_FEE_CONFIG = {\n /**\n * Growth Mode multiplier - 90% fee reduction for assets in growth phase\n * This is a protocol constant from HyperLiquid's fee formula\n */\n GrowthModeScale: 0.1,\n\n /**\n * Default deployerFeeScale when API is unavailable\n * Most HIP-3 DEXs use 1.0, which results in 2x base fees\n */\n DefaultDeployerFeeScale: 1.0,\n\n /**\n * Cache TTL for perpDexs data (5 minutes)\n * Fee scales rarely change, so longer cache is acceptable\n */\n PerpDexsCacheTtlMs: 5 * 60 * 1000,\n\n /**\n * @deprecated Use dynamic calculation via calculateHip3FeeMultiplier()\n * Kept for backwards compatibility during migration\n */\n FeeMultiplier: 2,\n} as const;\n\n/**\n * EIP-712 primary type of every HyperLiquid L1 action (orders, cancels,\n * leverage, ...). Only L1 actions may be signed by an agent; every other\n * request is a user-signed action for the main account.\n */\nexport const HYPERLIQUID_L1_ACTION_PRIMARY_TYPE = 'Agent';\n\n/**\n * EIP-712 domain name of every HyperLiquid L1 action.\n */\nexport const HYPERLIQUID_L1_ACTION_DOMAIN_NAME = 'Exchange';\n\nconst BUILDER_FEE_MAX_FEE_DECIMAL = 0.001;\n\n// Builder fee configuration\nexport const BUILDER_FEE_CONFIG = {\n // Test builder wallet\n TestnetBuilder: '0x724e57771ba749650875bd8adb2e29a85d0cacfa' as Hex,\n // Production builder wallet\n MainnetBuilder: '0xe95a5e31904e005066614247d309e00d8ad753aa' as Hex,\n // Fee in decimal (10 bp = 0.1%)\n MaxFeeDecimal: BUILDER_FEE_MAX_FEE_DECIMAL,\n MaxFeeTenthsBps: BUILDER_FEE_MAX_FEE_DECIMAL * 100000,\n MaxFeeRate: `${(BUILDER_FEE_MAX_FEE_DECIMAL * 100)\n .toFixed(4)\n .replace(/\\.?0+$/u, '')}%`,\n};\n\n/**\n * Strategies and standalone trigger orders HyperLiquid executes for its markets.\n * Providers own this declaration so clients never infer support from a\n * provider name.\n */\nexport const HYPERLIQUID_ORDER_CAPABILITIES = Object.freeze({\n status: 'ready',\n providerId: PROVIDER_CONFIG.DefaultProvider,\n supportedStrategies: Object.freeze([...STRATEGY_ORDER_TYPES]),\n supportedTriggerOrderTypes: Object.freeze([...TRIGGER_ORDER_TYPES]),\n strategyRules: Object.freeze({\n twap: Object.freeze({\n minDurationMinutes: HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes,\n maxDurationMinutes: HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes,\n minNotionalUsd: HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd,\n sliceIntervalSeconds: HYPERLIQUID_TWAP_LIMITS.SliceIntervalSeconds,\n }),\n chase: Object.freeze({\n maxActiveSessions: CHASE_ORDER_CONFIG.MaxActiveSessions,\n defaultIntervalMs: CHASE_ORDER_CONFIG.DefaultIntervalMs,\n minIntervalMs: CHASE_ORDER_CONFIG.MinIntervalMs,\n }),\n scale: Object.freeze({\n minOrders: SCALE_ORDER_COUNT.min,\n maxOrders: SCALE_ORDER_COUNT.max,\n }),\n }),\n positionTpsl: Object.freeze({\n supportsExpectedPosition: true,\n childOrderIds: 'request-correlated',\n takeProfitOrderType: 'take_profit_limit',\n stopLossOrderType: 'stop_market',\n defaultCoverage: 'dynamic-position',\n partialCoverage: Object.freeze({\n single: true,\n pair: 'independent',\n replacement: 'cancel-before-create',\n recovery: 'provider-default',\n }),\n }),\n}) satisfies DirectProviderOrderCapabilities;\n\n// Referral code configuration\nexport const REFERRAL_CONFIG = {\n // Production referral code\n MainnetCode: 'MMCSI',\n // Development/testnet referral code\n TestnetCode: 'MMCSITEST',\n};\n\n// Deposit constants\nexport const DEPOSIT_CONFIG = {\n EstimatedGasLimit: 100000, // Estimated gas limit for bridge deposit\n DefaultSlippage: 1, // 1% default slippage for bridge quotes\n BridgeQuoteTimeout: 1000, // 1 second timeout for bridge quotes\n RefreshRate: 30000, // 30 seconds quote refresh rate\n EstimatedTime: {\n DirectDeposit: '3-5 seconds', // Direct USDC deposit on Arbitrum\n SameChainSwap: '30-60 seconds', // Swap on same chain before deposit\n },\n};\n\n// Withdrawal constants (HyperLiquid-specific)\nexport const HYPERLIQUID_WITHDRAWAL_MINUTES = 5; // HyperLiquid withdrawal processing time in minutes\n\n// Type helpers\nexport type SupportedAsset = keyof typeof HYPERLIQUID_ASSET_CONFIGS;\n\n// Configuration helpers\nexport function getWebSocketEndpoint(isTestnet: boolean): string {\n return isTestnet\n ? HYPERLIQUID_ENDPOINTS.testnet\n : HYPERLIQUID_ENDPOINTS.mainnet;\n}\n\nexport function getChainId(isTestnet: boolean): string {\n return isTestnet ? ARBITRUM_TESTNET_CHAIN_ID : ARBITRUM_MAINNET_CHAIN_ID;\n}\n\nexport function getCaipChainId(isTestnet: boolean): CaipChainId {\n const network: HyperLiquidNetwork = isTestnet ? 'testnet' : 'mainnet';\n return HYPERLIQUID_BRIDGE_CONTRACTS[network].chainId;\n}\n\nexport function getBridgeInfo(isTestnet: boolean): BridgeContractConfig {\n const network: HyperLiquidNetwork = isTestnet ? 'testnet' : 'mainnet';\n return HYPERLIQUID_BRIDGE_CONTRACTS[network];\n}\n\nexport function getSupportedAssets(isTestnet?: boolean): CaipAssetId[] {\n const network = isTestnet ? 'testnet' : 'mainnet';\n return Object.values(HYPERLIQUID_ASSET_CONFIGS).map(\n (config) => config[network],\n );\n}\n\n// CAIP asset namespace constants\nexport const CAIP_ASSET_NAMESPACES = {\n Erc20: 'erc20',\n} as const;\n\n/**\n * HyperLiquid protocol-specific configuration\n * Contains constants specific to HyperLiquid's perps exchange\n */\nexport const HYPERLIQUID_CONFIG = {\n // Exchange name used in predicted funding data\n // HyperLiquid uses 'HlPerp' as their perps exchange identifier\n ExchangeName: 'HlPerp',\n // Maximum allowed deviation of the market (mid) price from the oracle (reference)\n // price before HyperLiquid rejects orders. HyperLiquid enforces \"Order price cannot\n // be more than 95% away from the reference price\", which makes markets — most often\n // HIP-3 builder-deployed ones — temporarily untradable when the mid price drifts past\n // this limit. Expressed as a decimal fraction (0.95 = 95%).\n // Protocol rule, not a UI warning threshold (see VALIDATION_THRESHOLDS.PriceDeviation).\n OraclePriceDeviationLimit: 0.95,\n} as const;\n\n/**\n * HIP-3 multi-DEX asset ID calculation constants\n * Per HIP-3-IMPLEMENTATION.md:\n * - Main DEX: assetId = index (0, 1, 2, ...)\n * - HIP-3 DEX: assetId = BASE_ASSET_ID + (perpDexIndex × DEX_MULTIPLIER) + index\n *\n * This formula enables proper order routing across multiple DEXs:\n * - Main DEX (perpDexIndex=0): Uses index directly (BTC=0, ETH=1, SOL=2, etc.)\n * - xyz DEX (perpDexIndex=1): 100000 + (1 × 10000) + index = 110000-110999\n * - abc DEX (perpDexIndex=2): 100000 + (2 × 10000) + index = 120000-120999\n *\n * Supports up to 10 HIP-3 DEXs with 10000 assets each.\n */\nexport const HIP3_ASSET_ID_CONFIG = {\n // Base offset for HIP-3 asset IDs (100000)\n // Ensures HIP-3 asset IDs don't conflict with main DEX indices\n BaseAssetId: 100000,\n\n // Multiplier for DEX index in asset ID calculation (10000)\n // Allocates 10000 asset ID slots per DEX (0-9999)\n DexMultiplier: 10000,\n} as const;\n\n/**\n * Basis points conversion constant\n * 1 basis point (bp) = 0.01% = 0.0001 as decimal\n * Used for fee discount calculations (e.g., 6500 bps = 65%)\n */\nexport const BASIS_POINTS_DIVISOR = 10000;\n\n/**\n * Offset added to spot market pair index to derive the spot asset ID\n * used in HyperLiquid order routing.\n * Per HyperLiquid protocol: spotAssetId = SPOT_ASSET_ID_OFFSET + pairIndex\n */\nexport const SPOT_ASSET_ID_OFFSET = 10000;\n\n/**\n * HIP-3 asset market type classifications (PRODUCTION DEFAULT)\n *\n * This is the production default configuration.\n *\n * Maps asset symbols (e.g., \"xyz:TSLA\") to their market type for badge display.\n *\n * Market type determines the badge shown in the UI:\n * - 'stock': Individual stocks (TSLA, NVDA, AAPL, etc.)\n * - 'pre-ipo': Pre-IPO assets not yet publicly listed\n * - 'index': Market indices (SP500, JP225, VIX, etc.)\n * - 'etf': Exchange-traded funds (EWY, EWJ, USAR, etc.)\n * - 'commodity': Commodities (GOLD, SILVER, CL, etc.)\n * - 'forex': Forex pairs (EUR, JPY, DXY)\n * - 'crypto': Explicitly categorized crypto assets\n * - undefined: No badge for unmapped assets\n *\n * Format: 'dex:SYMBOL' → MarketType\n * This allows flexible per-asset classification.\n * Assets not listed here will have no market type (undefined).\n */\nexport const HIP3_ASSET_MARKET_TYPES: Record<string, MarketType> = {\n // xyz DEX - Stocks (US)\n 'xyz:TSLA': MarketCategory.Stock,\n 'xyz:NVDA': MarketCategory.Stock,\n 'xyz:INTC': MarketCategory.Stock,\n 'xyz:MU': MarketCategory.Stock,\n 'xyz:CRCL': MarketCategory.Stock,\n 'xyz:HOOD': MarketCategory.Stock,\n 'xyz:SNDK': MarketCategory.Stock,\n 'xyz:GOOGL': MarketCategory.Stock,\n 'xyz:COIN': MarketCategory.Stock,\n 'xyz:ORCL': MarketCategory.Stock,\n 'xyz:AMZN': MarketCategory.Stock,\n 'xyz:PLTR': MarketCategory.Stock,\n 'xyz:AAPL': MarketCategory.Stock,\n 'xyz:META': MarketCategory.Stock,\n 'xyz:AMD': MarketCategory.Stock,\n 'xyz:MSFT': MarketCategory.Stock,\n 'xyz:BABA': MarketCategory.Stock,\n 'xyz:RIVN': MarketCategory.Stock,\n 'xyz:NFLX': MarketCategory.Stock,\n 'xyz:COST': MarketCategory.Stock,\n 'xyz:LLY': MarketCategory.Stock,\n 'xyz:TSM': MarketCategory.Stock,\n 'xyz:MSTR': MarketCategory.Stock,\n 'xyz:CRWV': MarketCategory.Stock,\n 'xyz:GME': MarketCategory.Stock,\n 'xyz:HIMS': MarketCategory.Stock,\n 'xyz:USAR': MarketCategory.Stock,\n 'xyz:DKNG': MarketCategory.Stock,\n 'xyz:BIRD': MarketCategory.Stock,\n 'xyz:RKLB': MarketCategory.Stock,\n 'xyz:MRVL': MarketCategory.Stock,\n 'xyz:ZM': MarketCategory.Stock,\n 'xyz:EBAY': MarketCategory.Stock,\n 'xyz:PURRDAT': MarketCategory.Stock,\n 'xyz:ARM': MarketCategory.Stock,\n 'xyz:BX': MarketCategory.Stock,\n 'xyz:LITE': MarketCategory.Stock,\n 'xyz:CBRS': MarketCategory.Stock,\n 'xyz:SPCX': MarketCategory.Stock,\n\n // xyz DEX - Stocks (Korea)\n 'xyz:SKHX': MarketCategory.Stock,\n 'xyz:SMSN': MarketCategory.Stock,\n 'xyz:HYUNDAI': MarketCategory.Stock,\n\n // xyz DEX - Stocks (Japan)\n 'xyz:SOFTBANK': MarketCategory.Stock,\n 'xyz:KIOXIA': MarketCategory.Stock,\n\n // xyz DEX - Pre-IPO\n 'xyz:IPOP': MarketCategory.PreIpo,\n\n // xyz DEX - Indices\n 'xyz:SP500': MarketCategory.Index,\n 'xyz:XYZ100': MarketCategory.Index,\n 'xyz:JP225': MarketCategory.Index,\n 'xyz:KR200': MarketCategory.Index,\n 'xyz:VIX': MarketCategory.Index,\n\n // xyz DEX - ETFs\n 'xyz:EWY': MarketCategory.Etf,\n 'xyz:EWJ': MarketCategory.Etf,\n 'xyz:EWT': MarketCategory.Etf,\n 'xyz:EWZ': MarketCategory.Etf,\n 'xyz:URNM': MarketCategory.Etf,\n 'xyz:DRAM': MarketCategory.Etf,\n 'xyz:XLE': MarketCategory.Etf,\n\n // xyz DEX - Commodities\n 'xyz:GOLD': MarketCategory.Commodity,\n 'xyz:SILVER': MarketCategory.Commodity,\n 'xyz:CL': MarketCategory.Commodity,\n 'xyz:WTIOIL': MarketCategory.Commodity,\n 'xyz:COPPER': MarketCategory.Commodity,\n 'xyz:ALUMINIUM': MarketCategory.Commodity,\n 'xyz:URANIUM': MarketCategory.Commodity,\n 'xyz:NATGAS': MarketCategory.Commodity,\n 'xyz:PLATINUM': MarketCategory.Commodity,\n 'xyz:PALLADIUM': MarketCategory.Commodity,\n 'xyz:BRENTOIL': MarketCategory.Commodity,\n\n // xyz DEX - Forex\n 'xyz:EUR': MarketCategory.Forex,\n 'xyz:JPY': MarketCategory.Forex,\n 'xyz:GBP': MarketCategory.Forex,\n 'xyz:DXY': MarketCategory.Forex,\n};\n\n/**\n * Human-readable market names keyed by HyperLiquid asset symbol.\n *\n * HyperLiquid does NOT expose a human-readable name per market: the `meta`\n * universe only returns the ticker (`BTC`, `xyz:TSLA`), and `perpDexs` only\n * exposes a `fullName` for the DEX/venue, not the individual asset. This map is\n * therefore maintained client-side so that clients (mobile, extension) can:\n * - match markets by full name in search (\"Bitcoin\", \"Apple\", \"Gold\"), and\n * - display the full name alongside / instead of the ticker.\n *\n * Keys follow the same convention as {@link HIP3_ASSET_MARKET_TYPES}: bare\n * `SYMBOL` for main-DEX crypto and `dex:SYMBOL` for HIP-3 markets. Use\n * {@link getHyperLiquidAssetName} to resolve a name with a safe fallback to the\n * ticker for unmapped assets.\n *\n * This list is intentionally curated (not exhaustive): unmapped assets simply\n * fall back to their ticker, which matches prior behavior. Add entries as needed.\n */\nexport const HYPERLIQUID_ASSET_NAMES: Record<string, string> = {\n // Main DEX - Crypto majors\n BTC: 'Bitcoin',\n ETH: 'Ethereum',\n SOL: 'Solana',\n XRP: 'XRP',\n BNB: 'BNB',\n DOGE: 'Dogecoin',\n ADA: 'Cardano',\n AVAX: 'Avalanche',\n LINK: 'Chainlink',\n LTC: 'Litecoin',\n DOT: 'Polkadot',\n BCH: 'Bitcoin Cash',\n TRX: 'TRON',\n MATIC: 'Polygon',\n ARB: 'Arbitrum',\n OP: 'Optimism',\n SUI: 'Sui',\n APT: 'Aptos',\n ATOM: 'Cosmos',\n NEAR: 'NEAR Protocol',\n INJ: 'Injective',\n TIA: 'Celestia',\n SEI: 'Sei',\n UNI: 'Uniswap',\n AAVE: 'Aave',\n MKR: 'Maker',\n CRV: 'Curve DAO',\n LDO: 'Lido DAO',\n PEPE: 'Pepe',\n WIF: 'dogwifhat',\n BONK: 'Bonk',\n SHIB: 'Shiba Inu',\n ETC: 'Ethereum Classic',\n FIL: 'Filecoin',\n HBAR: 'Hedera',\n ICP: 'Internet Computer',\n STX: 'Stacks',\n RUNE: 'THORChain',\n TON: 'Toncoin',\n KAS: 'Kaspa',\n FET: 'Fetch.ai',\n ENA: 'Ethena',\n JUP: 'Jupiter',\n PYTH: 'Pyth Network',\n JTO: 'Jito',\n STRK: 'Starknet',\n BLUR: 'Blur',\n GMX: 'GMX',\n DYDX: 'dYdX',\n HYPE: 'Hyperliquid',\n\n // xyz DEX - Stocks (US)\n 'xyz:TSLA': 'Tesla',\n 'xyz:NVDA': 'NVIDIA',\n 'xyz:INTC': 'Intel',\n 'xyz:MU': 'Micron Technology',\n 'xyz:CRCL': 'Circle',\n 'xyz:HOOD': 'Robinhood',\n 'xyz:SNDK': 'SanDisk',\n 'xyz:GOOGL': 'Alphabet (Google)',\n 'xyz:COIN': 'Coinbase',\n 'xyz:ORCL': 'Oracle',\n 'xyz:AMZN': 'Amazon',\n 'xyz:PLTR': 'Palantir',\n 'xyz:AAPL': 'Apple',\n 'xyz:META': 'Meta Platforms',\n 'xyz:AMD': 'AMD',\n 'xyz:MSFT': 'Microsoft',\n 'xyz:BABA': 'Alibaba',\n 'xyz:RIVN': 'Rivian',\n 'xyz:NFLX': 'Netflix',\n 'xyz:COST': 'Costco',\n 'xyz:LLY': 'Eli Lilly',\n 'xyz:TSM': 'Taiwan Semiconductor',\n 'xyz:MSTR': 'Strategy (MicroStrategy)',\n 'xyz:CRWV': 'CoreWeave',\n 'xyz:GME': 'GameStop',\n 'xyz:HIMS': 'Hims & Hers',\n 'xyz:USAR': 'USA Rare Earth',\n 'xyz:DKNG': 'DraftKings',\n 'xyz:RKLB': 'Rocket Lab',\n 'xyz:MRVL': 'Marvell',\n 'xyz:ZM': 'Zoom',\n 'xyz:EBAY': 'eBay',\n 'xyz:ARM': 'Arm Holdings',\n 'xyz:BX': 'Blackstone',\n 'xyz:LITE': 'Lumentum',\n\n // xyz DEX - Stocks (Korea)\n 'xyz:SKHX': 'SK Hynix',\n 'xyz:SMSN': 'Samsung Electronics',\n 'xyz:HYUNDAI': 'Hyundai Motor',\n\n // xyz DEX - Stocks (Japan)\n 'xyz:SOFTBANK': 'SoftBank Group',\n 'xyz:KIOXIA': 'Kioxia',\n\n // xyz DEX - Pre-IPO\n 'xyz:SPCX': 'SpaceX',\n 'xyz:CBRS': 'Cerebras',\n 'xyz:IPOP': 'Quantinuum',\n\n // xyz DEX - Indices\n 'xyz:SP500': 'S&P 500',\n 'xyz:JP225': 'Nikkei 225',\n 'xyz:KR200': 'KOSPI 200',\n 'xyz:VIX': 'CBOE Volatility Index',\n\n // xyz DEX - ETFs\n 'xyz:EWY': 'iShares MSCI South Korea ETF',\n 'xyz:EWJ': 'iShares MSCI Japan ETF',\n 'xyz:EWT': 'iShares MSCI Taiwan ETF',\n 'xyz:EWZ': 'iShares MSCI Brazil ETF',\n 'xyz:URNM': 'Sprott Uranium Miners ETF',\n 'xyz:XLE': 'Energy Select Sector SPDR Fund',\n\n // xyz DEX - Commodities\n 'xyz:GOLD': 'Gold',\n 'xyz:SILVER': 'Silver',\n 'xyz:CL': 'Crude Oil',\n 'xyz:WTIOIL': 'WTI Crude Oil',\n 'xyz:COPPER': 'Copper',\n 'xyz:ALUMINIUM': 'Aluminium',\n 'xyz:URANIUM': 'Uranium',\n 'xyz:NATGAS': 'Natural Gas',\n 'xyz:PLATINUM': 'Platinum',\n 'xyz:PALLADIUM': 'Palladium',\n 'xyz:BRENTOIL': 'Brent Crude Oil',\n\n // xyz DEX - Forex\n 'xyz:EUR': 'Euro',\n 'xyz:JPY': 'Japanese Yen',\n 'xyz:GBP': 'British Pound',\n 'xyz:DXY': 'US Dollar Index',\n};\n\n/**\n * Resolve the human-readable name for a HyperLiquid market.\n *\n * Falls back to the ticker symbol when the asset is not present in\n * {@link HYPERLIQUID_ASSET_NAMES}, so callers always receive a displayable\n * string and unmapped assets keep their prior behavior.\n *\n * @param symbol - HyperLiquid asset symbol (bare `SYMBOL` for main-DEX crypto,\n * `dex:SYMBOL` for HIP-3 markets).\n * @param names - Name map to look up against (defaults to the bundled\n * {@link HYPERLIQUID_ASSET_NAMES}); injectable for testing/overrides.\n * @returns The human-readable name, or the symbol itself when unmapped.\n */\nexport function getHyperLiquidAssetName(\n symbol: string,\n names: Record<string, string> = HYPERLIQUID_ASSET_NAMES,\n): string {\n return names[symbol] ?? symbol;\n}\n\n/**\n * Testnet-specific HIP-3 DEX configuration\n *\n * On testnet, there are many HIP-3 DEXs (test deployments from various builders).\n * Subscribing to all of them causes connection/subscription overload and instability.\n * This configuration limits which DEXs are discovered and subscribed to on testnet.\n */\nexport const TESTNET_HIP3_CONFIG = {\n /**\n * Allowed DEX names for testnet\n * Empty array = main DEX only (no HIP-3 DEXs)\n * Add specific DEX names to test with particular HIP-3 DEXs: ['testdex1', 'testdex2']\n */\n EnabledDexs: ['xyz'] as string[],\n\n /**\n * Set to true to enable full HIP-3 discovery on testnet (not recommended)\n * When false, only DEXs in ENABLED_DEXS are used\n */\n AutoDiscoverAll: false,\n} as const;\n\n/**\n * Mainnet-specific HIP-3 DEX configuration\n *\n * On mainnet, DEX filtering is dynamically determined from the allowlist markets\n * feature flag. This avoids hardcoding DEX names and ensures consistency with\n * the market filtering logic.\n *\n * When AutoDiscoverAll is false and no allowlist is provided, only the main DEX is used.\n * When an allowlist is provided, DEXs are extracted from the allowlist patterns.\n */\nexport const MAINNET_HIP3_CONFIG = {\n /**\n * Set to true to enable full HIP-3 discovery on mainnet\n * When false, DEXs are filtered based on the allowlist markets feature flag\n * (recommended for production to reduce subscription overhead)\n */\n AutoDiscoverAll: false,\n} as const;\n\n/**\n * Margin-mode values HyperLiquid sends on a market. `normal` means no\n * restriction; `MarketInfo.marginMode` carries only the restricting values.\n */\nexport const HYPERLIQUID_VENUE_MARGIN_MODES = [\n 'normal',\n 'strictIsolated',\n 'noCross',\n] as const;\n\n/**\n * Whether a venue `marginMode` places no restriction on the market. Absent,\n * null and `normal` are unrestricted; any other value, including ones added\n * later, restricts it.\n *\n * @param marginMode - The venue `marginMode`, if any.\n * @returns True when the value allows Cross margin.\n */\nexport function isUnrestrictedMarginMode(\n marginMode: string | null | undefined,\n): marginMode is 'normal' | null | undefined {\n return (\n marginMode === undefined || marginMode === null || marginMode === 'normal'\n );\n}\n\n/**\n * HIP-3 margin management configuration\n * Controls margin buffers and auto-rebalance behavior for manual HIP-3 collateral transfers\n *\n * Background: HyperLiquid validates spendableBalance >= totalRequiredMargin BEFORE reallocating\n * existing locked margin. This requires temporary over-funding when increasing positions,\n * followed by automatic cleanup to minimize locked capital.\n */\nexport const HIP3_MARGIN_CONFIG = {\n /**\n * Margin buffer multiplier for fees and slippage (0.3% = multiply by 1.003)\n * Covers HyperLiquid's max taker fee (0.035%) with comfortable margin\n */\n BufferMultiplier: 1.003,\n\n /**\n * Desired buffer to keep on HIP-3 DEX after auto-rebalance (USDC amount)\n * Small buffer allows quick follow-up orders without transfers\n */\n RebalanceDesiredBuffer: 0.1,\n\n /**\n * Minimum excess threshold to trigger auto-rebalance (USDC amount)\n * Prevents unnecessary transfers for tiny amounts\n */\n RebalanceMinThreshold: 0.1,\n} as const;\n\n// Progress bar constants\nexport const INITIAL_AMOUNT_UI_PROGRESS = 10;\nexport const WITHDRAWAL_PROGRESS_STAGES = [\n 25, 35, 45, 55, 65, 75, 85, 90, 95, 98,\n];\nexport const PROGRESS_BAR_COMPLETION_D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;;;;;GAMG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC;;;;OAIG;IACH,WAAW,EAAE,CAAC,KAAK,CAAa;IAEhC;;;OAGG;IACH,eAAe,EAAE,KAAK;CACd,CAAC;AAEX;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC;;;;OAIG;IACH,eAAe,EAAE,KAAK;CACd,CAAC;AAEX;;;GAGG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG;IAC5C,QAAQ;IACR,gBAAgB;IAChB,SAAS;CACD,CAAC;AAEX;;;;;;;GAOG;AACH,MAAM,UAAU,wBAAwB,CACtC,UAAqC;IAErC,OAAO,CACL,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,IAAI,IAAI,UAAU,KAAK,QAAQ,CAC3E,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC;;;OAGG;IACH,gBAAgB,EAAE,KAAK;IAEvB;;;OAGG;IACH,sBAAsB,EAAE,GAAG;IAE3B;;;OAGG;IACH,qBAAqB,EAAE,GAAG;CAClB,CAAC;AAEX,yBAAyB;AACzB,MAAM,CAAC,MAAM,0BAA0B,GAAG,EAAE,CAAC;AAC7C,MAAM,CAAC,MAAM,0BAA0B,GAAG;IACxC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE;CACvC,CAAC;AACF,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAC","sourcesContent":["import type { CaipAssetId, CaipChainId, Hex } from '@metamask/utils';\n\nimport { MarketCategory } from '../types/index.js';\nimport type {\n DirectProviderOrderCapabilities,\n MarketType,\n} from '../types/index.js';\nimport type {\n HyperLiquidNetwork,\n HyperLiquidEndpoints,\n HyperLiquidAssetConfigs,\n BridgeContractConfig,\n HyperLiquidBridgeContracts,\n HyperLiquidTransportConfig,\n TradingDefaultsConfig,\n FeeRatesConfig,\n} from '../types/perps-types.js';\nimport {\n SCALE_ORDER_COUNT,\n STRATEGY_ORDER_TYPES,\n TRIGGER_ORDER_TYPES,\n} from '../utils/orderTypes.js';\nimport {\n CHASE_ORDER_CONFIG,\n HYPERLIQUID_TWAP_LIMITS,\n PROVIDER_CONFIG,\n} from './perpsConfig.js';\n\n// Network constants\nexport const ARBITRUM_MAINNET_CHAIN_ID_HEX = '0xa4b1' as const;\nexport const ARBITRUM_MAINNET_CHAIN_ID = '42161';\nexport const ARBITRUM_TESTNET_CHAIN_ID = '421614';\nexport const ARBITRUM_MAINNET_CAIP_CHAIN_ID = `eip155:${ARBITRUM_MAINNET_CHAIN_ID}`;\nexport const ARBITRUM_TESTNET_CAIP_CHAIN_ID = `eip155:${ARBITRUM_TESTNET_CHAIN_ID}`;\n\n// Hyperliquid chain constants\nexport const HYPERLIQUID_MAINNET_CHAIN_ID = '0x3e7'; // 999 in decimal\nexport const HYPERLIQUID_TESTNET_CHAIN_ID = '0x3e6'; // 998 in decimal (assumed)\nexport const HYPERLIQUID_MAINNET_CAIP_CHAIN_ID = 'eip155:999' as CaipChainId;\nexport const HYPERLIQUID_TESTNET_CAIP_CHAIN_ID = 'eip155:998' as CaipChainId;\nexport const HYPERLIQUID_NETWORK_NAME = 'Hyperliquid';\n\n/**\n * Return the canonical snapshot identity: main first, then unique DEX ids.\n *\n * @param dexes - DEX identifiers to canonicalize.\n * @returns The canonical DEX identifiers.\n */\nexport function canonicalizeHyperLiquidDexes(\n dexes: Iterable<string>,\n): string[] {\n const additionalDexes = new Set(dexes);\n additionalDexes.delete('main');\n return ['main', ...Array.from(additionalDexes).sort()];\n}\n\n// Token constants\nexport const USDC_SYMBOL = 'USDC';\nexport const USDC_NAME = 'USD Coin';\nexport const USDC_DECIMALS = 6;\nexport const TOKEN_DECIMALS = 18;\n\n// Network constants\nexport const ARBITRUM_SEPOLIA_CHAIN_ID = '0x66eee'; // 421614 in decimal\n\n// USDC token addresses\nexport const USDC_ETHEREUM_MAINNET_ADDRESS =\n '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48';\nexport const USDC_ARBITRUM_MAINNET_ADDRESS =\n '0xaf88d065e77c8cC2239327C5EDb3A432268e5831';\n// USDC2: the token the Arbitrum Sepolia bridge credits (its usdcToken())\nexport const USDC_ARBITRUM_TESTNET_ADDRESS =\n '0x1baAbB04529D43a73232B713C0FE471f7c7334d5';\n\n// USDC token icon URL using MetaMask's official Token Icons API\n// Format: https://static.cx.metamask.io/api/v1/tokenIcons/{chainId}/{contractAddress}.png\n// This URL follows the same pattern used throughout MetaMask (bridges, swaps, etc.)\nexport const USDC_TOKEN_ICON_URL = `https://static.cx.metamask.io/api/v1/tokenIcons/1/${USDC_ETHEREUM_MAINNET_ADDRESS}.png`;\n\n// WebSocket endpoints\nexport const HYPERLIQUID_ENDPOINTS: HyperLiquidEndpoints = {\n mainnet: 'wss://api.hyperliquid.xyz/ws',\n testnet: 'wss://api.hyperliquid-testnet.xyz/ws',\n};\n\n// Asset icons base URL (HyperLiquid CDN - fallback source)\nexport const HYPERLIQUID_ASSET_ICONS_BASE_URL =\n 'https://app.hyperliquid.xyz/coins/';\n\n// MetaMask-hosted Perps asset icons (primary source)\n// Assets uploaded to: https://github.com/MetaMask/contract-metadata/tree/master/icons/eip155:999\n// HIP-3 assets use format: hip3:dex_SYMBOL.svg (e.g., hip3:xyz_AAPL.svg)\n// Regular assets use format: SYMBOL.svg (e.g., BTC.svg)\nexport const METAMASK_PERPS_ICONS_BASE_URL =\n 'https://raw.githubusercontent.com/MetaMask/contract-metadata/master/icons/eip155:999/';\n\n// Asset configurations for multichain abstraction\nexport const HYPERLIQUID_ASSET_CONFIGS: HyperLiquidAssetConfigs = {\n usdc: {\n mainnet: `${ARBITRUM_MAINNET_CAIP_CHAIN_ID}/erc20:0xaf88d065e77c8cC2239327C5EDb3A432268e5831/default`,\n testnet: `${ARBITRUM_TESTNET_CAIP_CHAIN_ID}/erc20:0x1baAbB04529D43a73232B713C0FE471f7c7334d5/default`,\n },\n};\n\n// HyperLiquid bridge contract addresses for direct USDC deposits\n// These are the official bridge contracts where USDC must be sent to credit user's HyperLiquid account\nexport const HYPERLIQUID_BRIDGE_CONTRACTS: HyperLiquidBridgeContracts = {\n mainnet: {\n chainId: ARBITRUM_MAINNET_CAIP_CHAIN_ID,\n contractAddress: '0x2df1c51e09aecf9cacb7bc98cb1742757f163df7',\n },\n testnet: {\n chainId: ARBITRUM_TESTNET_CAIP_CHAIN_ID,\n contractAddress: '0x08cfc1B6b2dCF36A1480b99353A354AA8AC56f89',\n },\n};\n\n// SDK transport configuration\nexport const HYPERLIQUID_TRANSPORT_CONFIG: HyperLiquidTransportConfig = {\n timeout: 10_000,\n keepAlive: { interval: 30_000 },\n reconnect: {\n maxRetries: 5,\n connectionTimeout: 10_000,\n },\n};\n\n// Trading configuration constants\nexport const TRADING_DEFAULTS: TradingDefaultsConfig = {\n leverage: 3, // 3x default leverage\n marginPercent: 10, // 10% fixed margin default\n takeProfitPercent: 0.3, // 30% take profit\n stopLossPercent: 0.1, // 10% stop loss\n amount: {\n mainnet: 10, // $10 minimum order size\n testnet: 10, // $10 minimum order size\n },\n};\n\n// Fee configuration\n// Note: These are base rates (Tier 0, no discounts)\n// Actual fees will be calculated based on user's volume tier and staking\nexport const FEE_RATES: FeeRatesConfig = {\n taker: 0.00045, // 0.045% - Market orders and aggressive limit orders\n maker: 0.00015, // 0.015% - Limit orders that add liquidity\n};\n\n/**\n * HIP-3 dynamic fee calculation configuration\n *\n * HIP-3 (builder-deployed) perpetual markets have variable fees based on:\n * 1. deployerFeeScale - Per-DEX fee multiplier (fetched from perpDexs API)\n * 2. growthMode - Per-asset 90% fee reduction (fetched from meta API)\n *\n * Fee Formula (from HyperLiquid docs):\n * - scaleIfHip3 = deployerFeeScale < 1 ? deployerFeeScale + 1 : deployerFeeScale * 2\n * - growthModeScale = growthMode ? 0.1 : 1\n * - finalRate = baseRate * scaleIfHip3 * growthModeScale\n *\n * Example: For xyz:TSLA with deployerFeeScale=1.0 and growthMode=\"enabled\":\n * - scaleIfHip3 = 1.0 * 2 = 2.0\n * - growthModeScale = 0.1 (90% reduction)\n * - Final multiplier = 2.0 * 0.1 = 0.2 (effectively 80% off standard 2x HIP-3 fees)\n *\n * @see https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees#fee-formula-for-developers\n * @see parseAssetName() in HyperLiquidProvider for HIP-3 asset detection\n */\nexport const HIP3_FEE_CONFIG = {\n /**\n * Growth Mode multiplier - 90% fee reduction for assets in growth phase\n * This is a protocol constant from HyperLiquid's fee formula\n */\n GrowthModeScale: 0.1,\n\n /**\n * Default deployerFeeScale when API is unavailable\n * Most HIP-3 DEXs use 1.0, which results in 2x base fees\n */\n DefaultDeployerFeeScale: 1.0,\n\n /**\n * Cache TTL for perpDexs data (5 minutes)\n * Fee scales rarely change, so longer cache is acceptable\n */\n PerpDexsCacheTtlMs: 5 * 60 * 1000,\n\n /**\n * @deprecated Use dynamic calculation via calculateHip3FeeMultiplier()\n * Kept for backwards compatibility during migration\n */\n FeeMultiplier: 2,\n} as const;\n\n/**\n * EIP-712 primary type of every HyperLiquid L1 action (orders, cancels,\n * leverage, ...). Only L1 actions may be signed by an agent; every other\n * request is a user-signed action for the main account.\n */\nexport const HYPERLIQUID_L1_ACTION_PRIMARY_TYPE = 'Agent';\n\n/**\n * EIP-712 domain name of every HyperLiquid L1 action.\n */\nexport const HYPERLIQUID_L1_ACTION_DOMAIN_NAME = 'Exchange';\n\nconst BUILDER_FEE_MAX_FEE_DECIMAL = 0.001;\n\n// Builder fee configuration\nexport const BUILDER_FEE_CONFIG = {\n // Test builder wallet\n TestnetBuilder: '0x724e57771ba749650875bd8adb2e29a85d0cacfa' as Hex,\n // Production builder wallet\n MainnetBuilder: '0xe95a5e31904e005066614247d309e00d8ad753aa' as Hex,\n // Fee in decimal (10 bp = 0.1%)\n MaxFeeDecimal: BUILDER_FEE_MAX_FEE_DECIMAL,\n MaxFeeTenthsBps: BUILDER_FEE_MAX_FEE_DECIMAL * 100000,\n MaxFeeRate: `${(BUILDER_FEE_MAX_FEE_DECIMAL * 100)\n .toFixed(4)\n .replace(/\\.?0+$/u, '')}%`,\n};\n\n/**\n * Strategies and standalone trigger orders HyperLiquid executes for its markets.\n * Providers own this declaration so clients never infer support from a\n * provider name.\n */\nexport const HYPERLIQUID_ORDER_CAPABILITIES = Object.freeze({\n status: 'ready',\n providerId: PROVIDER_CONFIG.DefaultProvider,\n supportedStrategies: Object.freeze([...STRATEGY_ORDER_TYPES]),\n supportedTriggerOrderTypes: Object.freeze([...TRIGGER_ORDER_TYPES]),\n strategyRules: Object.freeze({\n twap: Object.freeze({\n minDurationMinutes: HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes,\n maxDurationMinutes: HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes,\n minNotionalUsd: HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd,\n sliceIntervalSeconds: HYPERLIQUID_TWAP_LIMITS.SliceIntervalSeconds,\n }),\n chase: Object.freeze({\n maxActiveSessions: CHASE_ORDER_CONFIG.MaxActiveSessions,\n defaultIntervalMs: CHASE_ORDER_CONFIG.DefaultIntervalMs,\n minIntervalMs: CHASE_ORDER_CONFIG.MinIntervalMs,\n }),\n scale: Object.freeze({\n minOrders: SCALE_ORDER_COUNT.min,\n maxOrders: SCALE_ORDER_COUNT.max,\n }),\n }),\n positionTpsl: Object.freeze({\n supportsExpectedPosition: true,\n childOrderIds: 'request-correlated',\n takeProfitOrderType: 'take_profit_limit',\n stopLossOrderType: 'stop_market',\n defaultCoverage: 'dynamic-position',\n partialCoverage: Object.freeze({\n single: true,\n pair: 'independent',\n replacement: 'cancel-before-create',\n recovery: 'provider-default',\n }),\n }),\n}) satisfies DirectProviderOrderCapabilities;\n\n// Referral code configuration\nexport const REFERRAL_CONFIG = {\n // Production referral code\n MainnetCode: 'MMCSI',\n // Development/testnet referral code\n TestnetCode: 'MMCSITEST',\n};\n\n// Deposit constants\nexport const DEPOSIT_CONFIG = {\n EstimatedGasLimit: 100000, // Estimated gas limit for bridge deposit\n DefaultSlippage: 1, // 1% default slippage for bridge quotes\n BridgeQuoteTimeout: 1000, // 1 second timeout for bridge quotes\n RefreshRate: 30000, // 30 seconds quote refresh rate\n EstimatedTime: {\n DirectDeposit: '3-5 seconds', // Direct USDC deposit on Arbitrum\n SameChainSwap: '30-60 seconds', // Swap on same chain before deposit\n },\n};\n\n// Withdrawal constants (HyperLiquid-specific)\nexport const HYPERLIQUID_WITHDRAWAL_MINUTES = 5; // HyperLiquid withdrawal processing time in minutes\n\n// Type helpers\nexport type SupportedAsset = keyof typeof HYPERLIQUID_ASSET_CONFIGS;\n\n// Configuration helpers\nexport function getWebSocketEndpoint(isTestnet: boolean): string {\n return isTestnet\n ? HYPERLIQUID_ENDPOINTS.testnet\n : HYPERLIQUID_ENDPOINTS.mainnet;\n}\n\nexport function getChainId(isTestnet: boolean): string {\n return isTestnet ? ARBITRUM_TESTNET_CHAIN_ID : ARBITRUM_MAINNET_CHAIN_ID;\n}\n\nexport function getCaipChainId(isTestnet: boolean): CaipChainId {\n const network: HyperLiquidNetwork = isTestnet ? 'testnet' : 'mainnet';\n return HYPERLIQUID_BRIDGE_CONTRACTS[network].chainId;\n}\n\nexport function getBridgeInfo(isTestnet: boolean): BridgeContractConfig {\n const network: HyperLiquidNetwork = isTestnet ? 'testnet' : 'mainnet';\n return HYPERLIQUID_BRIDGE_CONTRACTS[network];\n}\n\nexport function getSupportedAssets(isTestnet?: boolean): CaipAssetId[] {\n const network = isTestnet ? 'testnet' : 'mainnet';\n return Object.values(HYPERLIQUID_ASSET_CONFIGS).map(\n (config) => config[network],\n );\n}\n\n// CAIP asset namespace constants\nexport const CAIP_ASSET_NAMESPACES = {\n Erc20: 'erc20',\n} as const;\n\n/**\n * HyperLiquid protocol-specific configuration\n * Contains constants specific to HyperLiquid's perps exchange\n */\nexport const HYPERLIQUID_CONFIG = {\n // Exchange name used in predicted funding data\n // HyperLiquid uses 'HlPerp' as their perps exchange identifier\n ExchangeName: 'HlPerp',\n DexDiscoveryInitialWaitMs: 5000,\n DexDiscoveryRetryDelayMs: 5000,\n // Maximum allowed deviation of the market (mid) price from the oracle (reference)\n // price before HyperLiquid rejects orders. HyperLiquid enforces \"Order price cannot\n // be more than 95% away from the reference price\", which makes markets — most often\n // HIP-3 builder-deployed ones — temporarily untradable when the mid price drifts past\n // this limit. Expressed as a decimal fraction (0.95 = 95%).\n // Protocol rule, not a UI warning threshold (see VALIDATION_THRESHOLDS.PriceDeviation).\n OraclePriceDeviationLimit: 0.95,\n} as const;\n\n/**\n * HIP-3 multi-DEX asset ID calculation constants\n * Per HIP-3-IMPLEMENTATION.md:\n * - Main DEX: assetId = index (0, 1, 2, ...)\n * - HIP-3 DEX: assetId = BASE_ASSET_ID + (perpDexIndex × DEX_MULTIPLIER) + index\n *\n * This formula enables proper order routing across multiple DEXs:\n * - Main DEX (perpDexIndex=0): Uses index directly (BTC=0, ETH=1, SOL=2, etc.)\n * - xyz DEX (perpDexIndex=1): 100000 + (1 × 10000) + index = 110000-110999\n * - abc DEX (perpDexIndex=2): 100000 + (2 × 10000) + index = 120000-120999\n *\n * Supports up to 10 HIP-3 DEXs with 10000 assets each.\n */\nexport const HIP3_ASSET_ID_CONFIG = {\n // Base offset for HIP-3 asset IDs (100000)\n // Ensures HIP-3 asset IDs don't conflict with main DEX indices\n BaseAssetId: 100000,\n\n // Multiplier for DEX index in asset ID calculation (10000)\n // Allocates 10000 asset ID slots per DEX (0-9999)\n DexMultiplier: 10000,\n} as const;\n\n/**\n * Basis points conversion constant\n * 1 basis point (bp) = 0.01% = 0.0001 as decimal\n * Used for fee discount calculations (e.g., 6500 bps = 65%)\n */\nexport const BASIS_POINTS_DIVISOR = 10000;\n\n/**\n * Offset added to spot market pair index to derive the spot asset ID\n * used in HyperLiquid order routing.\n * Per HyperLiquid protocol: spotAssetId = SPOT_ASSET_ID_OFFSET + pairIndex\n */\nexport const SPOT_ASSET_ID_OFFSET = 10000;\n\n/**\n * HIP-3 asset market type classifications (PRODUCTION DEFAULT)\n *\n * This is the production default configuration.\n *\n * Maps asset symbols (e.g., \"xyz:TSLA\") to their market type for badge display.\n *\n * Market type determines the badge shown in the UI:\n * - 'stock': Individual stocks (TSLA, NVDA, AAPL, etc.)\n * - 'pre-ipo': Pre-IPO assets not yet publicly listed\n * - 'index': Market indices (SP500, JP225, VIX, etc.)\n * - 'etf': Exchange-traded funds (EWY, EWJ, USAR, etc.)\n * - 'commodity': Commodities (GOLD, SILVER, CL, etc.)\n * - 'forex': Forex pairs (EUR, JPY, DXY)\n * - 'crypto': Explicitly categorized crypto assets\n * - undefined: No badge for unmapped assets\n *\n * Format: 'dex:SYMBOL' → MarketType\n * This allows flexible per-asset classification.\n * Assets not listed here will have no market type (undefined).\n */\nexport const HIP3_ASSET_MARKET_TYPES: Record<string, MarketType> = {\n // xyz DEX - Stocks (US)\n 'xyz:TSLA': MarketCategory.Stock,\n 'xyz:NVDA': MarketCategory.Stock,\n 'xyz:INTC': MarketCategory.Stock,\n 'xyz:MU': MarketCategory.Stock,\n 'xyz:CRCL': MarketCategory.Stock,\n 'xyz:HOOD': MarketCategory.Stock,\n 'xyz:SNDK': MarketCategory.Stock,\n 'xyz:GOOGL': MarketCategory.Stock,\n 'xyz:COIN': MarketCategory.Stock,\n 'xyz:ORCL': MarketCategory.Stock,\n 'xyz:AMZN': MarketCategory.Stock,\n 'xyz:PLTR': MarketCategory.Stock,\n 'xyz:AAPL': MarketCategory.Stock,\n 'xyz:META': MarketCategory.Stock,\n 'xyz:AMD': MarketCategory.Stock,\n 'xyz:MSFT': MarketCategory.Stock,\n 'xyz:BABA': MarketCategory.Stock,\n 'xyz:RIVN': MarketCategory.Stock,\n 'xyz:NFLX': MarketCategory.Stock,\n 'xyz:COST': MarketCategory.Stock,\n 'xyz:LLY': MarketCategory.Stock,\n 'xyz:TSM': MarketCategory.Stock,\n 'xyz:MSTR': MarketCategory.Stock,\n 'xyz:CRWV': MarketCategory.Stock,\n 'xyz:GME': MarketCategory.Stock,\n 'xyz:HIMS': MarketCategory.Stock,\n 'xyz:USAR': MarketCategory.Stock,\n 'xyz:DKNG': MarketCategory.Stock,\n 'xyz:BIRD': MarketCategory.Stock,\n 'xyz:RKLB': MarketCategory.Stock,\n 'xyz:MRVL': MarketCategory.Stock,\n 'xyz:ZM': MarketCategory.Stock,\n 'xyz:EBAY': MarketCategory.Stock,\n 'xyz:PURRDAT': MarketCategory.Stock,\n 'xyz:ARM': MarketCategory.Stock,\n 'xyz:BX': MarketCategory.Stock,\n 'xyz:LITE': MarketCategory.Stock,\n 'xyz:CBRS': MarketCategory.Stock,\n 'xyz:SPCX': MarketCategory.Stock,\n\n // xyz DEX - Stocks (Korea)\n 'xyz:SKHX': MarketCategory.Stock,\n 'xyz:SMSN': MarketCategory.Stock,\n 'xyz:HYUNDAI': MarketCategory.Stock,\n\n // xyz DEX - Stocks (Japan)\n 'xyz:SOFTBANK': MarketCategory.Stock,\n 'xyz:KIOXIA': MarketCategory.Stock,\n\n // xyz DEX - Pre-IPO\n 'xyz:IPOP': MarketCategory.PreIpo,\n\n // xyz DEX - Indices\n 'xyz:SP500': MarketCategory.Index,\n 'xyz:XYZ100': MarketCategory.Index,\n 'xyz:JP225': MarketCategory.Index,\n 'xyz:KR200': MarketCategory.Index,\n 'xyz:VIX': MarketCategory.Index,\n\n // xyz DEX - ETFs\n 'xyz:EWY': MarketCategory.Etf,\n 'xyz:EWJ': MarketCategory.Etf,\n 'xyz:EWT': MarketCategory.Etf,\n 'xyz:EWZ': MarketCategory.Etf,\n 'xyz:URNM': MarketCategory.Etf,\n 'xyz:DRAM': MarketCategory.Etf,\n 'xyz:XLE': MarketCategory.Etf,\n\n // xyz DEX - Commodities\n 'xyz:GOLD': MarketCategory.Commodity,\n 'xyz:SILVER': MarketCategory.Commodity,\n 'xyz:CL': MarketCategory.Commodity,\n 'xyz:WTIOIL': MarketCategory.Commodity,\n 'xyz:COPPER': MarketCategory.Commodity,\n 'xyz:ALUMINIUM': MarketCategory.Commodity,\n 'xyz:URANIUM': MarketCategory.Commodity,\n 'xyz:NATGAS': MarketCategory.Commodity,\n 'xyz:PLATINUM': MarketCategory.Commodity,\n 'xyz:PALLADIUM': MarketCategory.Commodity,\n 'xyz:BRENTOIL': MarketCategory.Commodity,\n\n // xyz DEX - Forex\n 'xyz:EUR': MarketCategory.Forex,\n 'xyz:JPY': MarketCategory.Forex,\n 'xyz:GBP': MarketCategory.Forex,\n 'xyz:DXY': MarketCategory.Forex,\n};\n\n/**\n * Human-readable market names keyed by HyperLiquid asset symbol.\n *\n * HyperLiquid does NOT expose a human-readable name per market: the `meta`\n * universe only returns the ticker (`BTC`, `xyz:TSLA`), and `perpDexs` only\n * exposes a `fullName` for the DEX/venue, not the individual asset. This map is\n * therefore maintained client-side so that clients (mobile, extension) can:\n * - match markets by full name in search (\"Bitcoin\", \"Apple\", \"Gold\"), and\n * - display the full name alongside / instead of the ticker.\n *\n * Keys follow the same convention as {@link HIP3_ASSET_MARKET_TYPES}: bare\n * `SYMBOL` for main-DEX crypto and `dex:SYMBOL` for HIP-3 markets. Use\n * {@link getHyperLiquidAssetName} to resolve a name with a safe fallback to the\n * ticker for unmapped assets.\n *\n * This list is intentionally curated (not exhaustive): unmapped assets simply\n * fall back to their ticker, which matches prior behavior. Add entries as needed.\n */\nexport const HYPERLIQUID_ASSET_NAMES: Record<string, string> = {\n // Main DEX - Crypto majors\n BTC: 'Bitcoin',\n ETH: 'Ethereum',\n SOL: 'Solana',\n XRP: 'XRP',\n BNB: 'BNB',\n DOGE: 'Dogecoin',\n ADA: 'Cardano',\n AVAX: 'Avalanche',\n LINK: 'Chainlink',\n LTC: 'Litecoin',\n DOT: 'Polkadot',\n BCH: 'Bitcoin Cash',\n TRX: 'TRON',\n MATIC: 'Polygon',\n ARB: 'Arbitrum',\n OP: 'Optimism',\n SUI: 'Sui',\n APT: 'Aptos',\n ATOM: 'Cosmos',\n NEAR: 'NEAR Protocol',\n INJ: 'Injective',\n TIA: 'Celestia',\n SEI: 'Sei',\n UNI: 'Uniswap',\n AAVE: 'Aave',\n MKR: 'Maker',\n CRV: 'Curve DAO',\n LDO: 'Lido DAO',\n PEPE: 'Pepe',\n WIF: 'dogwifhat',\n BONK: 'Bonk',\n SHIB: 'Shiba Inu',\n ETC: 'Ethereum Classic',\n FIL: 'Filecoin',\n HBAR: 'Hedera',\n ICP: 'Internet Computer',\n STX: 'Stacks',\n RUNE: 'THORChain',\n TON: 'Toncoin',\n KAS: 'Kaspa',\n FET: 'Fetch.ai',\n ENA: 'Ethena',\n JUP: 'Jupiter',\n PYTH: 'Pyth Network',\n JTO: 'Jito',\n STRK: 'Starknet',\n BLUR: 'Blur',\n GMX: 'GMX',\n DYDX: 'dYdX',\n HYPE: 'Hyperliquid',\n\n // xyz DEX - Stocks (US)\n 'xyz:TSLA': 'Tesla',\n 'xyz:NVDA': 'NVIDIA',\n 'xyz:INTC': 'Intel',\n 'xyz:MU': 'Micron Technology',\n 'xyz:CRCL': 'Circle',\n 'xyz:HOOD': 'Robinhood',\n 'xyz:SNDK': 'SanDisk',\n 'xyz:GOOGL': 'Alphabet (Google)',\n 'xyz:COIN': 'Coinbase',\n 'xyz:ORCL': 'Oracle',\n 'xyz:AMZN': 'Amazon',\n 'xyz:PLTR': 'Palantir',\n 'xyz:AAPL': 'Apple',\n 'xyz:META': 'Meta Platforms',\n 'xyz:AMD': 'AMD',\n 'xyz:MSFT': 'Microsoft',\n 'xyz:BABA': 'Alibaba',\n 'xyz:RIVN': 'Rivian',\n 'xyz:NFLX': 'Netflix',\n 'xyz:COST': 'Costco',\n 'xyz:LLY': 'Eli Lilly',\n 'xyz:TSM': 'Taiwan Semiconductor',\n 'xyz:MSTR': 'Strategy (MicroStrategy)',\n 'xyz:CRWV': 'CoreWeave',\n 'xyz:GME': 'GameStop',\n 'xyz:HIMS': 'Hims & Hers',\n 'xyz:USAR': 'USA Rare Earth',\n 'xyz:DKNG': 'DraftKings',\n 'xyz:RKLB': 'Rocket Lab',\n 'xyz:MRVL': 'Marvell',\n 'xyz:ZM': 'Zoom',\n 'xyz:EBAY': 'eBay',\n 'xyz:ARM': 'Arm Holdings',\n 'xyz:BX': 'Blackstone',\n 'xyz:LITE': 'Lumentum',\n\n // xyz DEX - Stocks (Korea)\n 'xyz:SKHX': 'SK Hynix',\n 'xyz:SMSN': 'Samsung Electronics',\n 'xyz:HYUNDAI': 'Hyundai Motor',\n\n // xyz DEX - Stocks (Japan)\n 'xyz:SOFTBANK': 'SoftBank Group',\n 'xyz:KIOXIA': 'Kioxia',\n\n // xyz DEX - Pre-IPO\n 'xyz:SPCX': 'SpaceX',\n 'xyz:CBRS': 'Cerebras',\n 'xyz:IPOP': 'Quantinuum',\n\n // xyz DEX - Indices\n 'xyz:SP500': 'S&P 500',\n 'xyz:JP225': 'Nikkei 225',\n 'xyz:KR200': 'KOSPI 200',\n 'xyz:VIX': 'CBOE Volatility Index',\n\n // xyz DEX - ETFs\n 'xyz:EWY': 'iShares MSCI South Korea ETF',\n 'xyz:EWJ': 'iShares MSCI Japan ETF',\n 'xyz:EWT': 'iShares MSCI Taiwan ETF',\n 'xyz:EWZ': 'iShares MSCI Brazil ETF',\n 'xyz:URNM': 'Sprott Uranium Miners ETF',\n 'xyz:XLE': 'Energy Select Sector SPDR Fund',\n\n // xyz DEX - Commodities\n 'xyz:GOLD': 'Gold',\n 'xyz:SILVER': 'Silver',\n 'xyz:CL': 'Crude Oil',\n 'xyz:WTIOIL': 'WTI Crude Oil',\n 'xyz:COPPER': 'Copper',\n 'xyz:ALUMINIUM': 'Aluminium',\n 'xyz:URANIUM': 'Uranium',\n 'xyz:NATGAS': 'Natural Gas',\n 'xyz:PLATINUM': 'Platinum',\n 'xyz:PALLADIUM': 'Palladium',\n 'xyz:BRENTOIL': 'Brent Crude Oil',\n\n // xyz DEX - Forex\n 'xyz:EUR': 'Euro',\n 'xyz:JPY': 'Japanese Yen',\n 'xyz:GBP': 'British Pound',\n 'xyz:DXY': 'US Dollar Index',\n};\n\n/**\n * Resolve the human-readable name for a HyperLiquid market.\n *\n * Falls back to the ticker symbol when the asset is not present in\n * {@link HYPERLIQUID_ASSET_NAMES}, so callers always receive a displayable\n * string and unmapped assets keep their prior behavior.\n *\n * @param symbol - HyperLiquid asset symbol (bare `SYMBOL` for main-DEX crypto,\n * `dex:SYMBOL` for HIP-3 markets).\n * @param names - Name map to look up against (defaults to the bundled\n * {@link HYPERLIQUID_ASSET_NAMES}); injectable for testing/overrides.\n * @returns The human-readable name, or the symbol itself when unmapped.\n */\nexport function getHyperLiquidAssetName(\n symbol: string,\n names: Record<string, string> = HYPERLIQUID_ASSET_NAMES,\n): string {\n return names[symbol] ?? symbol;\n}\n\n/**\n * Testnet-specific HIP-3 DEX configuration\n *\n * On testnet, there are many HIP-3 DEXs (test deployments from various builders).\n * Subscribing to all of them causes connection/subscription overload and instability.\n * This configuration limits which DEXs are discovered and subscribed to on testnet.\n */\nexport const TESTNET_HIP3_CONFIG = {\n /**\n * Allowed DEX names for testnet\n * Empty array = main DEX only (no HIP-3 DEXs)\n * Add specific DEX names to test with particular HIP-3 DEXs: ['testdex1', 'testdex2']\n */\n EnabledDexs: ['xyz'] as string[],\n\n /**\n * Set to true to enable full HIP-3 discovery on testnet (not recommended)\n * When false, only DEXs in ENABLED_DEXS are used\n */\n AutoDiscoverAll: false,\n} as const;\n\n/**\n * Mainnet-specific HIP-3 DEX configuration\n *\n * On mainnet, DEX filtering is dynamically determined from the allowlist markets\n * feature flag. This avoids hardcoding DEX names and ensures consistency with\n * the market filtering logic.\n *\n * When AutoDiscoverAll is false and no allowlist is provided, only the main DEX is used.\n * When an allowlist is provided, DEXs are extracted from the allowlist patterns.\n */\nexport const MAINNET_HIP3_CONFIG = {\n /**\n * Set to true to enable full HIP-3 discovery on mainnet\n * When false, DEXs are filtered based on the allowlist markets feature flag\n * (recommended for production to reduce subscription overhead)\n */\n AutoDiscoverAll: false,\n} as const;\n\n/**\n * Margin-mode values HyperLiquid sends on a market. `normal` means no\n * restriction; `MarketInfo.marginMode` carries only the restricting values.\n */\nexport const HYPERLIQUID_VENUE_MARGIN_MODES = [\n 'normal',\n 'strictIsolated',\n 'noCross',\n] as const;\n\n/**\n * Whether a venue `marginMode` places no restriction on the market. Absent,\n * null and `normal` are unrestricted; any other value, including ones added\n * later, restricts it.\n *\n * @param marginMode - The venue `marginMode`, if any.\n * @returns True when the value allows Cross margin.\n */\nexport function isUnrestrictedMarginMode(\n marginMode: string | null | undefined,\n): marginMode is 'normal' | null | undefined {\n return (\n marginMode === undefined || marginMode === null || marginMode === 'normal'\n );\n}\n\n/**\n * HIP-3 margin management configuration\n * Controls margin buffers and auto-rebalance behavior for manual HIP-3 collateral transfers\n *\n * Background: HyperLiquid validates spendableBalance >= totalRequiredMargin BEFORE reallocating\n * existing locked margin. This requires temporary over-funding when increasing positions,\n * followed by automatic cleanup to minimize locked capital.\n */\nexport const HIP3_MARGIN_CONFIG = {\n /**\n * Margin buffer multiplier for fees and slippage (0.3% = multiply by 1.003)\n * Covers HyperLiquid's max taker fee (0.035%) with comfortable margin\n */\n BufferMultiplier: 1.003,\n\n /**\n * Desired buffer to keep on HIP-3 DEX after auto-rebalance (USDC amount)\n * Small buffer allows quick follow-up orders without transfers\n */\n RebalanceDesiredBuffer: 0.1,\n\n /**\n * Minimum excess threshold to trigger auto-rebalance (USDC amount)\n * Prevents unnecessary transfers for tiny amounts\n */\n RebalanceMinThreshold: 0.1,\n} as const;\n\n// Progress bar constants\nexport const INITIAL_AMOUNT_UI_PROGRESS = 10;\nexport const WITHDRAWAL_PROGRESS_STAGES = [\n 25, 35, 45, 55, 65, 75, 85, 90, 95, 98,\n];\nexport const PROGRESS_BAR_COMPLETION_DELAY_MS = 500;\n"]}
|
|
@@ -207,6 +207,23 @@ export declare function toLighterInteger(value: number, decimals: number): numbe
|
|
|
207
207
|
* @returns Human-readable amount.
|
|
208
208
|
*/
|
|
209
209
|
export declare function fromLighterInteger(value: number, decimals: number): number;
|
|
210
|
+
/**
|
|
211
|
+
* Check the size precision accepted by the maker sizing calculation.
|
|
212
|
+
*
|
|
213
|
+
* @param decimals - Venue size decimals.
|
|
214
|
+
* @returns Whether the value can be used as a size precision.
|
|
215
|
+
*/
|
|
216
|
+
export declare function isLighterOrderSizeDecimals(decimals: number): boolean;
|
|
217
|
+
/**
|
|
218
|
+
* Read both maker minimums as a pair. Sizing requires both values.
|
|
219
|
+
*
|
|
220
|
+
* @param market - Market metadata from `orderBooks`.
|
|
221
|
+
* @returns The parsed minimums, or null when either is invalid.
|
|
222
|
+
*/
|
|
223
|
+
export declare function getLighterMakerMinimums(market: Pick<LighterOrderBookMeta, 'minBaseAmount' | 'minQuoteAmount'>): {
|
|
224
|
+
minBase: number;
|
|
225
|
+
minQuote: number;
|
|
226
|
+
} | null;
|
|
210
227
|
/**
|
|
211
228
|
* Compute the minimum order base size for a market that satisfies both
|
|
212
229
|
* `minBaseAmount` and `minQuoteAmount` at a given price.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lighterConfig.d.ts","sourceRoot":"","sources":["../../src/constants/lighterConfig.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EACV,gBAAgB,EAChB,cAAc,EACd,oBAAoB,EACrB,MAAM,2BAA2B,CAAC;AAMnC;;GAEG;AACH,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAC5C,eAAO,MAAM,wBAAwB,MAAM,CAAC;AAE5C;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAIjE;AAMD;;GAEG;AACH,eAAO,MAAM,iBAAiB,EAAE,gBAS/B,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,cAAc,GAAG,MAAM,CAEtE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,OAAO,EAA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