@metamask-previews/perps-controller 18.0.1-preview-c92646a67 → 19.0.0-preview-cdde826

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.
Files changed (100) hide show
  1. package/CHANGELOG.md +69 -1
  2. package/README.md +69 -0
  3. package/dist/PerpsController-method-action-types.d.ts +65 -1
  4. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  5. package/dist/PerpsController-method-action-types.js.map +1 -1
  6. package/dist/PerpsController.d.ts +56 -1
  7. package/dist/PerpsController.d.ts.map +1 -1
  8. package/dist/PerpsController.js +181 -2
  9. package/dist/PerpsController.js.map +1 -1
  10. package/dist/constants/hyperLiquidConfig.d.ts +10 -0
  11. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  12. package/dist/constants/hyperLiquidConfig.js +10 -0
  13. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  14. package/dist/constants/orderTypes.d.ts +3 -0
  15. package/dist/constants/orderTypes.d.ts.map +1 -1
  16. package/dist/constants/orderTypes.js +3 -0
  17. package/dist/constants/orderTypes.js.map +1 -1
  18. package/dist/index.d.ts +4 -4
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +1 -1
  21. package/dist/index.js.map +1 -1
  22. package/dist/perpsErrorCodes.d.ts.map +1 -1
  23. package/dist/perpsErrorCodes.js +3 -0
  24. package/dist/perpsErrorCodes.js.map +1 -1
  25. package/dist/providers/AggregatedPerpsProvider.d.ts +9 -0
  26. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  27. package/dist/providers/AggregatedPerpsProvider.js +46 -0
  28. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  29. package/dist/providers/HyperLiquidProvider.d.ts +18 -1
  30. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  31. package/dist/providers/HyperLiquidProvider.js +747 -186
  32. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  33. package/dist/providers/LighterProvider.d.ts +10 -0
  34. package/dist/providers/LighterProvider.d.ts.map +1 -1
  35. package/dist/providers/LighterProvider.js +93 -10
  36. package/dist/providers/LighterProvider.js.map +1 -1
  37. package/dist/services/HyperLiquidClientService.d.ts +4 -17
  38. package/dist/services/HyperLiquidClientService.d.ts.map +1 -1
  39. package/dist/services/HyperLiquidClientService.js.map +1 -1
  40. package/dist/services/HyperLiquidWalletService.d.ts +27 -29
  41. package/dist/services/HyperLiquidWalletService.d.ts.map +1 -1
  42. package/dist/services/HyperLiquidWalletService.js +101 -40
  43. package/dist/services/HyperLiquidWalletService.js.map +1 -1
  44. package/dist/services/LighterClientService.js +2 -2
  45. package/dist/services/LighterClientService.js.map +1 -1
  46. package/dist/services/LighterWalletService.d.ts +13 -8
  47. package/dist/services/LighterWalletService.d.ts.map +1 -1
  48. package/dist/services/LighterWalletService.js +41 -22
  49. package/dist/services/LighterWalletService.js.map +1 -1
  50. package/dist/services/MarketDataService.d.ts.map +1 -1
  51. package/dist/services/MarketDataService.js +14 -3
  52. package/dist/services/MarketDataService.js.map +1 -1
  53. package/dist/services/RewardsIntegrationService.d.ts +5 -4
  54. package/dist/services/RewardsIntegrationService.d.ts.map +1 -1
  55. package/dist/services/RewardsIntegrationService.js +35 -20
  56. package/dist/services/RewardsIntegrationService.js.map +1 -1
  57. package/dist/services/TradingReadinessCache.js.map +1 -1
  58. package/dist/services/TradingService.d.ts.map +1 -1
  59. package/dist/services/TradingService.js +37 -21
  60. package/dist/services/TradingService.js.map +1 -1
  61. package/dist/services/accountSigner.d.ts +18 -0
  62. package/dist/services/accountSigner.d.ts.map +1 -0
  63. package/dist/services/accountSigner.js +23 -0
  64. package/dist/services/accountSigner.js.map +1 -0
  65. package/dist/services/agentSigner.d.ts +61 -0
  66. package/dist/services/agentSigner.d.ts.map +1 -0
  67. package/dist/services/agentSigner.js +87 -0
  68. package/dist/services/agentSigner.js.map +1 -0
  69. package/dist/services/causeChain.d.ts +10 -0
  70. package/dist/services/causeChain.d.ts.map +1 -0
  71. package/dist/services/causeChain.js +21 -0
  72. package/dist/services/causeChain.js.map +1 -0
  73. package/dist/services/providerNetwork.d.ts +13 -0
  74. package/dist/services/providerNetwork.d.ts.map +1 -0
  75. package/dist/services/providerNetwork.js +17 -0
  76. package/dist/services/providerNetwork.js.map +1 -0
  77. package/dist/types/hyperliquid-types.d.ts +7 -7
  78. package/dist/types/hyperliquid-types.d.ts.map +1 -1
  79. package/dist/types/hyperliquid-types.js +4 -5
  80. package/dist/types/hyperliquid-types.js.map +1 -1
  81. package/dist/types/index.d.ts +190 -10
  82. package/dist/types/index.d.ts.map +1 -1
  83. package/dist/types/index.js.map +1 -1
  84. package/dist/types/lighter-types.d.ts +7 -17
  85. package/dist/types/lighter-types.d.ts.map +1 -1
  86. package/dist/types/lighter-types.js.map +1 -1
  87. package/dist/utils/accountUtils.js +1 -1
  88. package/dist/utils/accountUtils.js.map +1 -1
  89. package/dist/utils/errorUtils.d.ts +1 -1
  90. package/dist/utils/errorUtils.d.ts.map +1 -1
  91. package/dist/utils/errorUtils.js +3 -11
  92. package/dist/utils/errorUtils.js.map +1 -1
  93. package/dist/utils/hyperLiquidAbstraction.d.ts.map +1 -1
  94. package/dist/utils/hyperLiquidAbstraction.js +0 -1
  95. package/dist/utils/hyperLiquidAbstraction.js.map +1 -1
  96. package/dist/utils/lighterAdapter.d.ts +2 -2
  97. package/dist/utils/lighterAdapter.d.ts.map +1 -1
  98. package/dist/utils/lighterAdapter.js +23 -17
  99. package/dist/utils/lighterAdapter.js.map +1 -1
  100. package/package.json +6 -7
@@ -8,6 +8,7 @@ import { DETAILED_ORDER_TYPES } from '../constants/orderTypes.js';
8
8
  import { CHASE_ORDER_CONFIG, CHASE_ORDER_STATUS, HYPERLIQUID_TWAP_LIMITS, ORDER_SLIPPAGE_CONFIG, PERFORMANCE_CONFIG, PERPS_CONSTANTS, PROVIDER_CONFIG, TP_SL_CONFIG, WITHDRAWAL_CONSTANTS, } from '../constants/perpsConfig.js';
9
9
  import { PERPS_TRANSACTIONS_HISTORY_CONSTANTS } from '../constants/transactionsHistoryConfig.js';
10
10
  import { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';
11
+ import { AgentSignerUnavailableError, getAgentAccountKey, isAgentSignerUnavailableError, } from '../services/agentSigner.js';
11
12
  import { DexDiscoveryCacheManager } from '../services/DexDiscoveryCacheManager.js';
12
13
  import { HyperLiquidClientService, } from '../services/HyperLiquidClientService.js';
13
14
  import { HyperLiquidSubscriptionService } from '../services/HyperLiquidSubscriptionService.js';
@@ -38,6 +39,43 @@ const HISTORICAL_ORDER_TYPE_BY_DETAILED_TYPE = {
38
39
  [DETAILED_ORDER_TYPES.STOP_MARKET]: 'market',
39
40
  [DETAILED_ORDER_TYPES.TAKE_PROFIT_LIMIT]: 'limit',
40
41
  [DETAILED_ORDER_TYPES.TAKE_PROFIT_MARKET]: 'market',
42
+ [DETAILED_ORDER_TYPES.TWAP_SLICE]: 'market',
43
+ [DETAILED_ORDER_TYPES.VAULT_CLOSE]: 'market',
44
+ [DETAILED_ORDER_TYPES.SPOT_DUST_CONVERSION]: 'market',
45
+ };
46
+ const HISTORICAL_ORDER_STATUS_BY_SDK_STATUS = {
47
+ open: 'open',
48
+ filled: 'filled',
49
+ triggered: 'triggered',
50
+ canceled: 'canceled',
51
+ marginCanceled: 'canceled',
52
+ vaultWithdrawalCanceled: 'canceled',
53
+ openInterestCapCanceled: 'canceled',
54
+ selfTradeCanceled: 'canceled',
55
+ reduceOnlyCanceled: 'canceled',
56
+ siblingFilledCanceled: 'canceled',
57
+ delistedCanceled: 'canceled',
58
+ liquidatedCanceled: 'canceled',
59
+ outcomeSettledCanceled: 'canceled',
60
+ scheduledCancel: 'canceled',
61
+ internalCancel: 'canceled',
62
+ reduceOnlyRejected: 'canceled',
63
+ rejected: 'rejected',
64
+ tickRejected: 'rejected',
65
+ minTradeNtlRejected: 'rejected',
66
+ perpMarginRejected: 'rejected',
67
+ badAloPxRejected: 'rejected',
68
+ iocCancelRejected: 'rejected',
69
+ badTriggerPxRejected: 'rejected',
70
+ marketOrderNoLiquidityRejected: 'rejected',
71
+ positionIncreaseAtOpenInterestCapRejected: 'rejected',
72
+ positionFlipAtOpenInterestCapRejected: 'rejected',
73
+ tooAggressiveAtOpenInterestCapRejected: 'rejected',
74
+ openInterestIncreaseRejected: 'rejected',
75
+ insufficientSpotBalanceRejected: 'rejected',
76
+ oracleRejected: 'rejected',
77
+ perpMaxPositionRejected: 'rejected',
78
+ tooManyOpenOrdersRejected: 'rejected',
41
79
  };
42
80
  /**
43
81
  * Type guard to check if a status is an object (not a string literal like "waitingForFill")
@@ -164,6 +202,8 @@ const getCancelStatusesFromError = (error, expectedStatusCount) => {
164
202
  }
165
203
  return response.data.statuses;
166
204
  };
205
+ // The address in HyperLiquid's "User or API Wallet 0x... does not exist."
206
+ const UNKNOWN_WALLET_ADDRESS_PATTERN = /user or api wallet (0x[0-9a-f]{40})/iu;
167
207
  /**
168
208
  * Exchange messages that mean a cancel was refused because the order is not on
169
209
  * the book any more.
@@ -725,6 +765,23 @@ export class HyperLiquidProvider {
725
765
  #chasePlacementBlockers = 0;
726
766
  // Track whether clients have been initialized (lazy initialization)
727
767
  #clientsInitialized = false;
768
+ #getAgentSigner;
769
+ // Incremented by clearAgentSigners so answers pending across a clear are
770
+ // discarded and asked again.
771
+ #agentSignersGeneration = 0;
772
+ // The getAgentSigner answer per network and main account (see
773
+ // getAgentAccountKey), pending or non-null, so an agent is only used for its
774
+ // account and network, and the agent it resolved to. An entry is dropped
775
+ // when the venue rejects that agent.
776
+ #agentSigners = new Map();
777
+ // The account and network each agent last signed an L1 action for, keyed by
778
+ // the lowercased address the venue reports. A rejection is attributed from
779
+ // it rather than from the selected account, which may have changed while
780
+ // the write was in flight; an L1 signature names no user, so one agent acts
781
+ // for one account. Kept across clearAgentSigners, so an agent replaced while
782
+ // its action was in flight is still recognized.
783
+ #agentSignedFor = new Map();
784
+ #onAgentRejected;
728
785
  // Promise-based lock to prevent race conditions in concurrent initialization
729
786
  #initializationPromise = null;
730
787
  #messenger;
@@ -747,6 +804,8 @@ export class HyperLiquidProvider {
747
804
  options.subscriptionBuilderAddressTestnet;
748
805
  this.#subscriptionBuilderAddressMainnet =
749
806
  options.subscriptionBuilderAddressMainnet;
807
+ this.#getAgentSigner = options.getAgentSigner;
808
+ this.#onAgentRejected = options.onAgentRejected;
750
809
  this.#onChaseOrderMaxDistanceReached =
751
810
  options.onChaseOrderMaxDistanceReached;
752
811
  this.#priceDeviationLimit =
@@ -770,6 +829,7 @@ export class HyperLiquidProvider {
770
829
  });
771
830
  this.#walletService = new HyperLiquidWalletService(this.#deps, this.#messenger, {
772
831
  isTestnet,
832
+ resolveAgent: async (mainAddress) => await this.#resolveAgentSigner(mainAddress),
773
833
  });
774
834
  this.#subscriptionService = new HyperLiquidSubscriptionService(this.#clientService, this.#walletService, this.#deps, this.#hip3Enabled, [], // enabledDexs - will be populated after DEX discovery in buildAssetMapping
775
835
  this.#allowlistMarkets, this.#blocklistMarkets, this.#priceDeviationLimit, async () => {
@@ -1143,6 +1203,196 @@ export class HyperLiquidProvider {
1143
1203
  this.#initializationPromise = null;
1144
1204
  }
1145
1205
  }
1206
+ /**
1207
+ * Resolve the agent that signs L1 actions for a main account on the
1208
+ * current network through `getAgentSigner`. A non-null answer is kept;
1209
+ * null and failures are not, so the next L1 action asks again. An answer
1210
+ * pending across clearAgentSigners is discarded and asked again.
1211
+ *
1212
+ * @param mainAddress - The selected main account.
1213
+ * @returns The agent, or null to sign with the main account.
1214
+ */
1215
+ async #resolveAgentSigner(mainAddress) {
1216
+ const account = {
1217
+ mainAddress,
1218
+ isTestnet: this.#clientService.isTestnetMode(),
1219
+ };
1220
+ const key = getAgentAccountKey(account);
1221
+ const generation = this.#agentSignersGeneration;
1222
+ let entry = this.#agentSigners.get(key);
1223
+ if (!entry) {
1224
+ if (!this.#getAgentSigner) {
1225
+ return null;
1226
+ }
1227
+ let answer;
1228
+ try {
1229
+ answer = this.#getAgentSigner(account);
1230
+ }
1231
+ catch (error) {
1232
+ answer = Promise.reject(error);
1233
+ }
1234
+ entry = { answer };
1235
+ this.#agentSigners.set(key, entry);
1236
+ }
1237
+ const pendingEntry = entry;
1238
+ // A clear while this answer was pending wins, so it is asked again. Only a
1239
+ // clear replaces a pending answer: every other removal happens once it
1240
+ // settled, after all its callers resumed.
1241
+ const isSuperseded = () => generation !== this.#agentSignersGeneration;
1242
+ let agentSigner;
1243
+ try {
1244
+ agentSigner = await pendingEntry.answer;
1245
+ }
1246
+ catch (error) {
1247
+ if (isSuperseded()) {
1248
+ return await this.#resolveAgentSigner(mainAddress);
1249
+ }
1250
+ this.#agentSigners.delete(key);
1251
+ this.#deps.debugLogger.log('HyperLiquidProvider: getAgentSigner failed', {
1252
+ error: ensureError(error, 'HyperLiquidProvider.resolveAgentSigner')
1253
+ .message,
1254
+ });
1255
+ throw new AgentSignerUnavailableError(error);
1256
+ }
1257
+ if (isSuperseded()) {
1258
+ return await this.#resolveAgentSigner(mainAddress);
1259
+ }
1260
+ if (agentSigner) {
1261
+ pendingEntry.agent = agentSigner;
1262
+ // The wallet adapter resolves at every L1 signature, so this records
1263
+ // the account the agent is about to sign for.
1264
+ this.#agentSignedFor.set(agentSigner.address.toLowerCase(), {
1265
+ key,
1266
+ account,
1267
+ agentAddress: agentSigner.address,
1268
+ });
1269
+ }
1270
+ else {
1271
+ this.#agentSigners.delete(key);
1272
+ }
1273
+ return agentSigner;
1274
+ }
1275
+ /**
1276
+ * Map and log a failed exchange write, unless the signer could not sign it
1277
+ * (`KEYRING_LOCKED`: a locked keyring, or an unavailable or rejected
1278
+ * agent), which the caller retries.
1279
+ *
1280
+ * @param error - The caught error.
1281
+ * @param method - The write that failed.
1282
+ * @param extra - Context for the log.
1283
+ * @returns The mapped error.
1284
+ */
1285
+ async #reportWriteError(error, method, extra) {
1286
+ const signerFailure = this.#handleSignerFailure(error, method, extra);
1287
+ if (signerFailure) {
1288
+ return signerFailure;
1289
+ }
1290
+ const mappedError = this.#mapError(error);
1291
+ this.#deps.logger.error(mappedError, await this.#getTradingErrorContext(method, mappedError, extra));
1292
+ return mappedError;
1293
+ }
1294
+ /**
1295
+ * The agent a venue rejection names, with the account and network it last
1296
+ * signed for. HyperLiquid answers "User or API Wallet 0x... does not
1297
+ * exist." with the signer's address, so for a revoked or expired agent it
1298
+ * reads like a wallet with no account.
1299
+ *
1300
+ * @param error - The caught error.
1301
+ * @returns The rejected agent, with its address as the host supplied it
1302
+ * and the account it signed for, or undefined.
1303
+ */
1304
+ #findRejectedAgent(error) {
1305
+ if (this.#agentSignedFor.size === 0 ||
1306
+ !isHyperLiquidUserNotFoundError(error)) {
1307
+ return undefined;
1308
+ }
1309
+ const reportedAddress = UNKNOWN_WALLET_ADDRESS_PATTERN.exec(ensureError(error, 'HyperLiquidProvider.findRejectedAgent').message)?.[1];
1310
+ return reportedAddress === undefined
1311
+ ? undefined
1312
+ : this.#agentSignedFor.get(reportedAddress.toLowerCase());
1313
+ }
1314
+ /**
1315
+ * Handle a venue rejection of an agent: drop it if it is still the
1316
+ * resolved one, so the next L1 action asks for one again, and tell the
1317
+ * owner of the bindings.
1318
+ *
1319
+ * @param error - The caught error.
1320
+ * @returns True when the error was the rejection of an agent.
1321
+ */
1322
+ #evictRejectedAgent(error) {
1323
+ const rejected = this.#findRejectedAgent(error);
1324
+ if (!rejected) {
1325
+ return false;
1326
+ }
1327
+ const { account, key, agentAddress } = rejected;
1328
+ if (this.#agentSigners.get(key)?.agent?.address === agentAddress) {
1329
+ this.#agentSigners.delete(key);
1330
+ }
1331
+ this.#deps.debugLogger.log('HyperLiquidProvider: agent rejected by the venue, asking again', { agent: agentAddress });
1332
+ try {
1333
+ this.#onAgentRejected?.(account, agentAddress);
1334
+ }
1335
+ catch (callbackError) {
1336
+ this.#deps.debugLogger.log('HyperLiquidProvider: onAgentRejected threw', {
1337
+ error: ensureError(callbackError, 'HyperLiquidProvider.evictRejectedAgent').message,
1338
+ });
1339
+ }
1340
+ return true;
1341
+ }
1342
+ /**
1343
+ * Whether an exchange write failed because its signer could not sign it:
1344
+ * a locked keyring, an unavailable agent, or an agent the venue rejected.
1345
+ * It does not evict; the caller that reports the failure classifies it.
1346
+ *
1347
+ * @param error - The caught error.
1348
+ * @returns True for a signer failure.
1349
+ */
1350
+ #isSignerFailure(error) {
1351
+ return (isKeyringLockedError(error) ||
1352
+ isAgentSignerUnavailableError(error) ||
1353
+ this.#findRejectedAgent(error) !== undefined);
1354
+ }
1355
+ /**
1356
+ * Classify a failed exchange write whose signer could not sign it, evicting
1357
+ * a rejected agent. The next attempt retries.
1358
+ *
1359
+ * @param error - The caught error.
1360
+ * @returns `KEYRING_LOCKED` for a signer failure, else undefined.
1361
+ */
1362
+ #classifySignerFailure(error) {
1363
+ const rejectedAgent = this.#evictRejectedAgent(error);
1364
+ return rejectedAgent ||
1365
+ isKeyringLockedError(error) ||
1366
+ isAgentSignerUnavailableError(error)
1367
+ ? new Error(PERPS_ERROR_CODES.KEYRING_LOCKED)
1368
+ : undefined;
1369
+ }
1370
+ /**
1371
+ * Classify a failed write whose signer could not sign it, and note it as
1372
+ * retryable instead of reporting it.
1373
+ *
1374
+ * @param error - The caught error.
1375
+ * @param method - The write that failed.
1376
+ * @param extra - Context for the debug log.
1377
+ * @returns `KEYRING_LOCKED` for a signer failure, else undefined.
1378
+ */
1379
+ #handleSignerFailure(error, method, extra) {
1380
+ const signerFailure = this.#classifySignerFailure(error);
1381
+ if (signerFailure) {
1382
+ this.#logRetryableSignerFailure(method, extra);
1383
+ }
1384
+ return signerFailure;
1385
+ }
1386
+ /**
1387
+ * Note a write that failed because its signer could not sign it; the
1388
+ * caller retries it, so it is not reported as an error.
1389
+ *
1390
+ * @param method - The write that failed.
1391
+ * @param extra - Context for the debug log.
1392
+ */
1393
+ #logRetryableSignerFailure(method, extra) {
1394
+ this.#deps.debugLogger.log(`[${method}] Signer unavailable, the write can be retried`, extra);
1395
+ }
1146
1396
  /**
1147
1397
  * Decide whether the wallet has a Hyperliquid account.
1148
1398
  *
@@ -1158,7 +1408,7 @@ export class HyperLiquidProvider {
1158
1408
  * re-probe. The probe is cheap (~100ms), non-throwing, and returns the
1159
1409
  * full deposit/withdraw history. A non-empty array means the wallet has
1160
1410
  * interacted with Hyperliquid at least once — necessary and sufficient
1161
- * for `agentSetAbstraction` / `userSetAbstraction` / `setReferrer` to
1411
+ * for `agentSetAbstraction` / `setReferrer` to
1162
1412
  * succeed.
1163
1413
  *
1164
1414
  * If the probe itself throws (transient network), returns `true` and does
@@ -1244,12 +1494,12 @@ export class HyperLiquidProvider {
1244
1494
  * across provider reconnections (critical for hardware wallets).
1245
1495
  *
1246
1496
  * @param options - Optional configuration.
1247
- * @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.
1497
+ * @param options.allowUserSigning - When true, runs the migration for `default` / `disabled` accounts. Defaults to false so init does not surface a signing prompt; action-time entry points (trading, withdraw) pass true.
1248
1498
  * @private
1249
1499
  */
1250
1500
  async #ensureUnifiedAccountEnabled(options) {
1251
- // dexAbstraction → unifiedAccount requires an EIP-712 prompt (HL blocks
1252
- // the agent path for that transition). Init calls with allowUserSigning=false so
1501
+ // Without an agent, the migration is signed by the main wallet, which can
1502
+ // prompt (hardware wallets). Init calls with allowUserSigning=false so
1253
1503
  // viewing the Perps section never surfaces a signing dialog. Trading and
1254
1504
  // withdraw entry points pass allowUserSigning=true to drive the migration when
1255
1505
  // the user actually intends to act.
@@ -1280,12 +1530,12 @@ export class HyperLiquidProvider {
1280
1530
  }
1281
1531
  // Check if another provider instance is currently attempting this operation
1282
1532
  // This prevents concurrent signing attempts across providers during reconnection
1283
- const inFlightPromise = PerpsSigningCache.isInFlight('unifiedAccount', network, userAddress);
1284
- if (inFlightPromise) {
1533
+ let inFlightPromise = PerpsSigningCache.isInFlight('unifiedAccount', network, userAddress);
1534
+ while (inFlightPromise) {
1285
1535
  this.#deps.debugLogger.log('HyperLiquidProvider: Unified Account setup in-flight, waiting...', { network, userAddress });
1286
1536
  await inFlightPromise;
1287
1537
  // The other instance may have finished without writing the cache (e.g.
1288
- // an init-time call deferred a dexAbstraction migration). If the cache
1538
+ // an init-time call deferred the migration). If the cache
1289
1539
  // is still empty and we are an action-time caller (allowUserSigning=true),
1290
1540
  // we must run our own attempt — otherwise the trade/withdraw would
1291
1541
  // proceed in the deprecated mode.
@@ -1293,7 +1543,9 @@ export class HyperLiquidProvider {
1293
1543
  if (postWaitCache?.attempted) {
1294
1544
  return;
1295
1545
  }
1296
- // Fall through to acquire our own lock and retry.
1546
+ // Another waiter may have taken the lock first. The lock is checked
1547
+ // and taken with no await in between, so only one waiter gets it.
1548
+ inFlightPromise = PerpsSigningCache.isInFlight('unifiedAccount', network, userAddress);
1297
1549
  }
1298
1550
  // Set in-flight lock to prevent concurrent attempts
1299
1551
  const completeInFlight = PerpsSigningCache.setInFlight('unifiedAccount', network, userAddress);
@@ -1308,8 +1560,7 @@ export class HyperLiquidProvider {
1308
1560
  }
1309
1561
  // Skip the migration entirely for wallets that have no Hyperliquid
1310
1562
  // account yet. HL creates accounts server-side on first USDC deposit;
1311
- // before that, both `agentSetAbstraction` and `userSetAbstraction`
1312
- // reject with "User or API Wallet 0x... does not exist." — formerly
1563
+ // before that, `agentSetAbstraction` rejects with "User or API Wallet 0x... does not exist." — formerly
1313
1564
  // the top source of `feature:perps` Sentry events on 7.75.1.
1314
1565
  // The probe is cheap, non-throwing, and cached.
1315
1566
  const isRegistered = await this.#isWalletOnHyperliquid(userAddress, network);
@@ -1364,9 +1615,7 @@ export class HyperLiquidProvider {
1364
1615
  // Bail on unknown modes BEFORE firing analytics or attempting dispatch.
1365
1616
  // Keeps `migration_required` actionable (only fires for modes we can
1366
1617
  // actually migrate) and avoids re-emitting on every reconnection.
1367
- if (currentMode !== 'dexAbstraction' &&
1368
- currentMode !== 'default' &&
1369
- currentMode !== 'disabled') {
1618
+ if (currentMode !== 'default' && currentMode !== 'disabled') {
1370
1619
  this.#deps.debugLogger.log('HyperLiquidProvider: Unknown abstraction mode, skipping Unified Account migration', { user: userAddress, network, mode: currentMode });
1371
1620
  completeInFlight();
1372
1621
  return;
@@ -1400,32 +1649,16 @@ export class HyperLiquidProvider {
1400
1649
  [PERPS_EVENT_PROPERTY.ABSTRACTION_MODE]: currentMode,
1401
1650
  [PERPS_EVENT_PROPERTY.STATUS]: PERPS_EVENT_VALUE.STATUS.MIGRATION_REQUIRED,
1402
1651
  });
1403
- // Enable Unified Account mode.
1404
- // - default / disabled: agent wallet can do this silently (no prompt)
1405
- // - dexAbstraction: HL blocks the agent transition — requires the user's main
1406
- // wallet to sign an EIP-712 action via userSetAbstraction (one-time prompt)
1652
+ // Enable Unified Account mode (default / disabled → unifiedAccount).
1407
1653
  this.#deps.debugLogger.log('HyperLiquidProvider: Enabling Unified Account mode', {
1408
1654
  user: userAddress,
1409
1655
  network,
1410
1656
  previousMode: currentMode,
1411
1657
  note: 'HyperLiquid will auto-manage collateral for HIP-3 orders',
1412
1658
  });
1413
- const exchangeClient = this.#clientService.getExchangeClient();
1414
- if (currentMode === 'dexAbstraction') {
1415
- // Requires EIP-712 signature from the user's main wallet (one-time migration).
1416
- // HL blocks the dexAbstraction → unifiedAccount transition via the agent wallet,
1417
- // so userSetAbstraction (user-signed) is the only path for legacy users.
1418
- await exchangeClient.userSetAbstraction({
1419
- user: userAddress,
1420
- abstraction: HL_UNIFIED_ACCOUNT_MODE,
1421
- });
1422
- }
1423
- else {
1424
- // default / disabled — silent agent transition, no user prompt
1425
- await exchangeClient.agentSetAbstraction({
1426
- abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,
1427
- });
1428
- }
1659
+ await this.#clientService.getExchangeClient().agentSetAbstraction({
1660
+ abstraction: HL_ABSTRACTION_WIRE.unifiedAccount,
1661
+ });
1429
1662
  this.#deps.debugLogger.log('✅ HyperLiquidProvider: Unified Account enabled successfully');
1430
1663
  this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
1431
1664
  [PERPS_EVENT_PROPERTY.PREVIOUS_ABSTRACTION_MODE]: currentMode,
@@ -1443,10 +1676,11 @@ export class HyperLiquidProvider {
1443
1676
  completeInFlight();
1444
1677
  }
1445
1678
  catch (error) {
1446
- // HyperLiquid wraps wallet signing failures and preserves KEYRING_LOCKED
1447
- // in `cause`, so classify the full chain and leave retry caches empty.
1448
- if (isKeyringLockedError(error)) {
1449
- this.#deps.debugLogger.log('[ensureUnifiedAccountEnabled] Keyring locked, will retry later');
1679
+ // The signer could not sign (a locked keyring, or an unavailable or
1680
+ // rejected agent; HyperLiquid keeps the cause in `cause`): leave the
1681
+ // cache empty and retry later.
1682
+ if (this.#classifySignerFailure(error)) {
1683
+ this.#deps.debugLogger.log('[ensureUnifiedAccountEnabled] Signer unavailable, will retry later');
1450
1684
  this.#unifiedAccountSetupNeedsRetry = true;
1451
1685
  completeInFlight();
1452
1686
  return;
@@ -1491,39 +1725,16 @@ export class HyperLiquidProvider {
1491
1725
  completeInFlight();
1492
1726
  return;
1493
1727
  }
1494
- // Cache failure ONLY for the user-prompted path
1495
- // (`dexAbstraction → unifiedAccount` via `userSetAbstraction`). The
1496
- // rationale for caching is "don't re-prompt a user who already saw the
1497
- // signature dialog and rejected it" — that doesn't apply to:
1498
- // - Read-only userAbstraction lookup failures (no prompt; transient).
1499
- // - Silent agent-key paths (`default`/`disabled` → `agentSetAbstraction`
1500
- // does not show a UI prompt; failures are typically transient HL
1501
- // outages and pinning them would leave users stuck in the
1502
- // deprecated mode for the rest of the session).
1503
- // Action-time retries pick up the unmigrated state and try again.
1504
- if (currentMode === 'dexAbstraction') {
1505
- TradingReadinessCache.set(network, userAddress, {
1506
- attempted: true,
1507
- enabled: false,
1508
- });
1509
- }
1510
- else {
1511
- // Silent agent-key failure (default/disabled) or read-only
1512
- // userAbstraction lookup failure — neither is a final state, so
1513
- // signal #ensureReady to drop its memoized promise and retry on
1514
- // the next entry instead of pinning the user in the deprecated
1515
- // mode for the provider's lifetime.
1516
- this.#unifiedAccountSetupNeedsRetry = true;
1517
- }
1728
+ // Agent-path failures and read-only userAbstraction lookup failures
1729
+ // are not final: signal #ensureReady to drop its memoized promise and
1730
+ // retry on the next entry instead of pinning the user in the
1731
+ // deprecated mode for the provider's lifetime.
1732
+ this.#unifiedAccountSetupNeedsRetry = true;
1518
1733
  const errorMessage = ensureError(error, 'HyperLiquidProvider.ensureUnifiedAccountEnabled').message;
1519
1734
  this.#deps.debugLogger.log('HyperLiquidProvider: Unified Account setup failed', {
1520
1735
  user: userAddress,
1521
1736
  network,
1522
1737
  error: errorMessage,
1523
- // Cache writes only happen on the user-prompted dexAbstraction
1524
- // path (see P2-B logic above). Reflect that here so retry
1525
- // behaviour is debuggable from the log alone.
1526
- cached: currentMode === 'dexAbstraction',
1527
1738
  });
1528
1739
  this.#deps.metrics.trackPerpsEvent(PerpsAnalyticsEvent.AccountSetup, {
1529
1740
  ...(currentMode && {
@@ -1575,7 +1786,7 @@ export class HyperLiquidProvider {
1575
1786
  // the unified balance. Hardware wallets remain deferred to action time to
1576
1787
  // avoid repeated signing prompts while browsing.
1577
1788
  await this.#ensureUnifiedAccountEnabled({
1578
- allowUserSigning: !this.#walletService.isSelectedHardwareWallet(),
1789
+ allowUserSigning: !this.#walletService.requiresSignatureConfirmation(),
1579
1790
  });
1580
1791
  })();
1581
1792
  // Await initialization - keep the promise so subsequent calls resolve immediately
@@ -1619,6 +1830,13 @@ export class HyperLiquidProvider {
1619
1830
  */
1620
1831
  #tradingSetupPromise = null;
1621
1832
  #tradingSetupComplete = false;
1833
+ // Set when the referral's signer could not sign it, so trading setup is not
1834
+ // marked complete and the referral is attempted again.
1835
+ #referralSetupNeedsRetry = false;
1836
+ // Set when the builder's referral code was not ready. It is not the user's
1837
+ // to fix, so it does not hold trading setup back: the next
1838
+ // `prepareTradingWallet` checks it again, but orders do not.
1839
+ #referralAwaitsBuilderCode = false;
1622
1840
  #builderFeeSetupPromises = new Map();
1623
1841
  /**
1624
1842
  * Approve the standard builder fee once for the current account and network.
@@ -1628,9 +1846,13 @@ export class HyperLiquidProvider {
1628
1846
  *
1629
1847
  * @param approvalFailureCode - Operation-specific error to throw when
1630
1848
  * approval is unavailable or fails.
1849
+ * @param options - Options.
1850
+ * @param options.reportSignerFailure - Throw `KEYRING_LOCKED` when the
1851
+ * signer could not sign the approval, even without an approval failure
1852
+ * code (the approval is otherwise non-blocking).
1631
1853
  * @returns The account, network, and configured builder for the action.
1632
1854
  */
1633
- async #ensureBuilderFeeSetup(approvalFailureCode) {
1855
+ async #ensureBuilderFeeSetup(approvalFailureCode, options = {}) {
1634
1856
  const isTestnet = this.#clientService.isTestnetMode();
1635
1857
  const network = isTestnet ? 'testnet' : 'mainnet';
1636
1858
  const userAddress = await this.#walletService.getUserAddressWithDefault();
@@ -1650,13 +1872,24 @@ export class HyperLiquidProvider {
1650
1872
  pendingApproval = this.#ensureBuilderFeeApproval(context);
1651
1873
  this.#builderFeeSetupPromises.set(setupKey, pendingApproval);
1652
1874
  }
1875
+ // An approval the signer could not sign is retryable, not a failure.
1876
+ const approvalFailure = (code) => new Error(this.#walletService.isMainAccountSignerReady()
1877
+ ? code
1878
+ : PERPS_ERROR_CODES.KEYRING_LOCKED);
1653
1879
  try {
1654
1880
  await pendingApproval;
1655
1881
  }
1656
1882
  catch (error) {
1657
1883
  this.#deps.debugLogger.log('[ensureBuilderFeeSetup] Builder fee approval failed', error);
1884
+ // A signer that could not sign is retryable, not an approval failure.
1885
+ if (approvalFailureCode || options.reportSignerFailure) {
1886
+ const signerFailure = this.#classifySignerFailure(error);
1887
+ if (signerFailure) {
1888
+ throw signerFailure;
1889
+ }
1890
+ }
1658
1891
  if (approvalFailureCode) {
1659
- throw new Error(approvalFailureCode);
1892
+ throw approvalFailure(approvalFailureCode);
1660
1893
  }
1661
1894
  }
1662
1895
  finally {
@@ -1665,17 +1898,22 @@ export class HyperLiquidProvider {
1665
1898
  }
1666
1899
  }
1667
1900
  if (approvalFailureCode && !this.#builderFeeCheckCache.has(cacheKey)) {
1668
- throw new Error(approvalFailureCode);
1901
+ throw approvalFailure(approvalFailureCode);
1669
1902
  }
1670
1903
  return context;
1671
1904
  }
1672
1905
  async #ensureReadyForTrading(options) {
1673
1906
  // First ensure basic initialization is complete
1674
1907
  await this.#ensureReady();
1675
- // dexAbstraction users were deferred during init to avoid an EIP-712 prompt
1676
- // on Perps section open. Drive the migration here, gated by its own cache so
1677
- // already-migrated or already-rejected users are not re-prompted.
1908
+ // The migration was deferred during init to avoid a signing prompt on
1909
+ // Perps section open. Drive it here, gated by its own cache so
1910
+ // already-migrated users are not re-prompted.
1678
1911
  await this.#ensureUnifiedAccountEnabled({ allowUserSigning: true });
1912
+ // Reset right before the check, with no await in between, so a failure
1913
+ // above does not leave the setup for an order to run.
1914
+ if (options.recheckPendingReferral && this.#referralAwaitsBuilderCode) {
1915
+ this.#tradingSetupComplete = false;
1916
+ }
1679
1917
  if (!this.#tradingSetupComplete && !this.#tradingSetupPromise) {
1680
1918
  const lifecycleGeneration = this.#lifecycleGeneration;
1681
1919
  this.#deps.debugLogger.log('[ensureReadyForTrading] Starting shared trading setup');
@@ -1694,8 +1932,11 @@ export class HyperLiquidProvider {
1694
1932
  // Set up referral code independently from builder-fee applicability.
1695
1933
  await this.#ensureReferralSet();
1696
1934
  this.#assertProviderLifecycleCurrent(lifecycleGeneration, 'Trading setup completion');
1697
- // Only mark complete if keyring was unlocked (signing could actually happen)
1698
- if (this.#walletService.isKeyringUnlocked()) {
1935
+ // Only mark complete if the main-account signer is ready (signing
1936
+ // could actually happen) and the referral does not need another
1937
+ // attempt.
1938
+ if (this.#walletService.isMainAccountSignerReady() &&
1939
+ !this.#referralSetupNeedsRetry) {
1699
1940
  this.#tradingSetupComplete = true;
1700
1941
  }
1701
1942
  })();
@@ -2643,6 +2884,36 @@ export class HyperLiquidProvider {
2643
2884
  // Return original error to preserve stack trace for unmapped errors
2644
2885
  return ensureError(error, 'HyperLiquidProvider.mapError');
2645
2886
  }
2887
+ /**
2888
+ * Map a rejection the venue reported in a status entry rather than threw,
2889
+ * handling a rejected agent the way a thrown rejection is.
2890
+ *
2891
+ * @param message - The status entry's error.
2892
+ * @returns The mapped error.
2893
+ */
2894
+ #mapStatusError(message) {
2895
+ const error = new Error(message);
2896
+ return this.#classifySignerFailure(error) ?? this.#mapError(error);
2897
+ }
2898
+ /**
2899
+ * The signer failure a venue reported in cancel status entries rather than
2900
+ * threw. One signature covers the whole request, so it is classified (and
2901
+ * reported to the host) once for all its entries.
2902
+ *
2903
+ * @param statuses - The status entries.
2904
+ * @returns `KEYRING_LOCKED` for a signer failure, else undefined.
2905
+ */
2906
+ #classifyStatusSignerFailure(statuses) {
2907
+ for (const status of statuses) {
2908
+ if (isStatusObject(status) && typeof status.error === 'string') {
2909
+ const signerFailure = this.#classifySignerFailure(new Error(status.error));
2910
+ if (signerFailure) {
2911
+ return signerFailure;
2912
+ }
2913
+ }
2914
+ }
2915
+ return undefined;
2916
+ }
2646
2917
  /**
2647
2918
  * Get error context for logging with searchable tags and context.
2648
2919
  * Enables Sentry dashboard filtering by feature, provider, and network.
@@ -2846,10 +3117,11 @@ export class HyperLiquidProvider {
2846
3117
  }
2847
3118
  // HyperLiquid wraps wallet signing failures and preserves KEYRING_LOCKED
2848
3119
  // in `cause`, so classify the full chain and leave retry caches empty.
3120
+ // The caller reports it as retryable.
2849
3121
  if (isKeyringLockedError(error)) {
2850
3122
  this.#deps.debugLogger.log('[ensureBuilderFeeApproval] Keyring locked, will retry later');
2851
3123
  completeInFlight();
2852
- return;
3124
+ throw error;
2853
3125
  }
2854
3126
  // Record failure — will be retried on next trading operation
2855
3127
  PerpsSigningCache.setBuilderFee(network, userAddress, {
@@ -3073,6 +3345,10 @@ export class HyperLiquidProvider {
3073
3345
  amount: transferAmount,
3074
3346
  });
3075
3347
  if (!result.success) {
3348
+ // The signer could not sign the transfer: retryable, not a defect.
3349
+ if (result.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {
3350
+ throw new Error(PERPS_ERROR_CODES.KEYRING_LOCKED);
3351
+ }
3076
3352
  throw new Error(`Auto-transfer failed: ${result.error ?? 'Unknown error'}`);
3077
3353
  }
3078
3354
  this.#deps.debugLogger.log('✅ HyperLiquidProvider: HIP-3 auto-transfer complete', {
@@ -3302,6 +3578,11 @@ export class HyperLiquidProvider {
3302
3578
  amount: excessAmount.toFixed(USDC_DECIMALS),
3303
3579
  });
3304
3580
  if (!transferResult.success) {
3581
+ // The signer could not sign the transfer: retryable, not a defect.
3582
+ if (transferResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {
3583
+ this.#deps.debugLogger.log('HyperLiquidProvider: Auto-rebalance not signed - funds remain on HIP-3 DEX', { dex: dexName, excessAmount });
3584
+ return false;
3585
+ }
3305
3586
  throw new Error(transferResult.error ?? PERPS_ERROR_CODES.TRANSFER_FAILED);
3306
3587
  }
3307
3588
  this.#deps.debugLogger.log('✅ HyperLiquidProvider: Auto-rebalance completed', {
@@ -3371,6 +3652,10 @@ export class HyperLiquidProvider {
3371
3652
  returnedTo: transferInfo.sourceDex || 'main',
3372
3653
  });
3373
3654
  }
3655
+ else if (rollbackResult.error === PERPS_ERROR_CODES.KEYRING_LOCKED) {
3656
+ // The signer could not sign the transfer: retryable, not a defect.
3657
+ this.#deps.debugLogger.log('HyperLiquidProvider: Rollback not signed - funds remain on HIP-3 DEX', { dex: dexName, amount: transferInfo.amount });
3658
+ }
3374
3659
  else {
3375
3660
  this.#deps.logger.error(new Error(rollbackResult.error ?? 'Rollback transfer failed'), this.#getErrorContext('placeOrder:rollback', {
3376
3661
  dex: dexName,
@@ -3528,10 +3813,11 @@ export class HyperLiquidProvider {
3528
3813
  * @param params - The operation parameters.
3529
3814
  */
3530
3815
  async #prepareAssetForTrading(params) {
3531
- const { symbol, assetId, leverage, marginMode = 'isolated' } = params;
3816
+ const { symbol, assetId, leverage } = params;
3532
3817
  if (!leverage) {
3533
3818
  return;
3534
3819
  }
3820
+ const marginMode = params.marginMode ?? (await this.#resolveDefaultMarginMode(symbol));
3535
3821
  this.#deps.debugLogger.log('Updating leverage before order:', {
3536
3822
  symbol,
3537
3823
  assetId,
@@ -3552,6 +3838,30 @@ export class HyperLiquidProvider {
3552
3838
  leverage,
3553
3839
  });
3554
3840
  }
3841
+ /**
3842
+ * Resolve the margin mode for an order that omits one. HyperLiquid refuses
3843
+ * to switch mode while a position is open, so an open position's mode wins
3844
+ * over the isolated default (e.g. flipping a Cross position).
3845
+ *
3846
+ * @param symbol - Market symbol, including its DEX route when applicable.
3847
+ * @returns The open position's mode, or isolated when there is none or it
3848
+ * cannot be read.
3849
+ */
3850
+ async #resolveDefaultMarginMode(symbol) {
3851
+ const { dex: dexName } = parseAssetName(symbol);
3852
+ try {
3853
+ const positions = await this.#getPositionsForOperation(dexName ?? '');
3854
+ return (positions.find((position) => position.symbol === symbol)?.leverage
3855
+ .type ?? 'isolated');
3856
+ }
3857
+ catch (error) {
3858
+ this.#deps.debugLogger.log('Open position margin mode unavailable: defaulting to isolated', {
3859
+ symbol,
3860
+ error: ensureError(error, 'HyperLiquidProvider.resolveDefaultMarginMode').message,
3861
+ });
3862
+ return 'isolated';
3863
+ }
3864
+ }
3555
3865
  /**
3556
3866
  * Handles HIP-3 pre-order balance management
3557
3867
  *
@@ -3682,6 +3992,14 @@ export class HyperLiquidProvider {
3682
3992
  */
3683
3993
  async #handleOrderError(params) {
3684
3994
  const { error, symbol, orderType, isBuy } = params;
3995
+ const signerFailure = this.#handleSignerFailure(error, 'placeOrder', {
3996
+ symbol,
3997
+ orderType,
3998
+ isBuy,
3999
+ });
4000
+ if (signerFailure) {
4001
+ return createErrorResult(signerFailure, { success: false });
4002
+ }
3685
4003
  const mappedError = this.#mapError(error);
3686
4004
  // A wallet with no Hyperliquid account is an expected pre-account state,
3687
4005
  // not an app defect — same policy already applied to every other
@@ -4343,11 +4661,18 @@ export class HyperLiquidProvider {
4343
4661
  a: assetId,
4344
4662
  t: running.twapId,
4345
4663
  });
4664
+ const cancelStatus = cancelResult.response?.data?.status;
4665
+ // A rejected agent is dropped and reported; the TWAP stays live.
4666
+ if (isStatusObject(cancelStatus) &&
4667
+ typeof cancelStatus.error === 'string') {
4668
+ this.#evictRejectedAgent(new Error(cancelStatus.error));
4669
+ }
4346
4670
  remainsLive =
4347
- classifyCancelStatus(cancelResult.response?.data?.status) ===
4348
- CancelChildOutcome.Refused;
4671
+ classifyCancelStatus(cancelStatus) === CancelChildOutcome.Refused;
4349
4672
  }
4350
4673
  catch (error) {
4674
+ // A rejected agent is dropped and reported; the TWAP stays live.
4675
+ this.#evictRejectedAgent(error);
4351
4676
  this.#deps.debugLogger.log('Stale TWAP placement could not be retracted', {
4352
4677
  error: ensureError(error, 'HyperLiquidProvider.placeTwapOrder.retract').message,
4353
4678
  orderId,
@@ -4856,6 +5181,8 @@ export class HyperLiquidProvider {
4856
5181
  this.#chaseTickQueue = this.#chaseTickQueue
4857
5182
  .then(() => this.#runChaseTick(sessionId))
4858
5183
  .catch((error) => {
5184
+ // A rejected agent is dropped so the next tick asks for another.
5185
+ this.#evictRejectedAgent(error);
4859
5186
  // Resolve the shared queue after every failure. Otherwise one
4860
5187
  // rejected tick prevents all later ticks and teardown from running.
4861
5188
  this.#deps.debugLogger.log('Chase tick failed', {
@@ -5415,7 +5742,12 @@ export class HyperLiquidProvider {
5415
5742
  }
5416
5743
  throw error;
5417
5744
  }
5418
- return classifyCancelStatus(result.response?.data?.statuses?.[0]);
5745
+ const status = result.response?.data?.statuses?.[0];
5746
+ const signerFailure = this.#classifyStatusSignerFailure([status]);
5747
+ if (signerFailure) {
5748
+ throw signerFailure;
5749
+ }
5750
+ return classifyCancelStatus(status);
5419
5751
  }
5420
5752
  /**
5421
5753
  * Take back the order of a chase that was abandoned before it registered.
@@ -5441,6 +5773,8 @@ export class HyperLiquidProvider {
5441
5773
  return outcome;
5442
5774
  }
5443
5775
  catch (error) {
5776
+ // A rejected agent is dropped and reported; the order stays resting.
5777
+ this.#evictRejectedAgent(error);
5444
5778
  this.#deps.debugLogger.log('Could not retract abandoned chase order', {
5445
5779
  orderId: session.orderId,
5446
5780
  error: ensureError(error, 'HyperLiquidProvider.startChaseSession')
@@ -5827,12 +6161,11 @@ export class HyperLiquidProvider {
5827
6161
  return await this.#cancelChaseOrder(params);
5828
6162
  }
5829
6163
  catch (error) {
5830
- const mappedError = this.#mapError(error);
5831
- this.#deps.logger.error(mappedError, await this.#getTradingErrorContext('cancelOrder', mappedError, {
6164
+ const mappedError = await this.#reportWriteError(error, 'cancelOrder', {
5832
6165
  orderId: params.orderId,
5833
6166
  coin: params.symbol,
5834
6167
  orderType: params.orderType,
5835
- }));
6168
+ });
5836
6169
  return createErrorResult(mappedError, {
5837
6170
  success: false,
5838
6171
  orderId: params.orderId,
@@ -5912,7 +6245,7 @@ export class HyperLiquidProvider {
5912
6245
  const rawError = isStatusObject(status) && typeof status.error === 'string'
5913
6246
  ? status.error
5914
6247
  : 'TWAP cancellation failed';
5915
- return createErrorResult(this.#mapError(new Error(rawError)), {
6248
+ return createErrorResult(this.#mapStatusError(rawError), {
5916
6249
  success: false,
5917
6250
  orderId: params.orderId,
5918
6251
  });
@@ -5942,11 +6275,12 @@ export class HyperLiquidProvider {
5942
6275
  asset: assetId,
5943
6276
  cloid: clientOrderId,
5944
6277
  }));
5945
- const [remainingOrderIds, remainingClientOrderIds] = await Promise.all([
5946
- this.#cancelOrderRequests(exchangeClient, cancelRequests),
5947
- this.#cancelOrderCloidRequests(exchangeClient, cancelByCloidRequests),
6278
+ const [orderCancellation, cloidCancellation] = await Promise.all([
6279
+ this.#cancelOrderRequestBatch(exchangeClient, cancelRequests),
6280
+ this.#cancelOrderCloidRequestBatch(exchangeClient, cancelByCloidRequests),
5948
6281
  ]);
5949
- const remaining = remainingOrderIds.map(String);
6282
+ const remaining = orderCancellation.remainingOrderIds.map(String);
6283
+ const { remainingClientOrderIds } = cloidCancellation;
5950
6284
  /*
5951
6285
  * A rung that filled or was cancelled individually comes back as a
5952
6286
  * rejection, but nothing of it is resting. The shared cancellation helper
@@ -5966,6 +6300,18 @@ export class HyperLiquidProvider {
5966
6300
  orderIds: remaining,
5967
6301
  clientOrderIds: remainingClientOrderIds,
5968
6302
  });
6303
+ // The signer could not sign a cancel: retryable, not a defect.
6304
+ const signerFailure = orderCancellation.signerFailure ?? cloidCancellation.signerFailure;
6305
+ if (signerFailure) {
6306
+ this.#logRetryableSignerFailure('cancelOrder', {
6307
+ orderId: params.orderId,
6308
+ orderType: params.orderType,
6309
+ });
6310
+ return createErrorResult(signerFailure, {
6311
+ success: false,
6312
+ orderId: params.orderId,
6313
+ });
6314
+ }
5969
6315
  this.#deps.debugLogger.log('Scale group cancel left children resting', {
5970
6316
  groupId: params.orderId,
5971
6317
  remainingOrderIds: remaining.length,
@@ -6075,35 +6421,69 @@ export class HyperLiquidProvider {
6075
6421
  *
6076
6422
  * @param exchangeClient - Client that owns the orders.
6077
6423
  * @param requests - Venue cancel-by-CLOID requests.
6078
- * @returns Client order IDs that may still be pending.
6424
+ * @returns Client order IDs that may still be resting.
6079
6425
  */
6080
6426
  async #cancelOrderCloidRequests(exchangeClient, requests) {
6427
+ return (await this.#cancelOrderCloidRequestBatch(exchangeClient, requests))
6428
+ .remainingClientOrderIds;
6429
+ }
6430
+ /**
6431
+ * Cancel pending orders by client order ID, reporting a signer that could
6432
+ * not sign the cancel.
6433
+ *
6434
+ * @param exchangeClient - Client that owns the orders.
6435
+ * @param requests - Venue cancel-by-CLOID requests.
6436
+ * @returns Client order IDs that may still be resting, and the signer
6437
+ * failure when the signer could not sign the request.
6438
+ */
6439
+ async #cancelOrderCloidRequestBatch(exchangeClient, requests) {
6081
6440
  if (requests.length === 0) {
6082
- return [];
6441
+ return { remainingClientOrderIds: [] };
6083
6442
  }
6084
- const getRemainingClientOrderIds = (statuses) => requests.flatMap((request, index) => classifyCancelStatus(statuses[index]) === CancelChildOutcome.Refused
6085
- ? [request.cloid]
6086
- : []);
6443
+ const classifyStatuses = (statuses) => {
6444
+ // A signer failure is classified (and reported) once for the request;
6445
+ // entries the venue cancelled are not resting either way.
6446
+ const signerFailure = this.#classifyStatusSignerFailure(statuses);
6447
+ return {
6448
+ remainingClientOrderIds: requests.flatMap((request, index) => classifyCancelStatus(statuses[index]) === CancelChildOutcome.Refused
6449
+ ? [request.cloid]
6450
+ : []),
6451
+ ...(signerFailure && { signerFailure }),
6452
+ };
6453
+ };
6087
6454
  try {
6088
6455
  const result = await exchangeClient.cancelByCloid({
6089
6456
  cancels: requests,
6090
6457
  });
6091
6458
  const statuses = result.response?.data?.statuses ?? [];
6092
6459
  if (result.status !== 'ok' || statuses.length !== requests.length) {
6093
- return requests.map((request) => request.cloid);
6460
+ return {
6461
+ remainingClientOrderIds: requests.map((request) => request.cloid),
6462
+ };
6094
6463
  }
6095
- return getRemainingClientOrderIds(statuses);
6464
+ return classifyStatuses(statuses);
6096
6465
  }
6097
6466
  catch (error) {
6467
+ // The SDK throws when any entry failed, with every entry's status.
6098
6468
  const statuses = getCancelStatusesFromError(error, requests.length);
6099
6469
  if (statuses) {
6100
- return getRemainingClientOrderIds(statuses);
6470
+ return classifyStatuses(statuses);
6471
+ }
6472
+ // The signer could not sign, so nothing was cancelled.
6473
+ const signerFailure = this.#classifySignerFailure(error);
6474
+ if (signerFailure) {
6475
+ return {
6476
+ remainingClientOrderIds: requests.map((request) => request.cloid),
6477
+ signerFailure,
6478
+ };
6101
6479
  }
6102
6480
  this.#deps.debugLogger.log('Order cancellation by CLOID failed', {
6103
6481
  error: ensureError(error, 'HyperLiquidProvider.cancelOrderCloidRequests').message,
6104
6482
  clientOrderIds: requests.map((request) => request.cloid),
6105
6483
  });
6106
- return requests.map((request) => request.cloid);
6484
+ return {
6485
+ remainingClientOrderIds: requests.map((request) => request.cloid),
6486
+ };
6107
6487
  }
6108
6488
  }
6109
6489
  /**
@@ -6123,6 +6503,9 @@ export class HyperLiquidProvider {
6123
6503
  };
6124
6504
  }
6125
6505
  const classifyStatuses = (statuses) => {
6506
+ // A signer failure is classified (and reported) once for the request;
6507
+ // entries the venue cancelled still count as cancelled.
6508
+ const signerFailure = this.#classifyStatusSignerFailure(statuses);
6126
6509
  const remainingOrderIds = [];
6127
6510
  const cancelledOrderIds = [];
6128
6511
  requests.forEach((request, index) => {
@@ -6134,7 +6517,12 @@ export class HyperLiquidProvider {
6134
6517
  cancelledOrderIds.push(request.o);
6135
6518
  }
6136
6519
  });
6137
- return { remainingOrderIds, cancelledOrderIds, responseComplete: true };
6520
+ return {
6521
+ remainingOrderIds,
6522
+ cancelledOrderIds,
6523
+ responseComplete: true,
6524
+ ...(signerFailure && { signerFailure }),
6525
+ };
6138
6526
  };
6139
6527
  try {
6140
6528
  const result = await exchangeClient.cancel({ cancels: requests });
@@ -6149,10 +6537,21 @@ export class HyperLiquidProvider {
6149
6537
  return classifyStatuses(statuses);
6150
6538
  }
6151
6539
  catch (error) {
6540
+ // The SDK throws when any entry failed, with every entry's status.
6152
6541
  const statuses = getCancelStatusesFromError(error, requests.length);
6153
6542
  if (statuses) {
6154
6543
  return classifyStatuses(statuses);
6155
6544
  }
6545
+ // The signer could not sign, so nothing was cancelled.
6546
+ const signerFailure = this.#classifySignerFailure(error);
6547
+ if (signerFailure) {
6548
+ return {
6549
+ remainingOrderIds: requests.map((request) => request.o),
6550
+ cancelledOrderIds: [],
6551
+ responseComplete: false,
6552
+ signerFailure,
6553
+ };
6554
+ }
6156
6555
  this.#deps.debugLogger.log('Order cancellation batch failed', {
6157
6556
  error: ensureError(error, 'HyperLiquidProvider.cancelOrderRequests')
6158
6557
  .message,
@@ -6649,6 +7048,12 @@ export class HyperLiquidProvider {
6649
7048
  };
6650
7049
  }
6651
7050
  catch (error) {
7051
+ const signerFailure = this.#handleSignerFailure(error, 'editOrder', {
7052
+ orderId: params.orderId,
7053
+ });
7054
+ if (signerFailure) {
7055
+ return createErrorResult(signerFailure, { success: false });
7056
+ }
6652
7057
  this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.editOrder'), this.#getErrorContext('editOrder', {
6653
7058
  orderId: params.orderId,
6654
7059
  coin: params.newOrder.symbol,
@@ -6726,17 +7131,16 @@ export class HyperLiquidProvider {
6726
7131
  const rawError = isStatusObject(status) && typeof status.error === 'string'
6727
7132
  ? status.error
6728
7133
  : 'Order cancellation failed';
6729
- return createErrorResult(this.#mapError(new Error(rawError)), {
7134
+ return createErrorResult(this.#mapStatusError(rawError), {
6730
7135
  success: false,
6731
7136
  orderId: params.orderId,
6732
7137
  });
6733
7138
  }
6734
7139
  catch (error) {
6735
- const mappedError = this.#mapError(error);
6736
- this.#deps.logger.error(mappedError, await this.#getTradingErrorContext('cancelOrder', mappedError, {
7140
+ const mappedError = await this.#reportWriteError(error, 'cancelOrder', {
6737
7141
  orderId: params.orderId,
6738
7142
  coin: params.symbol,
6739
- }));
7143
+ });
6740
7144
  return createErrorResult(mappedError, {
6741
7145
  success: false,
6742
7146
  orderId: params.orderId,
@@ -6813,39 +7217,56 @@ export class HyperLiquidProvider {
6813
7217
  o: parseInt(order.orderId, 10),
6814
7218
  };
6815
7219
  }));
6816
- const result = await exchangeClient.cancel({
6817
- cancels: cancelRequests,
6818
- });
6819
- const statuses = result.response?.data?.statuses ?? [];
6820
- if (result.status === 'ok' &&
6821
- statuses.length === ordinaryOrders.length) {
7220
+ let statuses;
7221
+ try {
7222
+ const result = await exchangeClient.cancel({
7223
+ cancels: cancelRequests,
7224
+ });
7225
+ const returnedStatuses = result.response?.data?.statuses ?? [];
7226
+ statuses =
7227
+ result.status === 'ok' &&
7228
+ returnedStatuses.length === ordinaryOrders.length
7229
+ ? returnedStatuses
7230
+ : undefined;
7231
+ }
7232
+ catch (error) {
7233
+ // The SDK throws when any entry failed, with every entry's status.
7234
+ statuses = getCancelStatusesFromError(error, ordinaryOrders.length);
7235
+ if (!statuses) {
7236
+ throw error;
7237
+ }
7238
+ }
7239
+ if (statuses) {
7240
+ // One signature covers the batch, so a signer failure is classified
7241
+ // (and reported to the host) once. Each entry keeps its own result.
7242
+ const signerFailure = this.#classifyStatusSignerFailure(statuses);
6822
7243
  ordinaryOrders.forEach(({ index, order }, statusIndex) => {
6823
7244
  const status = statuses[statusIndex];
6824
7245
  const success = status === 'success';
6825
7246
  const statusError = isStatusObject(status) && typeof status.error === 'string'
6826
- ? status.error
7247
+ ? new Error(status.error)
6827
7248
  : undefined;
7249
+ let error = PERPS_ERROR_CODES.BATCH_CANCEL_FAILED;
7250
+ if (statusError) {
7251
+ error =
7252
+ signerFailure && this.#isSignerFailure(statusError)
7253
+ ? signerFailure.message
7254
+ : this.#mapError(statusError).message;
7255
+ }
6828
7256
  results[index] = {
6829
7257
  orderId: order.orderId,
6830
7258
  symbol: order.symbol,
6831
7259
  success,
6832
- ...(success
6833
- ? {}
6834
- : {
6835
- error: statusError === undefined
6836
- ? PERPS_ERROR_CODES.BATCH_CANCEL_FAILED
6837
- : this.#mapError(new Error(statusError)).message,
6838
- }),
7260
+ ...(success ? {} : { error }),
6839
7261
  };
6840
7262
  });
6841
7263
  }
6842
7264
  }
6843
7265
  }
6844
7266
  catch (error) {
6845
- const mappedError = this.#mapError(error);
6846
- this.#deps.logger.error(mappedError, await this.#getTradingErrorContext('cancelOrders', mappedError, {
7267
+ const mappedError = await this.#reportWriteError(error, 'cancelOrders', {
6847
7268
  orderCount: params.length,
6848
- }));
7269
+ });
6849
7270
  for (const result of results) {
6850
7271
  if (!result.success &&
6851
7272
  result.error === PERPS_ERROR_CODES.BATCH_CANCEL_FAILED) {
@@ -7122,10 +7543,16 @@ export class HyperLiquidProvider {
7122
7543
  };
7123
7544
  }
7124
7545
  catch (error) {
7125
- const safeError = ensureError(error, 'HyperLiquidProvider.closePositions');
7126
- this.#deps.logger.error(safeError, this.#getErrorContext('closePositions', {
7546
+ const signerFailure = this.#handleSignerFailure(error, 'closePositions', {
7127
7547
  positionCount: positionsToClose.length,
7128
- }));
7548
+ });
7549
+ const safeError = signerFailure ??
7550
+ ensureError(error, 'HyperLiquidProvider.closePositions');
7551
+ if (!signerFailure) {
7552
+ this.#deps.logger.error(safeError, this.#getErrorContext('closePositions', {
7553
+ positionCount: positionsToClose.length,
7554
+ }));
7555
+ }
7129
7556
  // Return all selected positions as failed, including unavailable DEXes.
7130
7557
  return {
7131
7558
  success: false,
@@ -7577,7 +8004,14 @@ export class HyperLiquidProvider {
7577
8004
  }
7578
8005
  catch (error) {
7579
8006
  success = false;
7580
- this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.updatePositionTPSL.restoreCancelledProtection'), this.#getErrorContext('updatePositionTPSL > restoreCancelledProtection', { symbol, grouping: protection.grouping }));
8007
+ // A signer that could not sign is retryable, not a defect; the
8008
+ // caller still learns the protection was lost.
8009
+ if (!this.#handleSignerFailure(error, 'updatePositionTPSL', {
8010
+ symbol,
8011
+ grouping: protection.grouping,
8012
+ })) {
8013
+ this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.updatePositionTPSL.restoreCancelledProtection'), this.#getErrorContext('updatePositionTPSL > restoreCancelledProtection', { symbol, grouping: protection.grouping }));
8014
+ }
7581
8015
  }
7582
8016
  }
7583
8017
  return { restoredOrderIds, success };
@@ -7586,11 +8020,25 @@ export class HyperLiquidProvider {
7586
8020
  success: false,
7587
8021
  childOrderIds: [...new Set(survivingOrderIds)],
7588
8022
  });
8023
+ // Cancel before placing for both position-bound and standalone partial
8024
+ // triggers. A place-first partial update leaves both trigger sets live
8025
+ // during the cancellation round trip and can reduce more than requested.
8026
+ const oldCancellation = await this.#cancelOrderRequestBatch(exchangeClient, cancelRequests);
8027
+ // The signer could not sign the cancel. With nothing cancelled the old
8028
+ // protection is still in place, and a clear keeps only what it could
8029
+ // not cancel, so the caller retries. A replacement that cancelled part
8030
+ // of the old protection restores it below.
8031
+ if (oldCancellation.signerFailure &&
8032
+ (orders.length === 0 || oldCancellation.cancelledOrderIds.length === 0)) {
8033
+ this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
8034
+ return createErrorResult(oldCancellation.signerFailure, {
8035
+ success: false,
8036
+ });
8037
+ }
7589
8038
  // Clearing has no replacement batch to preserve. A partial cancellation
7590
8039
  // is reported so the caller can retry the same clear operation.
7591
8040
  if (orders.length === 0) {
7592
- const remainingOrderIds = await this.#cancelOrderRequests(exchangeClient, cancelRequests);
7593
- if (remainingOrderIds.length > 0) {
8041
+ if (oldCancellation.remainingOrderIds.length > 0) {
7594
8042
  throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
7595
8043
  }
7596
8044
  this.#deps.debugLogger.log('No new TP/SL orders to place - existing ones cancelled');
@@ -7599,11 +8047,7 @@ export class HyperLiquidProvider {
7599
8047
  // No orderId since we only cancelled orders, didn't place new ones
7600
8048
  };
7601
8049
  }
7602
- // Cancel before placing for both position-bound and standalone partial
7603
- // triggers. A place-first partial update leaves both trigger sets live
7604
- // during the cancellation round trip and can reduce more than requested.
7605
8050
  const confirmedCancelledOldOrderIds = new Set();
7606
- const oldCancellation = await this.#cancelOrderRequestBatch(exchangeClient, cancelRequests);
7607
8051
  if (!oldCancellation.responseComplete) {
7608
8052
  const requestedOrderIds = new Set(cancelRequests.map((request) => request.o));
7609
8053
  let possiblyLiveOrderIds = Array.from(requestedOrderIds, String);
@@ -7630,6 +8074,19 @@ export class HyperLiquidProvider {
7630
8074
  ...restoration.restoredOrderIds,
7631
8075
  ]);
7632
8076
  }
8077
+ const survivingOrderIds = [
8078
+ ...new Set([
8079
+ ...oldCancellation.remainingOrderIds.map(String),
8080
+ ...restoration.restoredOrderIds,
8081
+ ]),
8082
+ ];
8083
+ if (oldCancellation.signerFailure) {
8084
+ this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
8085
+ return createErrorResult(oldCancellation.signerFailure, {
8086
+ success: false,
8087
+ childOrderIds: survivingOrderIds,
8088
+ });
8089
+ }
7633
8090
  const updateError = new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
7634
8091
  this.#deps.logger.error(updateError, this.#getErrorContext('updatePositionTPSL', {
7635
8092
  symbol: params.symbol,
@@ -7638,12 +8095,7 @@ export class HyperLiquidProvider {
7638
8095
  }));
7639
8096
  return createErrorResult(updateError, {
7640
8097
  success: false,
7641
- childOrderIds: [
7642
- ...new Set([
7643
- ...oldCancellation.remainingOrderIds.map(String),
7644
- ...restoration.restoredOrderIds,
7645
- ]),
7646
- ],
8098
+ childOrderIds: survivingOrderIds,
7647
8099
  });
7648
8100
  }
7649
8101
  let result;
@@ -7656,10 +8108,22 @@ export class HyperLiquidProvider {
7656
8108
  });
7657
8109
  }
7658
8110
  catch (error) {
8111
+ // Classify first, so a rejected agent is dropped (and reported) before
8112
+ // the restoration signs.
8113
+ const signerFailure = this.#classifySignerFailure(error);
7659
8114
  const restoration = await restoreCancelledProtection(confirmedCancelledOldOrderIds);
7660
8115
  if (!restoration.success) {
7661
8116
  return createProtectionLostResult(restoration.restoredOrderIds);
7662
8117
  }
8118
+ if (signerFailure) {
8119
+ this.#logRetryableSignerFailure('updatePositionTPSL', { symbol });
8120
+ return createErrorResult(signerFailure, {
8121
+ success: false,
8122
+ ...(restoration.restoredOrderIds.length > 0 && {
8123
+ childOrderIds: restoration.restoredOrderIds,
8124
+ }),
8125
+ });
8126
+ }
7663
8127
  throw error;
7664
8128
  }
7665
8129
  const placementStatuses = result.response?.data?.statuses ?? [];
@@ -7728,6 +8192,10 @@ export class HyperLiquidProvider {
7728
8192
  throw new Error(PERPS_ERROR_CODES.TPSL_UPDATE_FAILED);
7729
8193
  }
7730
8194
  catch (error) {
8195
+ const signerFailure = this.#handleSignerFailure(error, 'updatePositionTPSL', { symbol: params.symbol });
8196
+ if (signerFailure) {
8197
+ return createErrorResult(signerFailure, { success: false });
8198
+ }
7731
8199
  this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.updatePositionTPSL'), this.#getErrorContext('updatePositionTPSL', {
7732
8200
  symbol: params.symbol,
7733
8201
  hasTakeProfit: params.takeProfitPrice !== undefined,
@@ -7953,6 +8421,12 @@ export class HyperLiquidProvider {
7953
8421
  };
7954
8422
  }
7955
8423
  catch (error) {
8424
+ const signerFailure = this.#handleSignerFailure(error, 'updateMargin', {
8425
+ symbol: params.symbol,
8426
+ });
8427
+ if (signerFailure) {
8428
+ return { success: false, error: signerFailure.message };
8429
+ }
7956
8430
  const safeError = ensureError(error, 'HyperLiquidProvider.updateMargin');
7957
8431
  this.#deps.logger.error(safeError, this.#getErrorContext('updateMargin', {
7958
8432
  symbol: params.symbol,
@@ -8570,38 +9044,10 @@ export class HyperLiquidProvider {
8570
9044
  // Transform HyperLiquid orders to abstract Order type
8571
9045
  const orders = (rawOrders || []).map((rawOrder) => {
8572
9046
  const { order, status, statusTimestamp } = rawOrder;
8573
- // Normalize status
8574
- let normalizedStatus;
8575
- switch (status) {
8576
- case 'open':
8577
- normalizedStatus = 'open';
8578
- break;
8579
- case 'filled':
8580
- normalizedStatus = 'filled';
8581
- break;
8582
- case 'canceled':
8583
- case 'marginCanceled':
8584
- case 'vaultWithdrawalCanceled':
8585
- case 'openInterestCapCanceled':
8586
- case 'selfTradeCanceled':
8587
- case 'reduceOnlyCanceled':
8588
- case 'siblingFilledCanceled':
8589
- case 'delistedCanceled':
8590
- case 'liquidatedCanceled':
8591
- case 'scheduledCancel':
8592
- case 'reduceOnlyRejected':
8593
- normalizedStatus = 'canceled';
8594
- break;
8595
- case 'rejected':
8596
- // case 'minTradeNtlRejected':
8597
- normalizedStatus = 'rejected';
8598
- break;
8599
- case 'triggered':
8600
- normalizedStatus = 'triggered';
8601
- break;
8602
- default:
8603
- normalizedStatus = 'queued';
8604
- }
9047
+ // Statuses newer than the SDK types stay visible as queued.
9048
+ const normalizedStatus = hasProperty(HISTORICAL_ORDER_STATUS_BY_SDK_STATUS, status)
9049
+ ? HISTORICAL_ORDER_STATUS_BY_SDK_STATUS[status]
9050
+ : 'queued';
8605
9051
  const adaptedOrder = adaptOrderFromSDK(order, undefined);
8606
9052
  // limitPx is also populated as a slippage cap for market orders, so the
8607
9053
  // exchange's detailed type is the reliable execution-mode source.
@@ -10059,6 +10505,12 @@ export class HyperLiquidProvider {
10059
10505
  };
10060
10506
  }
10061
10507
  catch (error) {
10508
+ const signerFailure = this.#handleSignerFailure(error, 'withdraw', {
10509
+ assetId: params.assetId,
10510
+ });
10511
+ if (signerFailure) {
10512
+ return createErrorResult(signerFailure, { success: false });
10513
+ }
10062
10514
  const safeError = ensureError(error, 'HyperLiquidProvider.initiateWithdrawal');
10063
10515
  this.#deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL EXCEPTION', {
10064
10516
  error: safeError.message,
@@ -10144,6 +10596,10 @@ export class HyperLiquidProvider {
10144
10596
  throw new Error(PERPS_ERROR_CODES.TRANSFER_FAILED);
10145
10597
  }
10146
10598
  catch (error) {
10599
+ const signerFailure = this.#handleSignerFailure(error, 'transferBetweenDexs', { sourceDex: params.sourceDex, destinationDex: params.destinationDex });
10600
+ if (signerFailure) {
10601
+ return { success: false, error: signerFailure.message };
10602
+ }
10147
10603
  const safeError = ensureError(error, 'HyperLiquidProvider.transferToSpot');
10148
10604
  this.#deps.debugLogger.log('❌ HyperLiquidProvider: TRANSFER FAILED', {
10149
10605
  error: safeError.message,
@@ -10413,6 +10869,94 @@ export class HyperLiquidProvider {
10413
10869
  return createErrorResult(error, { success: false });
10414
10870
  }
10415
10871
  }
10872
+ /**
10873
+ * Forget every agent resolved through `getAgentSigner`, so the next L1
10874
+ * action asks again; an answer still pending is discarded too.
10875
+ */
10876
+ clearAgentSigners() {
10877
+ this.#agentSignersGeneration += 1;
10878
+ this.#agentSigners.clear();
10879
+ }
10880
+ /**
10881
+ * Run the deferred account migration, builder fee and referral setup ahead
10882
+ * of the first order. Results are cached, so an already-ready account signs
10883
+ * nothing. A referral whose MetaMask code is not ready yet is checked again
10884
+ * by the next call rather than by orders.
10885
+ *
10886
+ * @returns The readiness result described on
10887
+ * `PerpsController.prepareTradingWallet`.
10888
+ */
10889
+ async prepareTradingWallet() {
10890
+ // Nothing can be signed, so run no setup (and log nothing) until it can.
10891
+ if (!this.#walletService.isMainAccountSignerReady()) {
10892
+ return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
10893
+ }
10894
+ try {
10895
+ const lifecycleGeneration = this.#lifecycleGeneration;
10896
+ const userAddress = await this.#walletService.getUserAddressWithDefault();
10897
+ // The result is only for the provider and account it started with.
10898
+ const assertPreparationCurrent = async () => {
10899
+ this.#assertProviderLifecycleCurrent(lifecycleGeneration, 'Trading wallet preparation');
10900
+ // A deselected account changed too.
10901
+ const currentAddress = await this.#walletService
10902
+ .getUserAddressWithDefault()
10903
+ .catch(() => undefined);
10904
+ if (currentAddress?.toLowerCase() !== userAddress.toLowerCase()) {
10905
+ throw new Error(PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE);
10906
+ }
10907
+ };
10908
+ await this.#ensureReadyForTrading({
10909
+ requiresBuilderFee: false,
10910
+ recheckPendingReferral: true,
10911
+ });
10912
+ const network = this.#clientService.isTestnetMode()
10913
+ ? 'testnet'
10914
+ : 'mainnet';
10915
+ const isRegistered = await this.#isWalletOnHyperliquid(userAddress, network);
10916
+ await assertPreparationCurrent();
10917
+ // The venue rejects every write from a wallet with no HyperLiquid account
10918
+ // yet, so it is not asked to sign a builder fee approval either.
10919
+ if (!isRegistered) {
10920
+ return {
10921
+ ready: false,
10922
+ error: this.#walletService.isMainAccountSignerReady()
10923
+ ? PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND
10924
+ : PERPS_ERROR_CODES.KEYRING_LOCKED,
10925
+ };
10926
+ }
10927
+ await this.#ensureBuilderFeeSetup(undefined, {
10928
+ reportSignerFailure: true,
10929
+ });
10930
+ // The builder fee setup ends quietly when the provider disconnects.
10931
+ await assertPreparationCurrent();
10932
+ if (!this.#walletService.isMainAccountSignerReady()) {
10933
+ return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
10934
+ }
10935
+ const ready = this.#tradingSetupComplete &&
10936
+ !this.#unifiedAccountSetupNeedsRetry &&
10937
+ this.#builderFeeCheckCache.has(this.#getCacheKey(network, userAddress));
10938
+ return { ready };
10939
+ }
10940
+ catch (error) {
10941
+ // A step failed because the signer could not sign it (or locked while
10942
+ // it ran): retryable, not logged.
10943
+ if (isKeyringLockedError(error) ||
10944
+ !this.#walletService.isMainAccountSignerReady()) {
10945
+ return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
10946
+ }
10947
+ const caughtError = ensureError(error, 'HyperLiquidProvider.prepareTradingWallet');
10948
+ if (caughtError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
10949
+ this.#deps.debugLogger.log('[prepareTradingWallet] Provider replaced during preparation');
10950
+ }
10951
+ else if (caughtError.message === PERPS_ERROR_CODES.NO_ACCOUNT_SELECTED) {
10952
+ this.#deps.debugLogger.log('[prepareTradingWallet] No account selected');
10953
+ }
10954
+ else {
10955
+ this.#deps.logger.error(caughtError, this.#getErrorContext('prepareTradingWallet'));
10956
+ }
10957
+ return { ready: false, error: caughtError.message };
10958
+ }
10959
+ }
10416
10960
  /**
10417
10961
  * Check if ready to trade
10418
10962
  *
@@ -11260,6 +11804,8 @@ export class HyperLiquidProvider {
11260
11804
  * Note: Non-blocking - failures are logged to Sentry but don't prevent trading
11261
11805
  */
11262
11806
  async #ensureReferralSet() {
11807
+ this.#referralSetupNeedsRetry = false;
11808
+ this.#referralAwaitsBuilderCode = false;
11263
11809
  const isTestnet = this.#clientService.isTestnetMode();
11264
11810
  const network = isTestnet ? 'testnet' : 'mainnet';
11265
11811
  const expectedReferralCode = this.#getReferralCode(isTestnet);
@@ -11290,12 +11836,15 @@ export class HyperLiquidProvider {
11290
11836
  this.#deps.debugLogger.log('[ensureReferralSet] Using global cache (prevents hardware wallet prompt spam)', { network, success: globalCached.success });
11291
11837
  return;
11292
11838
  }
11293
- // Check if another provider is currently attempting this
11294
- const inFlightPromise = PerpsSigningCache.isInFlight('referral', network, userAddress);
11295
- if (inFlightPromise) {
11839
+ // Wait while another provider attempts it. That attempt may end without
11840
+ // caching a result (its signer could not sign), so take the lock once it
11841
+ // is free and re-check the cache under it. The lock is checked and taken
11842
+ // with no await in between, so only one of several waiters gets it.
11843
+ let inFlightPromise = PerpsSigningCache.isInFlight('referral', network, userAddress);
11844
+ while (inFlightPromise) {
11296
11845
  this.#deps.debugLogger.log('[ensureReferralSet] Global in-flight, waiting...', { network });
11297
11846
  await inFlightPromise;
11298
- return;
11847
+ inFlightPromise = PerpsSigningCache.isInFlight('referral', network, userAddress);
11299
11848
  }
11300
11849
  // Set global in-flight lock
11301
11850
  const completeInFlight = PerpsSigningCache.setInFlight('referral', network, userAddress);
@@ -11307,11 +11856,14 @@ export class HyperLiquidProvider {
11307
11856
  completeInFlight();
11308
11857
  return;
11309
11858
  }
11310
- const isReady = await this.#isReferralCodeReady();
11311
- if (!isReady) {
11312
- this.#deps.debugLogger.log('[ensureReferralSet] Builder referral not ready, skipping', { network });
11859
+ const codeStatus = await this.#getReferralCodeStatus();
11860
+ if (codeStatus !== 'ready') {
11861
+ this.#deps.debugLogger.log('[ensureReferralSet] Builder referral not ready, skipping', { network, codeStatus });
11862
+ // Don't cache. A failed lookup (already logged) waits for the next
11863
+ // setup; a code that is not ready yet, for the next preparation.
11864
+ this.#referralAwaitsBuilderCode = codeStatus === 'pending';
11313
11865
  completeInFlight();
11314
- return; // Don't cache - retry when ready
11866
+ return;
11315
11867
  }
11316
11868
  // Check if user already has a referral on-chain
11317
11869
  const hasReferral = await this.#checkReferralSet();
@@ -11344,10 +11896,12 @@ export class HyperLiquidProvider {
11344
11896
  completeInFlight();
11345
11897
  }
11346
11898
  catch (error) {
11347
- // HyperLiquid wraps wallet signing failures and preserves KEYRING_LOCKED
11348
- // in `cause`, so classify the full chain and leave retry caches empty.
11349
- if (isKeyringLockedError(error)) {
11350
- this.#deps.debugLogger.log('[ensureReferralSet] Keyring locked, will retry later');
11899
+ // The signer could not sign (a locked keyring, or an unavailable or
11900
+ // rejected agent; HyperLiquid keeps the cause in `cause`): leave the
11901
+ // cache empty and attempt the referral again at the next setup.
11902
+ if (this.#classifySignerFailure(error)) {
11903
+ this.#deps.debugLogger.log('[ensureReferralSet] Signer unavailable, will retry later');
11904
+ this.#referralSetupNeedsRetry = true;
11351
11905
  completeInFlight();
11352
11906
  return;
11353
11907
  }
@@ -11378,11 +11932,12 @@ export class HyperLiquidProvider {
11378
11932
  }
11379
11933
  }
11380
11934
  /**
11381
- * Check if the referral code is ready to be used
11935
+ * Check whether the builder's referral code can be used.
11382
11936
  *
11383
- * @returns Promise resolving to true if referral code is ready
11937
+ * @returns `ready`, `pending` while the builder's code is not ready yet, or
11938
+ * `failed` when the lookup failed or the code on file does not match (logged).
11384
11939
  */
11385
- async #isReferralCodeReady() {
11940
+ async #getReferralCodeStatus() {
11386
11941
  try {
11387
11942
  const infoClient = this.#clientService.getInfoClient();
11388
11943
  const isTestnet = this.#clientService.isTestnetMode();
@@ -11395,22 +11950,22 @@ export class HyperLiquidProvider {
11395
11950
  if (onFile.toUpperCase() !== code.toUpperCase()) {
11396
11951
  throw new Error(`Ready for referrals but there is a config code mismatch ${onFile} vs ${code}`);
11397
11952
  }
11398
- return true;
11953
+ return 'ready';
11399
11954
  }
11400
11955
  // Not ready yet - log as debugLogger since this is expected during setup phase
11401
- this.#deps.debugLogger.log('[isReferralCodeReady] Referral code not ready', {
11956
+ this.#deps.debugLogger.log('[getReferralCodeStatus] Referral code not ready', {
11402
11957
  stage,
11403
11958
  code,
11404
11959
  referrerAddr,
11405
11960
  });
11406
- return false;
11961
+ return 'pending';
11407
11962
  }
11408
11963
  catch (error) {
11409
- this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.isReferralCodeReady'), this.#getErrorContext('isReferralCodeReady', {
11964
+ this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.getReferralCodeStatus'), this.#getErrorContext('getReferralCodeStatus', {
11410
11965
  code: this.#getReferralCode(this.#clientService.isTestnetMode()),
11411
11966
  referrerAddress: this.#getBuilderAddress(this.#clientService.isTestnetMode()),
11412
11967
  }));
11413
- return false;
11968
+ return 'failed';
11414
11969
  }
11415
11970
  }
11416
11971
  /**
@@ -11469,6 +12024,12 @@ export class HyperLiquidProvider {
11469
12024
  return result?.status === 'ok';
11470
12025
  }
11471
12026
  catch (error) {
12027
+ // Retryable (a locked keyring, an unavailable agent, or one the venue
12028
+ // rejected): `#ensureReferralSet` retries at the next entry, so it is
12029
+ // not an error to report.
12030
+ if (this.#isSignerFailure(error)) {
12031
+ throw error;
12032
+ }
11472
12033
  // Benign for unfunded wallets — downgrade and rethrow so the outer
11473
12034
  // `#ensureReferralSet` catch self-heals the walletRegistered gate
11474
12035
  // without forwarding to Sentry.