@metamask-previews/perps-controller 24.1.0-preview-2da314d6d → 24.1.0-preview-11e30b2

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 (45) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/PerpsController-method-action-types.d.ts +7 -5
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +7 -5
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +7 -5
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/errors.d.ts +13 -2
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +2 -2
  12. package/dist/errors.js.map +1 -1
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js.map +1 -1
  16. package/dist/perpsErrorCodes.d.ts +3 -0
  17. package/dist/perpsErrorCodes.d.ts.map +1 -1
  18. package/dist/perpsErrorCodes.js +4 -0
  19. package/dist/perpsErrorCodes.js.map +1 -1
  20. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  21. package/dist/providers/AggregatedPerpsProvider.js +6 -5
  22. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  23. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  24. package/dist/providers/HyperLiquidProvider.js +121 -165
  25. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  26. package/dist/services/TradingService.d.ts.map +1 -1
  27. package/dist/services/TradingService.js +19 -5
  28. package/dist/services/TradingService.js.map +1 -1
  29. package/dist/types/index.d.ts +36 -1
  30. package/dist/types/index.d.ts.map +1 -1
  31. package/dist/types/index.js.map +1 -1
  32. package/dist/utils/errorContext.d.ts +33 -0
  33. package/dist/utils/errorContext.d.ts.map +1 -1
  34. package/dist/utils/errorContext.js +41 -0
  35. package/dist/utils/errorContext.js.map +1 -1
  36. package/dist/utils/errorUtils.d.ts +18 -0
  37. package/dist/utils/errorUtils.d.ts.map +1 -1
  38. package/dist/utils/errorUtils.js +133 -1
  39. package/dist/utils/errorUtils.js.map +1 -1
  40. package/dist/utils/hyperLiquidValidation.d.ts +9 -2
  41. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  42. package/dist/utils/hyperLiquidValidation.js +18 -17
  43. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  44. package/docs/architecture.md +4 -2
  45. package/package.json +1 -1
@@ -21,8 +21,8 @@ import { PerpsAnalyticsEvent } from '../types/index.js';
21
21
  import { addSpotBalanceToAccountState, aggregateAccountStates, } from '../utils/accountUtils.js';
22
22
  import { boundTwapExecution, isChaseOrderRunning, reconcileTwapExecution, supersedesTwapOrder, } from '../utils/advancedOrders.js';
23
23
  import { isValidCapabilitySymbol } from '../utils/capabilitySymbols.js';
24
- import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, createPerpsErrorContext, } from '../utils/errorContext.js';
25
- import { ensureError, isHyperLiquidMultiSigRequiredError, isHyperLiquidUserNotFoundError, isKeyringLockedError, } from '../utils/errorUtils.js';
24
+ import { PERPS_ERROR_ACTION, PERPS_ERROR_COMPONENT, PERPS_ERROR_OPERATION, attachProviderErrorCause, createPerpsErrorContext, } from '../utils/errorContext.js';
25
+ import { ensureError, isHyperLiquidMultiSigRequiredError, isHyperLiquidUserNotFoundError, isKeyringLockedError, normalizeHyperLiquidError, } from '../utils/errorUtils.js';
26
26
  import { shouldDeferUnifiedAccountSetup } from '../utils/hyperLiquidAbstraction.js';
27
27
  import { adaptAccountStateFromSDK, adaptHyperLiquidLedgerUpdateToUserHistoryItem, adaptMarketFromSDK, adaptOrderFromSDK, adaptPositionFromSDK, adaptPositionTriggerOrderFromSDK, adaptPublicTradesFromHyperLiquid, adaptTpslLinkageToGrouping, buildAssetMapping, buildHyperLiquidFillId, formatHyperLiquidPrice, formatHyperLiquidSize, HYPERLIQUID_SCALE_CLOID_MARKER, parseAssetName, readScaleGroupId, } from '../utils/hyperLiquidAdapter.js';
28
28
  import { previewHyperLiquidIsolatedPositionModify, resolveHyperLiquidMarginTiers, } from '../utils/hyperLiquidPositionPreview.js';
@@ -280,23 +280,6 @@ function getBuilderFeeRefusal(error) {
280
280
  ? message
281
281
  : undefined;
282
282
  }
283
- /**
284
- * Exchange messages that mean a cancel was refused because the order is not on
285
- * the book any more.
286
- *
287
- * HyperLiquid answers a cancel it cannot match with "Order was never placed,
288
- * already canceled, or filled." That is a rejection of the request but a
289
- * confirmation of what the caller wanted — nothing of that order is resting.
290
- * Every other rejection (multi-sig, a stale nonce, a rate limit) leaves the
291
- * order exactly where it was, which is a materially different outcome.
292
- */
293
- const ALREADY_GONE_CANCEL_MARKERS = [
294
- 'never placed',
295
- 'already canceled',
296
- 'already cancelled',
297
- 'order not found',
298
- 'twap not found',
299
- ];
300
283
  const RETRYABLE_CHASE_PLACEMENT_MARKERS = [
301
284
  'post only order would have immediately matched',
302
285
  'price too far from oracle',
@@ -353,10 +336,11 @@ const classifyCancelStatus = (status) => {
353
336
  if (status === 'success') {
354
337
  return CancelChildOutcome.Cancelled;
355
338
  }
356
- const message = (isStatusObject(status) && typeof status.error === 'string'
339
+ const message = isStatusObject(status) && typeof status.error === 'string'
357
340
  ? status.error
358
- : '').toLowerCase();
359
- return ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))
341
+ : '';
342
+ return normalizeHyperLiquidError(message).errorCode ===
343
+ PERPS_ERROR_CODES.ORDER_NO_LONGER_OPEN
360
344
  ? CancelChildOutcome.Gone
361
345
  : CancelChildOutcome.Refused;
362
346
  };
@@ -727,6 +711,23 @@ const normalizeHyperLiquidScalePriceLadder = (params) => {
727
711
  }
728
712
  return prices;
729
713
  };
714
+ /**
715
+ * Build a normalized readiness failure without exposing venue text.
716
+ *
717
+ * @param error - The failure that prevented trading readiness.
718
+ * @returns A not-ready result with the public error contract.
719
+ */
720
+ function createNotReadyResult(error) {
721
+ const normalizedError = normalizeHyperLiquidError(error);
722
+ return {
723
+ ready: false,
724
+ error: normalizedError.message,
725
+ errorCode: normalizedError.errorCode,
726
+ ...(normalizedError.errorDetails === undefined
727
+ ? {}
728
+ : { errorDetails: normalizedError.errorDetails }),
729
+ };
730
+ }
730
731
  /**
731
732
  * HyperLiquid provider implementation
732
733
  *
@@ -821,13 +822,6 @@ export class HyperLiquidProvider {
821
822
  #pendingValidatedDexsPromise = null;
822
823
  // Cache for USDC token ID from spot metadata
823
824
  #cachedUsdcTokenId;
824
- // Error mappings from HyperLiquid API errors to standardized PERPS_ERROR_CODES
825
- #errorMappings = {
826
- 'isolated position does not have sufficient margin available to decrease leverage': PERPS_ERROR_CODES.ORDER_LEVERAGE_REDUCTION_FAILED,
827
- 'could not immediately match': PERPS_ERROR_CODES.IOC_CANCEL,
828
- 'multi-sig required': PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED,
829
- 'invalid nonce': PERPS_ERROR_CODES.EXCHANGE_INVALID_NONCE,
830
- };
831
825
  // Scale ladders placed by this provider instance, keyed by group handle, so
832
826
  // one cancel can reach every rung. Cleared on disconnect; the rung IDs are
833
827
  // also returned to the caller as `OrderResult.childOrderIds`.
@@ -3425,22 +3419,7 @@ export class HyperLiquidProvider {
3425
3419
  * @returns The result of the operation.
3426
3420
  */
3427
3421
  #mapError(error) {
3428
- const { message } = ensureError(error, 'HyperLiquidProvider.mapError');
3429
- // "User or API Wallet 0x... does not exist." carries the user's address, so
3430
- // it cannot be matched by the static substring table below. It means the
3431
- // wallet has no Hyperliquid account yet — surface an actionable code the
3432
- // client can translate ("fund your account") instead of leaking the raw
3433
- // exchange string to the UI and to failed-trade analytics.
3434
- if (isHyperLiquidUserNotFoundError(error)) {
3435
- return new PerpsControllerError(PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND, PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND);
3436
- }
3437
- for (const [pattern, code] of Object.entries(this.#errorMappings)) {
3438
- if (message.toLowerCase().includes(pattern.toLowerCase())) {
3439
- return new PerpsControllerError(code, code);
3440
- }
3441
- }
3442
- // Return original error to preserve stack trace for unmapped errors
3443
- return ensureError(error, 'HyperLiquidProvider.mapError');
3422
+ return normalizeHyperLiquidError(error);
3444
3423
  }
3445
3424
  /**
3446
3425
  * Map a rejection the venue reported in a status entry rather than threw,
@@ -4896,7 +4875,7 @@ export class HyperLiquidProvider {
4896
4875
  error: isMinimumOrderError &&
4897
4876
  !params.reduceOnly &&
4898
4877
  !isStrategyOrderType(params.orderType)
4899
- ? new PerpsControllerError(PERPS_ERROR_CODES.ORDER_SIZE_MIN, PERPS_ERROR_CODES.ORDER_SIZE_MIN)
4878
+ ? new PerpsControllerError(PERPS_ERROR_CODES.ORDER_SIZE_MIN, PERPS_ERROR_CODES.ORDER_SIZE_MIN, undefined, { cause: error })
4900
4879
  : error,
4901
4880
  symbol: params.symbol,
4902
4881
  orderType: params.orderType,
@@ -6542,8 +6521,8 @@ export class HyperLiquidProvider {
6542
6521
  }
6543
6522
  catch (error) {
6544
6523
  this.#recordUnsupportedAccountFromError(error, session.accountContext);
6545
- const message = ensureError(error, 'HyperLiquidProvider.cancelChaseChild').message.toLowerCase();
6546
- if (ALREADY_GONE_CANCEL_MARKERS.some((marker) => message.includes(marker))) {
6524
+ if (normalizeHyperLiquidError(error).errorCode ===
6525
+ PERPS_ERROR_CODES.ORDER_NO_LONGER_OPEN) {
6547
6526
  return CancelChildOutcome.Gone;
6548
6527
  }
6549
6528
  throw error;
@@ -8025,21 +8004,15 @@ export class HyperLiquidProvider {
8025
8004
  };
8026
8005
  }
8027
8006
  catch (error) {
8028
- const signerFailure = await this.#handleSignerFailure(error, 'editOrder', {
8029
- orderId: params.orderId,
8030
- });
8031
- if (signerFailure) {
8032
- return createErrorResult(signerFailure, { success: false });
8033
- }
8034
- this.#deps.logger.error(ensureError(error, 'HyperLiquidProvider.editOrder'), this.#getErrorContext('editOrder', {
8007
+ const mappedError = await this.#reportWriteError(error, 'editOrder', {
8035
8008
  orderId: params.orderId,
8036
8009
  coin: params.newOrder.symbol,
8037
8010
  orderType: params.newOrder.orderType,
8038
8011
  }, {
8039
8012
  operation: PERPS_ERROR_OPERATION.OrderManagement,
8040
8013
  action: PERPS_ERROR_ACTION.EditOrder,
8041
- }));
8042
- return createErrorResult(error, { success: false });
8014
+ });
8015
+ return createErrorResult(mappedError, { success: false });
8043
8016
  }
8044
8017
  }
8045
8018
  /**
@@ -8532,17 +8505,39 @@ export class HyperLiquidProvider {
8532
8505
  }
8533
8506
  // Index submitted and skipped outcomes by symbol so `results` can keep the
8534
8507
  // order of the requested positions: consumers may correlate them by index.
8535
- const submittedResults = new Map(statuses.map((status, index) => [
8536
- orderedPositions[index].symbol,
8537
- {
8508
+ const submittedResults = new Map(statuses.map((status, index) => {
8509
+ const success = isStatusObject(status) &&
8510
+ (hasProperty(status, 'filled') || hasProperty(status, 'resting'));
8511
+ const rawStatusError = isStatusObject(status) &&
8512
+ hasProperty(status, 'error') &&
8513
+ typeof status.error === 'string'
8514
+ ? status.error
8515
+ : undefined;
8516
+ const normalizedStatusError = rawStatusError === undefined
8517
+ ? undefined
8518
+ : normalizeHyperLiquidError(createStatusError(rawStatusError, result));
8519
+ const outcome = {
8538
8520
  symbol: orderedPositions[index].symbol,
8539
- success: isStatusObject(status) &&
8540
- (hasProperty(status, 'filled') || hasProperty(status, 'resting')),
8541
- error: isStatusObject(status) && hasProperty(status, 'error')
8542
- ? String(status.error)
8543
- : undefined,
8544
- },
8545
- ]));
8521
+ success,
8522
+ error: success || normalizedStatusError === undefined
8523
+ ? undefined
8524
+ : normalizedStatusError.message,
8525
+ ...(success || normalizedStatusError === undefined
8526
+ ? {}
8527
+ : {
8528
+ errorCode: normalizedStatusError.errorCode,
8529
+ ...(normalizedStatusError.errorDetails === undefined
8530
+ ? {}
8531
+ : { errorDetails: normalizedStatusError.errorDetails }),
8532
+ }),
8533
+ };
8534
+ return [
8535
+ orderedPositions[index].symbol,
8536
+ success || normalizedStatusError === undefined
8537
+ ? outcome
8538
+ : attachProviderErrorCause(outcome, normalizedStatusError),
8539
+ ];
8540
+ }));
8546
8541
  const skippedBySymbol = new Map(skippedResults.map((skipped) => [skipped.symbol, skipped]));
8547
8542
  return {
8548
8543
  success: successCount > 0,
@@ -8562,34 +8557,31 @@ export class HyperLiquidProvider {
8562
8557
  if (accountContext) {
8563
8558
  this.#recordUnsupportedAccountFromError(error, accountContext);
8564
8559
  }
8565
- const signerFailure = await this.#handleSignerFailure(error, 'closePositions', {
8560
+ const mappedError = await this.#reportWriteError(error instanceof Error
8561
+ ? error
8562
+ : new Error(PERPS_ERROR_CODES.BATCH_CLOSE_FAILED), 'closePositions', {
8566
8563
  positionCount: positionsToClose.length,
8564
+ }, {
8565
+ operation: PERPS_ERROR_OPERATION.PositionManagement,
8566
+ action: PERPS_ERROR_ACTION.ClosePosition,
8567
8567
  });
8568
- const safeError = signerFailure ??
8569
- ensureError(error, 'HyperLiquidProvider.closePositions');
8570
- if (!signerFailure) {
8571
- this.#deps.logger.error(safeError, this.#getErrorContext('closePositions', {
8572
- positionCount: positionsToClose.length,
8573
- }, {
8574
- operation: PERPS_ERROR_OPERATION.PositionManagement,
8575
- action: PERPS_ERROR_ACTION.ClosePosition,
8576
- }));
8577
- }
8568
+ const normalizedError = normalizeHyperLiquidError(mappedError);
8569
+ const { errorDetails } = normalizedError;
8578
8570
  // Return all selected positions as failed, including unavailable DEXes.
8579
8571
  return {
8580
8572
  success: false,
8581
8573
  successCount: 0,
8582
8574
  failureCount: positionsToClose.length + unavailableResults.length,
8583
- error: error instanceof Error
8584
- ? safeError.message
8585
- : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,
8575
+ error: normalizedError.message,
8576
+ errorCode: normalizedError.errorCode,
8577
+ ...(errorDetails === undefined ? {} : { errorDetails }),
8586
8578
  results: [
8587
8579
  ...positionsToClose.map((position) => ({
8588
8580
  symbol: position.symbol,
8589
8581
  success: false,
8590
- error: error instanceof Error
8591
- ? safeError.message
8592
- : PERPS_ERROR_CODES.BATCH_CLOSE_FAILED,
8582
+ error: normalizedError.message,
8583
+ errorCode: normalizedError.errorCode,
8584
+ ...(errorDetails === undefined ? {} : { errorDetails }),
8593
8585
  })),
8594
8586
  ...unavailableResults,
8595
8587
  ],
@@ -9523,19 +9515,15 @@ export class HyperLiquidProvider {
9523
9515
  });
9524
9516
  }
9525
9517
  catch (error) {
9526
- const signerFailure = await this.#handleSignerFailure(error, operationName, { symbol: params.symbol });
9527
- if (signerFailure) {
9528
- return createErrorResult(signerFailure, { success: false });
9529
- }
9530
- this.#deps.logger.error(ensureError(error, `HyperLiquidProvider.${operationName}`), this.#getErrorContext(operationName, {
9518
+ const mappedError = await this.#reportWriteError(error, operationName, {
9531
9519
  symbol: params.symbol,
9532
9520
  hasTakeProfit: params.takeProfitPrice !== undefined,
9533
9521
  hasStopLoss: params.stopLossPrice !== undefined,
9534
9522
  }, {
9535
9523
  operation: PERPS_ERROR_OPERATION.PositionManagement,
9536
9524
  action: PERPS_ERROR_ACTION.PositionTpslUpdate,
9537
- }));
9538
- return createErrorResult(error, { success: false });
9525
+ });
9526
+ return createErrorResult(mappedError, { success: false });
9539
9527
  }
9540
9528
  }
9541
9529
  /**
@@ -9681,6 +9669,8 @@ export class HyperLiquidProvider {
9681
9669
  return result;
9682
9670
  }
9683
9671
  catch (error) {
9672
+ // Setup failures are returned for the service boundary to report. The
9673
+ // result is still normalized so the raw message never crosses it.
9684
9674
  const safeError = ensureError(error, 'HyperLiquidProvider.closePosition');
9685
9675
  this.#deps.debugLogger.log('[closePosition] Close failed', {
9686
9676
  error: safeError.message,
@@ -9764,29 +9754,17 @@ export class HyperLiquidProvider {
9764
9754
  };
9765
9755
  }
9766
9756
  catch (error) {
9767
- const isMultiSigRequired = accountContext
9768
- ? this.#recordUnsupportedAccountFromError(error, accountContext)
9769
- : false;
9770
- const signerFailure = await this.#handleSignerFailure(error, 'updateMargin', {
9771
- symbol: params.symbol,
9772
- });
9773
- if (signerFailure) {
9774
- return { success: false, error: signerFailure.message };
9757
+ if (accountContext) {
9758
+ this.#recordUnsupportedAccountFromError(error, accountContext);
9775
9759
  }
9776
- const safeError = isMultiSigRequired
9777
- ? new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)
9778
- : ensureError(error, 'HyperLiquidProvider.updateMargin');
9779
- this.#deps.logger.error(safeError, this.#getErrorContext('updateMargin', {
9760
+ const mappedError = await this.#reportWriteError(error, 'updateMargin', {
9780
9761
  symbol: params.symbol,
9781
9762
  amount: params.amount,
9782
9763
  }, {
9783
9764
  operation: PERPS_ERROR_OPERATION.PositionManagement,
9784
9765
  action: PERPS_ERROR_ACTION.UpdateMargin,
9785
- }));
9786
- return {
9787
- success: false,
9788
- error: safeError.message,
9789
- };
9766
+ });
9767
+ return createErrorResult(mappedError, { success: false });
9790
9768
  }
9791
9769
  }
9792
9770
  /**
@@ -11890,50 +11868,36 @@ export class HyperLiquidProvider {
11890
11868
  };
11891
11869
  }
11892
11870
  const rejection = new Error(`Withdrawal failed: ${JSON.stringify(result)}`);
11893
- const isMultiSigRequired = this.#recordUnsupportedAccountFromError(rejection, accountContext);
11894
- const errorMessage = isMultiSigRequired
11895
- ? PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED
11896
- : `Withdrawal failed: ${String(result.status)}`;
11871
+ this.#recordUnsupportedAccountFromError(rejection, accountContext);
11897
11872
  this.#deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL FAILED', {
11898
- error: errorMessage,
11873
+ error: rejection.message,
11899
11874
  status: result.status,
11900
11875
  response: result,
11901
11876
  params,
11902
11877
  });
11903
- return {
11904
- success: false,
11905
- error: errorMessage,
11906
- };
11878
+ // A venue status rejection is an expected result, not an exception to
11879
+ // report. Preserve the diagnostic for debugging and normalize for clients.
11880
+ return createErrorResult(rejection, { success: false });
11907
11881
  }
11908
11882
  catch (error) {
11909
- const isMultiSigRequired = accountContext
11910
- ? this.#recordUnsupportedAccountFromError(error, accountContext)
11911
- : false;
11912
- const signerFailure = await this.#handleSignerFailure(error, 'withdraw', {
11913
- assetId: params.assetId,
11914
- });
11915
- if (signerFailure) {
11916
- return createErrorResult(signerFailure, { success: false });
11883
+ if (accountContext) {
11884
+ this.#recordUnsupportedAccountFromError(error, accountContext);
11917
11885
  }
11918
- const safeError = isMultiSigRequired
11919
- ? new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)
11920
- : ensureError(error, 'HyperLiquidProvider.initiateWithdrawal');
11921
11886
  this.#deps.debugLogger.log('HyperLiquidProvider: WITHDRAWAL EXCEPTION', {
11922
- error: safeError.message,
11923
- errorType: safeError.name,
11924
- stack: safeError.stack,
11887
+ error: ensureError(error, 'HyperLiquidProvider.initiateWithdrawal')
11888
+ .message,
11925
11889
  params,
11926
11890
  timestamp: new Date().toISOString(),
11927
11891
  });
11928
- this.#deps.logger.error(safeError, this.#getErrorContext('withdraw', {
11892
+ const mappedError = await this.#reportWriteError(error, 'withdraw', {
11929
11893
  assetId: params.assetId,
11930
11894
  amount: params.amount,
11931
11895
  destination: params.destination,
11932
11896
  }, {
11933
11897
  operation: PERPS_ERROR_OPERATION.FinancialOperations,
11934
11898
  action: PERPS_ERROR_ACTION.FinancialWithdrawal,
11935
- }));
11936
- return createErrorResult(safeError, { success: false });
11899
+ });
11900
+ return createErrorResult(mappedError, { success: false });
11937
11901
  }
11938
11902
  }
11939
11903
  /**
@@ -12037,28 +12001,25 @@ export class HyperLiquidProvider {
12037
12001
  if (this.#recordUnsupportedAccountFromError(new Error(`DEX transfer failed: ${JSON.stringify(result)}`), accountContext)) {
12038
12002
  throw new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED);
12039
12003
  }
12040
- throw new Error(PERPS_ERROR_CODES.TRANSFER_FAILED);
12004
+ throw new Error(PERPS_ERROR_CODES.TRANSFER_FAILED, {
12005
+ cause: new Error(`DEX transfer failed: ${JSON.stringify(result)}`),
12006
+ });
12041
12007
  }
12042
12008
  catch (error) {
12043
- const isMultiSigRequired = accountContext
12044
- ? this.#recordUnsupportedAccountFromError(error, accountContext)
12045
- : false;
12046
- const signerFailure = await this.#handleSignerFailure(error, 'transferBetweenDexs', { sourceDex: params.sourceDex, destinationDex: params.destinationDex });
12047
- if (signerFailure) {
12048
- return { success: false, error: signerFailure.message };
12009
+ if (accountContext) {
12010
+ this.#recordUnsupportedAccountFromError(error, accountContext);
12049
12011
  }
12050
- const safeError = isMultiSigRequired
12051
- ? new Error(PERPS_ERROR_CODES.EXCHANGE_MULTI_SIG_REQUIRED)
12052
- : ensureError(error, 'HyperLiquidProvider.transferToSpot');
12012
+ const mappedError = await this.#reportWriteError(error, 'transferBetweenDexs', {
12013
+ sourceDex: params.sourceDex,
12014
+ destinationDex: params.destinationDex,
12015
+ }, {
12016
+ operation: PERPS_ERROR_OPERATION.FinancialOperations,
12017
+ });
12053
12018
  this.#deps.debugLogger.log('❌ HyperLiquidProvider: TRANSFER FAILED', {
12054
- error: safeError.message,
12019
+ error: mappedError.message,
12055
12020
  params,
12056
12021
  });
12057
- this.#deps.logger.error(safeError, this.#getErrorContext('transferBetweenDexs', { ...params }));
12058
- return {
12059
- success: false,
12060
- error: safeError.message,
12061
- };
12022
+ return createErrorResult(mappedError, { success: false });
12062
12023
  }
12063
12024
  }
12064
12025
  /**
@@ -12440,7 +12401,7 @@ export class HyperLiquidProvider {
12440
12401
  async prepareTradingWallet() {
12441
12402
  // Nothing can be signed, so run no setup (and log nothing) until it can.
12442
12403
  if (!this.#walletService.isMainAccountSignerReady()) {
12443
- return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
12404
+ return createNotReadyResult(PERPS_ERROR_CODES.KEYRING_LOCKED);
12444
12405
  }
12445
12406
  try {
12446
12407
  const lifecycleGeneration = this.#lifecycleGeneration;
@@ -12473,12 +12434,9 @@ export class HyperLiquidProvider {
12473
12434
  // The venue rejects every write from a wallet with no HyperLiquid account
12474
12435
  // yet, so it is not asked to sign a builder fee approval either.
12475
12436
  if (!isRegistered) {
12476
- return {
12477
- ready: false,
12478
- error: this.#walletService.isMainAccountSignerReady()
12479
- ? PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND
12480
- : PERPS_ERROR_CODES.KEYRING_LOCKED,
12481
- };
12437
+ return createNotReadyResult(this.#walletService.isMainAccountSignerReady()
12438
+ ? PERPS_ERROR_CODES.EXCHANGE_ACCOUNT_NOT_FOUND
12439
+ : PERPS_ERROR_CODES.KEYRING_LOCKED);
12482
12440
  }
12483
12441
  await this.#ensureBuilderFeeSetup(undefined, {
12484
12442
  reportSignerFailure: true,
@@ -12487,7 +12445,7 @@ export class HyperLiquidProvider {
12487
12445
  // The builder fee setup ends quietly when the provider disconnects.
12488
12446
  await assertPreparationCurrent();
12489
12447
  if (!this.#walletService.isMainAccountSignerReady()) {
12490
- return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
12448
+ return createNotReadyResult(PERPS_ERROR_CODES.KEYRING_LOCKED);
12491
12449
  }
12492
12450
  const ready = this.#tradingSetupComplete &&
12493
12451
  !this.#unifiedAccountSetupNeedsRetry &&
@@ -12499,9 +12457,10 @@ export class HyperLiquidProvider {
12499
12457
  // it ran): retryable, not logged.
12500
12458
  if (isKeyringLockedError(error) ||
12501
12459
  !this.#walletService.isMainAccountSignerReady()) {
12502
- return { ready: false, error: PERPS_ERROR_CODES.KEYRING_LOCKED };
12460
+ return createNotReadyResult(PERPS_ERROR_CODES.KEYRING_LOCKED);
12503
12461
  }
12504
12462
  const caughtError = ensureError(error, 'HyperLiquidProvider.prepareTradingWallet');
12463
+ const normalizedError = normalizeHyperLiquidError(caughtError);
12505
12464
  if (caughtError.message === PERPS_ERROR_CODES.PROVIDER_LIFECYCLE_STALE) {
12506
12465
  this.#deps.debugLogger.log('[prepareTradingWallet] Provider replaced during preparation');
12507
12466
  }
@@ -12513,9 +12472,9 @@ export class HyperLiquidProvider {
12513
12472
  this.#deps.debugLogger.log('[prepareTradingWallet] Builder fee approval refused', { error: caughtError.message });
12514
12473
  }
12515
12474
  else {
12516
- this.#deps.logger.error(caughtError, this.#getErrorContext('prepareTradingWallet'));
12475
+ this.#deps.logger.error(normalizedError, this.#getErrorContext('prepareTradingWallet'));
12517
12476
  }
12518
- return { ready: false, error: caughtError.message };
12477
+ return createNotReadyResult(normalizedError);
12519
12478
  }
12520
12479
  }
12521
12480
  /**
@@ -12546,12 +12505,9 @@ export class HyperLiquidProvider {
12546
12505
  }
12547
12506
  catch (error) {
12548
12507
  return {
12549
- ready: false,
12508
+ ...createNotReadyResult(error),
12550
12509
  walletConnected: false,
12551
12510
  networkSupported: false,
12552
- error: error instanceof Error
12553
- ? error.message
12554
- : PERPS_ERROR_CODES.UNKNOWN_ERROR,
12555
12511
  };
12556
12512
  }
12557
12513
  }