-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathHyperLiquidProvider.ts
More file actions
8627 lines (7720 loc) · 286 KB
/
HyperLiquidProvider.ts
File metadata and controls
8627 lines (7720 loc) · 286 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { CaipAccountId, hasProperty } from '@metamask/utils';
import type { Hex } from '@metamask/utils';
import type {
ExchangeClient,
UserAbstractionResponse,
} from '@nktkas/hyperliquid';
import { v4 as uuidv4 } from 'uuid';
import type { CandlePeriod } from '../constants/chartConfig';
import {
PERPS_EVENT_PROPERTY,
PERPS_EVENT_VALUE,
} from '../constants/eventNames';
import {
BASIS_POINTS_DIVISOR,
BUILDER_FEE_CONFIG,
FEE_RATES,
getBridgeInfo,
getChainId,
HIP3_ASSET_MARKET_TYPES,
HIP3_FEE_CONFIG,
HIP3_MARGIN_CONFIG,
HYPERLIQUID_WITHDRAWAL_MINUTES,
REFERRAL_CONFIG,
SPOT_ASSET_ID_OFFSET,
TRADING_DEFAULTS,
USDC_DECIMALS,
USDH_CONFIG,
} from '../constants/hyperLiquidConfig';
import {
ORDER_SLIPPAGE_CONFIG,
PERFORMANCE_CONFIG,
PERPS_CONSTANTS,
TP_SL_CONFIG,
WITHDRAWAL_CONSTANTS,
} from '../constants/perpsConfig';
import { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig';
import { PERPS_ERROR_CODES } from '../perpsErrorCodes';
import { DexDiscoveryCacheManager } from '../services/DexDiscoveryCacheManager';
import {
HyperLiquidClientService,
WebSocketConnectionState,
} from '../services/HyperLiquidClientService';
import { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService';
import { HyperLiquidWalletService } from '../services/HyperLiquidWalletService';
import {
TradingReadinessCache,
PerpsSigningCache,
} from '../services/TradingReadinessCache';
import { PerpsAnalyticsEvent } from '../types';
import type {
AccountState,
AssetRoute,
BatchCancelOrdersParams,
CancelOrderParams,
CancelOrderResult,
CancelOrdersResult,
CandleData,
ClosePositionParams,
ClosePositionsParams,
ClosePositionsResult,
DepositParams,
DisconnectResult,
EditOrderParams,
FeeCalculationParams,
FeeCalculationResult,
Funding,
GetAccountStateParams,
GetAvailableDexsParams,
GetFundingParams,
GetHistoricalPortfolioParams,
GetMarketsParams,
GetOrderFillsParams,
GetOrdersParams,
GetOrFetchFillsParams,
GetPositionsParams,
GetSupportedPathsParams,
HistoricalPortfolioResult,
InitializeResult,
PerpsPlatformDependencies,
PerpsProvider,
LiquidationPriceParams,
LiveDataConfig,
MaintenanceMarginParams,
MarginResult,
MarketInfo,
Order,
OrderFill,
OrderParams,
OrderResult,
PerpsMarketData,
Position,
ReadyToTradeResult,
SubscribeAccountParams,
SubscribeCandlesParams,
SubscribeOICapsParams,
SubscribeOrderBookParams,
SubscribeOrderFillsParams,
SubscribeOrdersParams,
SubscribePositionsParams,
SubscribePricesParams,
ToggleTestnetResult,
TransferBetweenDexsParams,
TransferBetweenDexsResult,
UpdateMarginParams,
UpdatePositionTPSLParams,
UserHistoryItem,
WithdrawParams,
WithdrawResult,
RawLedgerUpdate,
PerpsReadOptions,
} from '../types';
import type {
SDKOrderParams,
MetaResponse,
PerpsAssetCtx,
FrontendOrder,
SpotMetaResponse,
} from '../types/hyperliquid-types';
import {
HL_ABSTRACTION_WIRE,
HL_UNIFIED_ACCOUNT_MODE,
hyperLiquidModeFoldsSpot,
} from '../types/hyperliquid-types';
import type { PerpsControllerMessengerBase } from '../types/messenger';
import type { ExtendedAssetMeta, ExtendedPerpDex } from '../types/perps-types';
import {
addSpotBalanceToAccountState,
aggregateAccountStates,
} from '../utils/accountUtils';
import { ensureError } from '../utils/errorUtils';
import {
adaptAccountStateFromSDK,
adaptHyperLiquidLedgerUpdateToUserHistoryItem,
adaptMarketFromSDK,
adaptOrderFromSDK,
adaptPositionFromSDK,
buildAssetMapping,
formatHyperLiquidPrice,
formatHyperLiquidSize,
parseAssetName,
} from '../utils/hyperLiquidAdapter';
import {
createErrorResult,
getMaxOrderValue,
getSupportedPaths,
validateAssetSupport,
validateBalance,
validateCoinExists,
validateDepositParams,
validateOrderParams,
validateWithdrawalParams,
} from '../utils/hyperLiquidValidation';
import { transformMarketData } from '../utils/marketDataTransform';
import {
compileMarketPattern,
shouldIncludeMarket,
} from '../utils/marketUtils';
import type { CompiledMarketPattern } from '../utils/marketUtils';
import {
buildOrdersArray,
calculateFinalPositionSize,
calculateOrderPriceAndSize,
} from '../utils/orderCalculations';
import {
createStandaloneInfoClient,
queryStandaloneClearinghouseStates,
queryStandaloneOpenOrders,
} from '../utils/standaloneInfoClient';
// getStreamManagerInstance removed: use this.#deps.streamManager instead
/**
* Type guard to check if a status is an object (not a string literal like "waitingForFill")
* The SDK returns status as a union of object types and string literals.
*
* @param status - The current status.
* @returns The result of the operation.
*/
const isStatusObject = (status: unknown): status is Record<string, unknown> =>
typeof status === 'object' && status !== null;
// Helper method parameter interfaces (module-level for class-dependent methods only)
type GetAssetInfoParams = {
symbol: string;
dexName: string | null;
};
type DexFetchFailureStep = 'metaAndAssetCtxs' | 'allMids';
type DexFetchResult = {
dex: string | null;
meta: MetaResponse | null;
assetCtxs: PerpsAssetCtx[];
allMids: Record<string, string>;
success: boolean;
failedStep?: DexFetchFailureStep;
errorMessage?: string;
};
type DexQueryResult<TResult> = {
dex: string | null;
data: TResult;
};
type DexQueryResponse<TResult> = {
results: DexQueryResult<TResult>[];
failedDexs: { dex: string | null; error: Error }[];
};
type CachedMarketDataSnapshot = {
data: PerpsMarketData[];
timestamp: number;
contributingDexs: string[];
failedDexs: string[];
};
type GetAssetInfoResult = {
assetInfo: {
name: string;
szDecimals: number;
maxLeverage: number;
};
currentPrice: number;
meta: MetaResponse;
};
type PrepareAssetForTradingParams = {
symbol: string;
assetId: number;
leverage?: number;
};
type HandleHip3PreOrderParams = {
dexName: string;
symbol: string;
orderPrice: number;
positionSize: number;
leverage: number;
isBuy: boolean;
maxLeverage: number;
};
type HandleHip3PreOrderResult = {
transferInfo: { amount: number; sourceDex: string } | null;
};
type SubmitOrderWithRollbackParams = {
orders: SDKOrderParams[];
grouping: 'na' | 'normalTpsl' | 'positionTpsl';
isHip3Order: boolean;
dexName: string | null;
transferInfo: { amount: number; sourceDex: string } | null;
symbol: string;
assetId: number;
};
type HandleOrderErrorParams = {
error: unknown;
symbol: string;
orderType: 'market' | 'limit';
isBuy: boolean;
};
type GetOrFetchPriceParams = {
symbol: string;
dexName: string | null;
};
/**
* HyperLiquid provider implementation
*
* Implements the PerpsProvider interface for HyperLiquid protocol.
* Uses the @nktkas/hyperliquid SDK for all operations.
* Delegates to service classes for client management, wallet integration, and subscriptions.
*
* HIP-3 Balance Management:
* Attempts to use HyperLiquid's native DEX abstraction for automatic collateral transfers.
* If not supported, falls back to programmatic balance management using SDK's sendAsset.
*/
export class HyperLiquidProvider implements PerpsProvider {
readonly protocolId = 'hyperliquid';
// Platform dependencies for logging and debugging
readonly #deps: PerpsPlatformDependencies;
// Service instances
readonly #clientService: HyperLiquidClientService;
readonly #walletService: HyperLiquidWalletService;
readonly #subscriptionService: HyperLiquidSubscriptionService;
// Asset mapping
readonly #symbolToAssetId = new Map<string, number>();
// Cache for user fee rates to avoid excessive API calls
readonly #userFeeCache = new Map<
string,
{
perpsTakerRate: number;
perpsMakerRate: number;
spotTakerRate: number;
spotMakerRate: number;
timestamp: number;
ttl: number;
}
>();
// Cache for max leverage values to avoid excessive API calls
readonly #maxLeverageCache = new Map<
string,
{ value: number; timestamp: number }
>();
// Cache for raw meta responses (shared across methods to avoid redundant API calls)
// Filtering is applied on-demand (cheap array operations) - no need for separate processed cache
readonly #cachedMetaByDex = new Map<string, MetaResponse>();
// Last known-good market list for stale fallback when every enabled DEX fails in one fetch window.
#cachedMarketDataWithPrices: CachedMarketDataSnapshot | null = null;
// Session cache for spot metadata (contains USDC/USDH token info for HIP-3 collateral checks)
// Pre-fetched in ensureReadyForTrading() to avoid API failures during order placement
#cachedSpotMeta: SpotMetaResponse | null = null;
// Unified DEX discovery cache — single source of truth for all perpDexs() derivatives.
// Replaces three separate caches to eliminate desync bugs by construction.
// All writes go through #dexDiscoveryCache.update(); readers use .state.
readonly #dexDiscoveryCache: DexDiscoveryCacheManager;
// Session cache for referral state (cleared on disconnect/reconnect)
// Key: `network:userAddress`, Value: true if referral is set
readonly #referralCheckCache = new Map<string, boolean>();
// Session cache for builder fee approval state (cleared on disconnect/reconnect)
// Key: `network:userAddress`, Value: true if builder fee is approved
readonly #builderFeeCheckCache = new Map<string, boolean>();
// Pending promise trackers for deduplicating concurrent calls
// Prevents multiple signature requests when methods called simultaneously
#ensureReadyPromise: Promise<void> | null = null;
readonly #pendingBuilderFeeApprovals = new Map<string, Promise<void>>();
// Pre-compiled patterns for fast filtering
readonly #compiledAllowlistPatterns: CompiledMarketPattern[] = [];
readonly #compiledBlocklistPatterns: CompiledMarketPattern[] = [];
// Fee discount context for MetaMask reward discounts (in basis points)
#userFeeDiscountBips?: number;
// Feature flag configuration for HIP-3 market filtering
readonly #hip3Enabled: boolean;
readonly #allowlistMarkets: string[];
readonly #blocklistMarkets: string[];
// Emergency kill-switch for the Unified Account migration flow. Defaults
// to true and is the expected production state after HL's DEX Abstraction
// deprecation. Kept as a constructor option (not removed) so we can
// disable the migration via a hot-fix release if a regression surfaces
// in the wild — flipping this to false reverts to the legacy programmatic
// HIP-3 transfer path that already lives in the codebase.
#useUnifiedAccount: boolean;
// True once DEX discovery has succeeded with real data (not a fallback).
// When false, #ensureReadyPromise is reset after each init so the next
// caller retries DEX discovery instead of reusing a degraded mapping.
#dexDiscoveryComplete = false;
// True when the most recent #ensureUnifiedAccountEnabled run ended in a
// transient state that warrants retry (silent agent-key failure, REST
// userAbstraction lookup failure, or keyring locked). #ensureReady resets
// its memoized promise when this is set so the next entry retries the
// migration instead of returning the cached resolved promise.
#unifiedAccountSetupNeedsRetry = false;
// Pending promise to deduplicate concurrent getValidatedDexs() calls
#pendingValidatedDexsPromise: Promise<(string | null)[]> | null = null;
// Cache for USDC token ID from spot metadata
#cachedUsdcTokenId?: string;
// Error mappings from HyperLiquid API errors to standardized PERPS_ERROR_CODES
readonly #errorMappings = {
'isolated position does not have sufficient margin available to decrease leverage':
PERPS_ERROR_CODES.ORDER_LEVERAGE_REDUCTION_FAILED,
'could not immediately match': PERPS_ERROR_CODES.IOC_CANCEL,
};
// Track whether clients have been initialized (lazy initialization)
#clientsInitialized = false;
// Promise-based lock to prevent race conditions in concurrent initialization
#initializationPromise: Promise<void> | null = null;
readonly #messenger: PerpsControllerMessengerBase;
readonly #builderAddressTestnet?: string;
readonly #builderAddressMainnet?: string;
constructor(options: {
isTestnet?: boolean;
hip3Enabled?: boolean;
allowlistMarkets?: string[];
blocklistMarkets?: string[];
useUnifiedAccount?: boolean;
platformDependencies: PerpsPlatformDependencies;
messenger: PerpsControllerMessengerBase;
initialAssetMapping?: [string, number][];
builderAddressTestnet?: string;
builderAddressMainnet?: string;
}) {
this.#deps = options.platformDependencies;
this.#messenger = options.messenger;
this.#builderAddressTestnet = options.builderAddressTestnet;
this.#builderAddressMainnet = options.builderAddressMainnet;
const isTestnet = options.isTestnet ?? false;
// Dev-friendly defaults: Enable all markets by default for easier testing (discovery mode)
this.#hip3Enabled = options.hip3Enabled ?? false;
this.#allowlistMarkets = options.allowlistMarkets ?? [];
this.#blocklistMarkets = options.blocklistMarkets ?? [];
// Attempt unified account mode, fallback to programmatic transfer if unsupported
this.#useUnifiedAccount = options.useUnifiedAccount ?? true;
// Initialize services with injected platform dependencies
this.#clientService = new HyperLiquidClientService(this.#deps, {
isTestnet,
});
this.#dexDiscoveryCache = new DexDiscoveryCacheManager({
isTestnetMode: (): boolean => this.#clientService.isTestnetMode(),
debugLogger: this.#deps.debugLogger,
getAllowlistMarkets: (): string[] => this.#allowlistMarkets,
});
this.#walletService = new HyperLiquidWalletService(
this.#deps,
this.#messenger,
{
isTestnet,
},
);
this.#subscriptionService = new HyperLiquidSubscriptionService(
this.#clientService,
this.#walletService,
this.#deps,
this.#hip3Enabled,
[], // enabledDexs - will be populated after DEX discovery in buildAssetMapping
this.#allowlistMarkets,
this.#blocklistMarkets,
);
// NOTE: Clients are NOT initialized here - they'll be initialized lazily
// when first needed. This avoids accessing Engine.context before it's ready.
// Pre-compile filter patterns for performance (invalid patterns are skipped)
this.#compiledAllowlistPatterns = this.#compilePatternsSafely(
this.#allowlistMarkets,
'allowlist',
);
this.#compiledBlocklistPatterns = this.#compilePatternsSafely(
this.#blocklistMarkets,
'blocklist',
);
// Populate initial asset mapping if provided (used for DI in tests)
if (options.initialAssetMapping) {
for (const [symbol, assetId] of options.initialAssetMapping) {
this.#symbolToAssetId.set(symbol, assetId);
}
}
// Debug: Confirm batch methods exist and show HIP-3 config
this.#deps.debugLogger.log('[HyperLiquidProvider] Constructor complete', {
hasBatchCancel: typeof this.cancelOrders === 'function',
hasBatchClose: typeof this.closePositions === 'function',
protocolId: this.protocolId,
hip3Enabled: this.#hip3Enabled,
allowlistMarkets: this.#allowlistMarkets,
blocklistMarkets: this.#blocklistMarkets,
isTestnet,
});
}
/**
* Compile market patterns safely, skipping any that fail validation.
* Prevents a single bad pattern from crashing the entire constructor.
*
* @param patterns - The array of patterns to validate.
* @param listName - The name of the list for logging context.
* @returns The result of the operation.
*/
#compilePatternsSafely(
patterns: string[],
listName: string,
): CompiledMarketPattern[] {
const compiled: CompiledMarketPattern[] = [];
for (const pattern of patterns) {
try {
compiled.push({ pattern, matcher: compileMarketPattern(pattern) });
} catch (error) {
this.#deps.logger.error(
ensureError(error, `HyperLiquidProvider.compilePatternsSafely`),
this.#getErrorContext('compilePatternsSafely', { listName, pattern }),
);
}
}
return compiled;
}
/**
* Initialize HyperLiquid SDK clients (lazy initialization)
*
* This is called on first API operation to ensure Engine.context is ready.
* Creating the wallet adapter requires accessing Engine.context.AccountTreeController,
* which may not be available during early app initialization.
*
* IMPORTANT: This method awaits the WebSocket transport.ready() to ensure
* the connection is fully established before marking initialization complete.
*/
async #ensureClientsInitialized(): Promise<void> {
if (this.#clientsInitialized) {
return; // Already initialized
}
// Reuse existing initialization promise if one is in progress
// This prevents race conditions when multiple methods call concurrently
if (this.#initializationPromise) {
await this.#initializationPromise;
return;
}
// Create and cache the initialization promise
this.#initializationPromise = (async (): Promise<void> => {
// Double-check after acquiring the "lock"
if (this.#clientsInitialized) {
return;
}
const wallet = this.#walletService.createWalletAdapter();
await this.#clientService.initialize(wallet);
// Set termination callback for logging when WebSocket terminates
// Note: Do NOT restore subscriptions here - termination means connection failed permanently
this.#clientService.setOnTerminateCallback((error: Error) => {
this.#deps.debugLogger.log(
'[HyperLiquidProvider] WebSocket terminated',
{
error: error.message,
},
);
});
// Set reconnection callback to restore subscriptions after successful reconnection
// This is called in handleConnectionDrop() after the WebSocket reconnects successfully
this.#clientService.setOnReconnectCallback(async () => {
try {
this.#deps.debugLogger.log(
'[HyperLiquidProvider] WebSocket reconnected, restoring subscriptions',
);
await this.#subscriptionService.restoreSubscriptions();
this.#deps.streamManager.clearAllChannels();
} catch (restoreError) {
this.#deps.debugLogger.log(
'[HyperLiquidProvider] Failed to restore subscriptions',
restoreError,
);
}
});
// Only set flag AFTER successful initialization
this.#clientsInitialized = true;
this.#deps.debugLogger.log(
'[HyperLiquidProvider] Clients initialized lazily',
);
})();
try {
await this.#initializationPromise;
} finally {
// Clear promise after completion (success or failure)
// so future calls can retry if needed
this.#initializationPromise = null;
}
}
/**
* Attempt to enable HyperLiquid Unified Account mode for HIP-3 orders
*
* If successful, HyperLiquid automatically manages collateral transfers for HIP-3 orders.
* If not supported, disables the flag to trigger programmatic transfer fallback.
*
* IMPORTANT: Uses global singleton cache to prevent repeated signing requests
* across provider reconnections (critical for hardware wallets).
*
* @param options - Optional configuration.
* @param options.allowUserSigning - When true, runs the EIP-712 user-signed migration for `dexAbstraction` accounts. Defaults to false so init does not surface a signing prompt; action-time entry points (trading, withdraw) pass true.
* @private
*/
async #ensureUnifiedAccountEnabled(options?: {
allowUserSigning?: boolean;
}): Promise<void> {
// dexAbstraction → unifiedAccount requires an EIP-712 prompt (HL blocks
// the agent path for that transition). Init calls with allowUserSigning=false so
// viewing the Perps section never surfaces a signing dialog. Trading and
// withdraw entry points pass allowUserSigning=true to drive the migration when
// the user actually intends to act.
const allowUserSigning = options?.allowUserSigning ?? false;
// Optimistic reset — set true below only at the failure points that
// warrant retry (silent agent failure, REST lookup failure, keyring
// locked). Final-state outcomes (success, prompted-failure cached,
// already-on-compatible, defer, unknown mode, feature off) leave it
// false so #ensureReady can keep the memoized promise.
this.#unifiedAccountSetupNeedsRetry = false;
if (!this.#useUnifiedAccount) {
return; // Feature disabled
}
const userAddress = await this.#walletService.getUserAddressWithDefault();
const network = this.#clientService.isTestnetMode() ? 'testnet' : 'mainnet';
// Check global cache first to avoid repeated signing requests
// This is CRITICAL for hardware wallets to prevent QR popup spam
const cachedStatus = TradingReadinessCache.get(network, userAddress);
if (cachedStatus?.attempted) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Unified Account setup already attempted (from global cache)',
{
user: userAddress,
network,
enabled: cachedStatus.enabled,
note: 'Skipping to prevent repeated signing requests',
},
);
return;
}
// Check if another provider instance is currently attempting this operation
// This prevents concurrent signing attempts across providers during reconnection
const inFlightPromise = PerpsSigningCache.isInFlight(
'unifiedAccount',
network,
userAddress,
);
if (inFlightPromise) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Unified Account setup in-flight, waiting...',
{ network, userAddress },
);
await inFlightPromise;
// The other instance may have finished without writing the cache (e.g.
// an init-time call deferred a dexAbstraction migration). If the cache
// is still empty and we are an action-time caller (allowUserSigning=true),
// we must run our own attempt — otherwise the trade/withdraw would
// proceed in the deprecated mode.
const postWaitCache = TradingReadinessCache.get(network, userAddress);
if (postWaitCache?.attempted) {
return;
}
// Fall through to acquire our own lock and retry.
}
// Set in-flight lock to prevent concurrent attempts
const completeInFlight = PerpsSigningCache.setInFlight(
'unifiedAccount',
network,
userAddress,
);
let currentMode: UserAbstractionResponse | undefined;
try {
// Re-check cache after acquiring lock (another provider might have finished)
const recheckCache = TradingReadinessCache.get(network, userAddress);
if (recheckCache?.attempted) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Unified Account setup completed by another provider',
{ network, userAddress },
);
completeInFlight();
return;
}
const infoClient = this.#clientService.getInfoClient();
// Check current abstraction mode on-chain
currentMode = await infoClient.userAbstraction({
user: userAddress,
});
if (
currentMode === 'unifiedAccount' ||
currentMode === 'portfolioMargin'
) {
// portfolioMargin is a superset of unifiedAccount — it already supports
// auto-collateral management for HIP-3 orders and is more capital-efficient.
// Downgrading portfolio margin users to unifiedAccount would be harmful,
// so we treat both modes as already-enabled and skip migration.
this.#deps.debugLogger.log(
'HyperLiquidProvider: Account already in a compatible mode, skipping migration',
{ user: userAddress, network, mode: currentMode },
);
this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,
[PERPS_EVENT_PROPERTY.STATUS]:
PERPS_EVENT_VALUE.STATUS.ALREADY_ENABLED,
});
TradingReadinessCache.set(network, userAddress, {
attempted: true,
enabled: true,
});
// Record the resolved mode in the subscription service so the next
// aggregation folds spot correctly without waiting for #refreshSpotState.
this.#subscriptionService.setUserAbstractionMode(
userAddress,
currentMode,
);
completeInFlight();
return;
}
// Defer the user-signed transition until the user attempts an action.
// Cache is intentionally left untouched so the next entry re-evaluates;
// the read-only userAbstraction call is cheap and gated by the in-flight
// lock, preventing concurrent prompts.
if (currentMode === 'dexAbstraction' && !allowUserSigning) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Deferring dexAbstraction → unifiedAccount migration to action time',
{ user: userAddress, network },
);
completeInFlight();
return;
}
// Bail on unknown modes BEFORE firing analytics or attempting dispatch.
// Keeps `migration_required` actionable (only fires for modes we can
// actually migrate) and avoids re-emitting on every reconnection.
if (
currentMode !== 'dexAbstraction' &&
currentMode !== 'default' &&
currentMode !== 'disabled'
) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Unknown abstraction mode, skipping Unified Account migration',
{ user: userAddress, network, mode: currentMode },
);
completeInFlight();
return;
}
// Track which mode users are currently on before we attempt migration.
// This tells us the distribution of legacy modes across our user base.
this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,
[PERPS_EVENT_PROPERTY.STATUS]:
PERPS_EVENT_VALUE.STATUS.MIGRATION_REQUIRED,
});
// Enable Unified Account mode.
// - default / disabled: agent wallet can do this silently (no prompt)
// - dexAbstraction: HL blocks the agent transition — requires the user's main
// wallet to sign an EIP-712 action via userSetAbstraction (one-time prompt)
this.#deps.debugLogger.log(
'HyperLiquidProvider: Enabling Unified Account mode',
{
user: userAddress,
network,
previousMode: currentMode,
note: 'HyperLiquid will auto-manage collateral for HIP-3 orders',
},
);
const exchangeClient = this.#clientService.getExchangeClient();
if (currentMode === 'dexAbstraction') {
// Requires EIP-712 signature from the user's main wallet (one-time migration).
// HL blocks the dexAbstraction → unifiedAccount transition via the agent wallet,
// so userSetAbstraction (user-signed) is the only path for legacy users.
await exchangeClient.userSetAbstraction({
user: userAddress,
abstraction: HL_UNIFIED_ACCOUNT_MODE,
});
} else {
// default / disabled — silent agent transition, no user prompt
await exchangeClient.agentSetAbstraction({
abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,
});
}
this.#deps.debugLogger.log(
'✅ HyperLiquidProvider: Unified Account enabled successfully',
);
this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
[PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,
[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,
[PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.SUCCESS,
});
TradingReadinessCache.set(network, userAddress, {
attempted: true,
enabled: true,
});
// Record the post-migration mode in the subscription service so it
// immediately re-aggregates with fold=true and surfaces the unified
// balance rather than waiting for the next #refreshSpotState.
this.#subscriptionService.setUserAbstractionMode(
userAddress,
HL_UNIFIED_ACCOUNT_MODE,
);
completeInFlight();
} catch (error) {
// If keyring is locked, don't cache so it retries when unlocked
if (ensureError(error).message === PERPS_ERROR_CODES.KEYRING_LOCKED) {
this.#deps.debugLogger.log(
'[ensureUnifiedAccountEnabled] Keyring locked, will retry later',
);
this.#unifiedAccountSetupNeedsRetry = true;
completeInFlight();
return;
}
// Cache failure ONLY for the user-prompted path
// (`dexAbstraction → unifiedAccount` via `userSetAbstraction`). The
// rationale for caching is "don't re-prompt a user who already saw the
// signature dialog and rejected it" — that doesn't apply to:
// - Read-only userAbstraction lookup failures (no prompt; transient).
// - Silent agent-key paths (`default`/`disabled` → `agentSetAbstraction`
// does not show a UI prompt; failures are typically transient HL
// outages and pinning them would leave users stuck in the
// deprecated mode for the rest of the session).
// Action-time retries pick up the unmigrated state and try again.
if (currentMode === 'dexAbstraction') {
TradingReadinessCache.set(network, userAddress, {
attempted: true,
enabled: false,
});
} else {
// Silent agent-key failure (default/disabled) or read-only
// userAbstraction lookup failure — neither is a final state, so
// signal #ensureReady to drop its memoized promise and retry on
// the next entry instead of pinning the user in the deprecated
// mode for the provider's lifetime.
this.#unifiedAccountSetupNeedsRetry = true;
}
const errorMessage = ensureError(
error,
'HyperLiquidProvider.ensureUnifiedAccountEnabled',
).message;
this.#deps.debugLogger.log(
'HyperLiquidProvider: Unified Account setup failed',
{
user: userAddress,
network,
error: errorMessage,
// Cache writes only happen on the user-prompted dexAbstraction
// path (see P2-B logic above). Reflect that here so retry
// behaviour is debuggable from the log alone.
cached: currentMode === 'dexAbstraction',
},
);
this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
...(currentMode && {
[PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,
[PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: HL_UNIFIED_ACCOUNT_MODE,
}),
[PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.FAILED,
[PERPS_EVENT_PROPERTY.ERROR_MESSAGE]: errorMessage,
});
completeInFlight();
this.#deps.logger.error(
ensureError(error, 'HyperLiquidProvider.ensureUnifiedAccountEnabled'),
this.#getErrorContext('ensureUnifiedAccountEnabled', {
note: 'Could not enable Unified Account (user rejected, or network error)',
}),
);
}
}
/**
* Ensure clients are initialized and asset mapping is loaded
* Asset mapping is built once on first call and reused for the provider's lifetime
* since HIP-3 configuration is immutable after construction
*/
async #ensureReady(): Promise<void> {
// If already initializing or completed, wait for/return that promise
// This prevents duplicate initialization flows when multiple methods called concurrently
if (this.#ensureReadyPromise) {
this.#deps.debugLogger.log(
'[ensureReady] Reusing existing initialization promise',
);
await this.#ensureReadyPromise;
return;
}
this.#deps.debugLogger.log('[ensureReady] Starting new initialization');
// Create and track initialization promise
this.#ensureReadyPromise = (async (): Promise<void> => {
// Lazy initialization: ensure clients are created (safe after Engine.context is ready)
// This awaits WebSocket transport.ready() to ensure connection is established
await this.#ensureClientsInitialized();
// Verify clients are properly initialized
this.#clientService.ensureInitialized();
// Build asset mapping on first call, or retry if DEX discovery previously failed
if (this.#symbolToAssetId.size === 0 || !this.#dexDiscoveryComplete) {
this.#deps.debugLogger.log(
'HyperLiquidProvider: Building asset mapping',
{
hip3Enabled: this.#hip3Enabled,
allowlistMarkets: this.#allowlistMarkets,
blocklistMarkets: this.#blocklistMarkets,
},
);
await this.#buildAssetMapping();
}
// Attempt Unified Account migration as early as possible so users aren't
// blocked when they try to trade. Software-wallet dexAbstraction users can
// complete the one-time EIP-712 migration during initial setup so the first
// trade sees the unified balance. Hardware wallets remain deferred to
// action time to avoid QR / Ledger prompt spam while browsing.
await this.#ensureUnifiedAccountEnabled({
allowUserSigning: !this.#walletService.isSelectedHardwareWallet(),
});
})();
// Await initialization - keep the promise so subsequent calls resolve immediately
// The promise is only reset in disconnect() for clean reconnection,
// or when DEX discovery was degraded so the next caller retries.
await this.#ensureReadyPromise;
if (!this.#dexDiscoveryComplete) {
// DEX discovery failed transiently — reset so next call retries.
// Trading still works (main DEX mapping is populated), but HIP-3 markets
// will be re-discovered on the next #ensureReady() call.
this.#ensureReadyPromise = null;
} else if (this.#unifiedAccountSetupNeedsRetry) {
// Silent migration / lookup / keyring-locked failure left the cache
// empty. Without resetting the memoized promise, subsequent
// #ensureReady calls would skip retry and the user would be stuck
// in the deprecated mode for the provider's lifetime.
this.#ensureReadyPromise = null;
}
this.#deps.debugLogger.log('[ensureReady] Initialization complete');
}
/**
* Ensure provider is ready for TRADING operations (signing required)
*
* This method performs additional setup that requires user signatures:
* - DEX abstraction enablement (for HIP-3 auto-transfers)
* - Builder fee approval (required for orders)
* - Referral code setup (attribution)
*
* These operations are DEFERRED from ensureReady() to avoid QR popup spam
* when users are just viewing the Perps section (critical for hardware wallets).
*
* Call this method before any trading operation (placeOrder, cancelOrder, etc.)
*/
#tradingSetupPromise: Promise<void> | null = null;
#tradingSetupComplete = false;
async #ensureReadyForTrading(): Promise<void> {
// First ensure basic initialization is complete
await this.#ensureReady();
// dexAbstraction users were deferred during init to avoid an EIP-712 prompt
// on Perps section open. Drive the migration here, gated by its own cache so
// already-migrated or already-rejected users are not re-prompted.
await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });
// If trading setup already complete, return immediately
if (this.#tradingSetupComplete) {
return;
}
// If trading setup is in progress, wait for it
if (this.#tradingSetupPromise) {
this.#deps.debugLogger.log(
'[ensureReadyForTrading] Waiting for in-progress trading setup',
);
await this.#tradingSetupPromise;
return;
}
this.#deps.debugLogger.log(
'[ensureReadyForTrading] Starting trading setup (may require signatures)',
);