@metamask-previews/perps-controller 11.0.0-preview-9c0f91815 → 11.0.0-preview-e57e5c3dc

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 (82) hide show
  1. package/CHANGELOG.md +0 -49
  2. package/dist/PerpsController.cjs.map +1 -1
  3. package/dist/PerpsController.d.cts +1 -1
  4. package/dist/PerpsController.d.cts.map +1 -1
  5. package/dist/PerpsController.d.mts +1 -1
  6. package/dist/PerpsController.d.mts.map +1 -1
  7. package/dist/PerpsController.mjs.map +1 -1
  8. package/dist/constants/eventNames.cjs +0 -4
  9. package/dist/constants/eventNames.cjs.map +1 -1
  10. package/dist/constants/eventNames.d.cts +0 -3
  11. package/dist/constants/eventNames.d.cts.map +1 -1
  12. package/dist/constants/eventNames.d.mts +0 -3
  13. package/dist/constants/eventNames.d.mts.map +1 -1
  14. package/dist/constants/eventNames.mjs +0 -4
  15. package/dist/constants/eventNames.mjs.map +1 -1
  16. package/dist/constants/perpsConfig.cjs +1 -54
  17. package/dist/constants/perpsConfig.cjs.map +1 -1
  18. package/dist/constants/perpsConfig.d.cts +2 -71
  19. package/dist/constants/perpsConfig.d.cts.map +1 -1
  20. package/dist/constants/perpsConfig.d.mts +2 -71
  21. package/dist/constants/perpsConfig.d.mts.map +1 -1
  22. package/dist/constants/perpsConfig.mjs +0 -53
  23. package/dist/constants/perpsConfig.mjs.map +1 -1
  24. package/dist/index.cjs +3 -12
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +4 -4
  27. package/dist/index.d.cts.map +1 -1
  28. package/dist/index.d.mts +4 -4
  29. package/dist/index.d.mts.map +1 -1
  30. package/dist/index.mjs +2 -2
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/perpsErrorCodes.cjs +0 -20
  33. package/dist/perpsErrorCodes.cjs.map +1 -1
  34. package/dist/perpsErrorCodes.d.cts +0 -19
  35. package/dist/perpsErrorCodes.d.cts.map +1 -1
  36. package/dist/perpsErrorCodes.d.mts +0 -19
  37. package/dist/perpsErrorCodes.d.mts.map +1 -1
  38. package/dist/perpsErrorCodes.mjs +0 -20
  39. package/dist/perpsErrorCodes.mjs.map +1 -1
  40. package/dist/providers/HyperLiquidProvider.cjs +14 -1276
  41. package/dist/providers/HyperLiquidProvider.cjs.map +1 -1
  42. package/dist/providers/HyperLiquidProvider.d.cts.map +1 -1
  43. package/dist/providers/HyperLiquidProvider.d.mts.map +1 -1
  44. package/dist/providers/HyperLiquidProvider.mjs +17 -1279
  45. package/dist/providers/HyperLiquidProvider.mjs.map +1 -1
  46. package/dist/types/index.cjs.map +1 -1
  47. package/dist/types/index.d.cts +2 -40
  48. package/dist/types/index.d.cts.map +1 -1
  49. package/dist/types/index.d.mts +2 -40
  50. package/dist/types/index.d.mts.map +1 -1
  51. package/dist/types/index.mjs.map +1 -1
  52. package/dist/types/perps-types.cjs.map +1 -1
  53. package/dist/types/perps-types.d.cts +2 -33
  54. package/dist/types/perps-types.d.cts.map +1 -1
  55. package/dist/types/perps-types.d.mts +2 -33
  56. package/dist/types/perps-types.d.mts.map +1 -1
  57. package/dist/types/perps-types.mjs.map +1 -1
  58. package/dist/utils/hyperLiquidValidation.cjs +3 -192
  59. package/dist/utils/hyperLiquidValidation.cjs.map +1 -1
  60. package/dist/utils/hyperLiquidValidation.d.cts +3 -30
  61. package/dist/utils/hyperLiquidValidation.d.cts.map +1 -1
  62. package/dist/utils/hyperLiquidValidation.d.mts +3 -30
  63. package/dist/utils/hyperLiquidValidation.d.mts.map +1 -1
  64. package/dist/utils/hyperLiquidValidation.mjs +5 -194
  65. package/dist/utils/hyperLiquidValidation.mjs.map +1 -1
  66. package/dist/utils/orderCalculations.cjs +1 -131
  67. package/dist/utils/orderCalculations.cjs.map +1 -1
  68. package/dist/utils/orderCalculations.d.cts +3 -88
  69. package/dist/utils/orderCalculations.d.cts.map +1 -1
  70. package/dist/utils/orderCalculations.d.mts +3 -88
  71. package/dist/utils/orderCalculations.d.mts.map +1 -1
  72. package/dist/utils/orderCalculations.mjs +2 -128
  73. package/dist/utils/orderCalculations.mjs.map +1 -1
  74. package/dist/utils/orderTypes.cjs +4 -56
  75. package/dist/utils/orderTypes.cjs.map +1 -1
  76. package/dist/utils/orderTypes.d.cts +3 -32
  77. package/dist/utils/orderTypes.d.cts.map +1 -1
  78. package/dist/utils/orderTypes.d.mts +3 -32
  79. package/dist/utils/orderTypes.d.mts.map +1 -1
  80. package/dist/utils/orderTypes.mjs +3 -54
  81. package/dist/utils/orderTypes.mjs.map +1 -1
  82. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidValidation.d.mts","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,WAAW,EAAE,GAAG,EAAE,wBAAwB;AAaxD,OAAO,KAAK,EACV,uBAAuB,EACvB,gBAAgB,EACjB,2BAA0B;AAC3B,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,iCAAgC;AAStE;;;;GAIG;AACH,MAAM,MAAM,qBAAqB,GAAG,gBAAgB,GAAG,SAAS,CAAC;AAEjE;;GAEG;AAEH;;;;;;GAMG;AACH,wBAAgB,iBAAiB,CAC/B,MAAM,SAAS;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EACnD,KAAK,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,GAAG,MAAM,CAOjD;AAED;;;;;;;;;GASG;AACH,wBAAgB,wBAAwB,CACtC,MAAM,EAAE;IACN,OAAO,CAAC,EAAE,WAAW,CAAC;IACtB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,GAAG,CAAC;CACnB,EACD,WAAW,CAAC,EAAE,qBAAqB,GAClC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAkEtC;AAED;;;;;;;;;GASG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KAAK,CAAC;CACrC,GAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAqIvC;AA2DD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,GACjC;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,CAStC"}
@@ -1,8 +1,8 @@
1
1
  import { isValidHexAddress } from "@metamask/utils";
2
2
  import { HYPERLIQUID_ASSET_CONFIGS, getSupportedAssets, TRADING_DEFAULTS } from "../constants/hyperLiquidConfig.mjs";
3
- import { CHASE_ORDER_CONFIG, HYPERLIQUID_ORDER_LIMITS, HYPERLIQUID_TWAP_LIMITS } from "../constants/perpsConfig.mjs";
3
+ import { HYPERLIQUID_ORDER_LIMITS } from "../constants/perpsConfig.mjs";
4
4
  import { PERPS_ERROR_CODES } from "../perpsErrorCodes.mjs";
5
- import { getTriggerExecution, isLimitExecutionOrderType, isStrategyOrderType, isTriggerOrderType, SCALE_ORDER_COUNT } from "./orderTypes.mjs";
5
+ import { isLimitExecutionOrderType, isTriggerOrderType } from "./orderTypes.mjs";
6
6
  /**
7
7
  * Validation utilities for HyperLiquid operations
8
8
  */
@@ -343,9 +343,8 @@ export function getSupportedPaths(params, debugLogger) {
343
343
  * Based on HyperLiquid contract specifications.
344
344
  *
345
345
  * @param maxLeverage - The maximum leverage for the market
346
- * @param orderType - The order type; every type follows the limit/market
347
- * multiplier of its execution mode, so `stop_limit`, `scale` and `chase` are all
348
- * treated as limit orders and `twap` as a market order
346
+ * @param orderType - The order type; trigger types follow the limit/market
347
+ * multiplier of their execution mode (e.g. `stop_limit` is treated as a limit order)
349
348
  * @returns Maximum order value in USD
350
349
  */
351
350
  export function getMaxOrderValue(maxLeverage, orderType) {
@@ -362,11 +361,7 @@ export function getMaxOrderValue(maxLeverage, orderType) {
362
361
  else {
363
362
  marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.LowLeverage;
364
363
  }
365
- // The higher cap follows how the order executes, not whose price it uses: a
366
- // scale ladder and a chase rest limit orders on the book, so holding them to
367
- // the tighter market-order cap would bound them by how they were requested
368
- // rather than by what they do.
369
- return getTriggerExecution(orderType) === 'limit'
364
+ return isLimitExecutionOrderType(orderType)
370
365
  ? marketLimit * HYPERLIQUID_ORDER_LIMITS.LimitOrderMultiplier
371
366
  : marketLimit;
372
367
  }
@@ -379,175 +374,6 @@ const TPSL_LINKAGE_GROUPING = {
379
374
  order: 'normalTpsl',
380
375
  position: 'positionTpsl',
381
376
  };
382
- /**
383
- * Which strategy owns each strategy-only field.
384
- *
385
- * Anything a placement does not own is rejected rather than ignored: a `twap`
386
- * carrying `scaleNumOrders` is a caller mistake, and dropping it silently would
387
- * execute something other than what was asked for.
388
- */
389
- const STRATEGY_FIELD_OWNER = {
390
- twapDuration: 'twap',
391
- twapRandomize: 'twap',
392
- scaleMinPrice: 'scale',
393
- scaleMaxPrice: 'scale',
394
- scaleNumOrders: 'scale',
395
- chaseIntervalMs: 'chase',
396
- chaseMaxDurationMs: 'chase',
397
- chaseMaxRepricings: 'chase',
398
- };
399
- /**
400
- * Validate the TWAP-specific parameters of a `twap` placement.
401
- *
402
- * @param params - Strategy fields supplied by the caller.
403
- * @returns Validation result with isValid flag and optional error message.
404
- */
405
- function validateTwapParams(params) {
406
- if (params.twapDuration === undefined) {
407
- return {
408
- isValid: false,
409
- error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,
410
- };
411
- }
412
- // The venue validates `twap.m` as a safe integer within these bounds before
413
- // the request is signed, so checking it here turns an opaque SDK failure into
414
- // a typed rejection that costs no round trip.
415
- if (!Number.isInteger(params.twapDuration) ||
416
- params.twapDuration < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||
417
- params.twapDuration > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes) {
418
- return {
419
- isValid: false,
420
- error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,
421
- };
422
- }
423
- return { isValid: true };
424
- }
425
- /**
426
- * Validate the ladder parameters of a `scale` placement.
427
- *
428
- * @param params - Strategy fields supplied by the caller.
429
- * @returns Validation result with isValid flag and optional error message.
430
- */
431
- function validateScaleParams(params) {
432
- if (params.scaleMinPrice === undefined ||
433
- params.scaleMaxPrice === undefined) {
434
- return {
435
- isValid: false,
436
- error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,
437
- };
438
- }
439
- const minPrice = parseFloat(params.scaleMinPrice);
440
- const maxPrice = parseFloat(params.scaleMaxPrice);
441
- if (!Number.isFinite(minPrice) ||
442
- !Number.isFinite(maxPrice) ||
443
- minPrice <= 0 ||
444
- maxPrice <= minPrice) {
445
- return {
446
- isValid: false,
447
- error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,
448
- };
449
- }
450
- if (params.scaleNumOrders === undefined ||
451
- !Number.isInteger(params.scaleNumOrders) ||
452
- params.scaleNumOrders < SCALE_ORDER_COUNT.min ||
453
- params.scaleNumOrders > SCALE_ORDER_COUNT.max) {
454
- return {
455
- isValid: false,
456
- error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,
457
- };
458
- }
459
- return { isValid: true };
460
- }
461
- /**
462
- * Validate the polling parameters of a `chase` placement.
463
- *
464
- * @param params - Strategy fields supplied by the caller.
465
- * @returns Validation result with isValid flag and optional error message.
466
- */
467
- function validateChaseParams(params) {
468
- const interval = params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;
469
- if (!Number.isFinite(interval) ||
470
- interval < CHASE_ORDER_CONFIG.MinIntervalMs) {
471
- return {
472
- isValid: false,
473
- error: PERPS_ERROR_CODES.ORDER_CHASE_INTERVAL_INVALID,
474
- };
475
- }
476
- const maxDuration = params.chaseMaxDurationMs ?? CHASE_ORDER_CONFIG.DefaultMaxDurationMs;
477
- // A window shorter than one poll would place the order and immediately stop
478
- // chasing it — a plain post-only limit order wearing a chase's name.
479
- if (!Number.isFinite(maxDuration) || maxDuration < interval) {
480
- return {
481
- isValid: false,
482
- error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,
483
- };
484
- }
485
- const maxRepricings = params.chaseMaxRepricings ?? CHASE_ORDER_CONFIG.DefaultMaxRepricings;
486
- if (!Number.isInteger(maxRepricings) || maxRepricings < 1) {
487
- return {
488
- isValid: false,
489
- error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,
490
- };
491
- }
492
- return { isValid: true };
493
- }
494
- /**
495
- * Validate strategy placement parameters, and the absence of them.
496
- *
497
- * Runs before every other order rule so a strategy placement is rejected with a
498
- * strategy-shaped reason rather than with the trigger/limit rule its shape
499
- * happens to trip first.
500
- *
501
- * @param params - Order parameters to validate.
502
- * @param params.orderType - The order placement type.
503
- * @returns Validation result with isValid flag and optional error message.
504
- */
505
- function validateStrategyOrderParams(params) {
506
- const { orderType } = params;
507
- const strategy = orderType !== undefined && isStrategyOrderType(orderType)
508
- ? orderType
509
- : undefined;
510
- // Every strategy-only field must belong to the placement carrying it. This
511
- // also covers the non-strategy case, where no field has an owner to match.
512
- const foreignField = Object.keys(STRATEGY_FIELD_OWNER).find((field) => params[field] !== undefined && STRATEGY_FIELD_OWNER[field] !== strategy);
513
- if (foreignField) {
514
- return {
515
- isValid: false,
516
- error: PERPS_ERROR_CODES.ORDER_STRATEGY_PARAMS_NOT_SUPPORTED,
517
- };
518
- }
519
- if (!strategy) {
520
- return { isValid: true };
521
- }
522
- // A strategy owns its own execution: it derives its own prices, rests its own
523
- // orders, and decides its own time in force. Accepting these fields would
524
- // mean quietly ignoring them.
525
- //
526
- // `clientOrderId` is refused for the same reason and cannot be honoured even
527
- // in principle: the venue's TWAP action carries no client id, a scale ladder
528
- // is many orders and a client id must be unique per order, and a chase
529
- // replaces its order on every re-price. One id cannot name any of them.
530
- if (params.price !== undefined ||
531
- params.triggerPrice !== undefined ||
532
- params.timeInForce !== undefined ||
533
- params.clientOrderId !== undefined ||
534
- params.takeProfitPrice !== undefined ||
535
- params.stopLossPrice !== undefined ||
536
- params.takeProfitSize !== undefined ||
537
- params.stopLossSize !== undefined) {
538
- return {
539
- isValid: false,
540
- error: PERPS_ERROR_CODES.ORDER_STRATEGY_FIELD_UNSUPPORTED,
541
- };
542
- }
543
- if (strategy === 'twap') {
544
- return validateTwapParams(params);
545
- }
546
- if (strategy === 'scale') {
547
- return validateScaleParams(params);
548
- }
549
- return validateChaseParams(params);
550
- }
551
377
  /**
552
378
  * Validate order parameters.
553
379
  * Basic validation - checks required fields are present.
@@ -567,15 +393,6 @@ function validateStrategyOrderParams(params) {
567
393
  * @param params.tpslLinkage - How an attached TP/SL is linked
568
394
  * @param params.grouping - Deprecated protocol-shaped spelling of `tpslLinkage`
569
395
  * @param params.timeInForce - Time in force; only a plain limit order can carry one
570
- * @param params.clientOrderId - Client-provided order ID; a strategy placement cannot carry one
571
- * @param params.twapDuration - TWAP window in whole minutes
572
- * @param params.twapRandomize - Whether to randomize the TWAP slice timing
573
- * @param params.scaleMinPrice - Lowest price in a scale ladder
574
- * @param params.scaleMaxPrice - Highest price in a scale ladder
575
- * @param params.scaleNumOrders - How many orders a scale ladder fans out into
576
- * @param params.chaseIntervalMs - How often a chase re-reads the touch
577
- * @param params.chaseMaxDurationMs - How long a chase keeps re-pricing
578
- * @param params.chaseMaxRepricings - Cap on a chase's cancel/replace cycles
579
396
  * @returns Validation result with isValid flag and optional error message
580
397
  */
581
398
  export function validateOrderParams(params) {
@@ -586,12 +403,6 @@ export function validateOrderParams(params) {
586
403
  };
587
404
  }
588
405
  // Note: Size validation removed - validateOrder handles amount validation using USD as source of truth
589
- // Strategy placements are decided first: their shape trips the limit-price and
590
- // trigger rules below, and the strategy-shaped reason is the useful one.
591
- const strategyValidation = validateStrategyOrderParams(params);
592
- if (!strategyValidation.isValid) {
593
- return strategyValidation;
594
- }
595
406
  const { orderType } = params;
596
407
  const isTrigger = orderType !== undefined && isTriggerOrderType(orderType);
597
408
  // Require price for orders that execute as limit orders (limit, stop_limit,
@@ -1 +1 @@
1
- {"version":3,"file":"hyperLiquidValidation.mjs","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,wBAAwB;AAGpD,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,EACjB,2CAA0C;AAC3C,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,uBAAuB,EACxB,qCAAoC;AACrC,OAAO,EAAE,iBAAiB,EAAE,+BAA8B;AAM1D,OAAO,EACL,mBAAmB,EACnB,yBAAyB,EACzB,mBAAmB,EACnB,kBAAkB,EAClB,iBAAiB,EAClB,yBAAwB;AASzB;;GAEG;AAEH;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAE/B,KAAc,EAAE,eAAuB;IACvC,OAAO;QACL,GAAG,eAAe;QAClB,OAAO,EAAE,KAAK;QACd,KAAK,EACH,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC,aAAa;KAC3E,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAIC,EACD,WAAmC;IAEnC,WAAW,EAAE,GAAG,CAAC,+CAA+C,EAAE;QAChE,MAAM;QACN,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC;QACnC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;QACjC,cAAc,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC;KAC5C,CAAC,CAAC;IAEH,+BAA+B;IAC/B,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,WAAW,EAAE,GAAG,CAAC,2CAA2C,EAAE;YAC5D,KAAK,EAAE,iBAAiB,CAAC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,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,iBAAiB,CAAC,kBAAkB;SAC5C,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { isValidHexAddress } from '@metamask/utils';\nimport type { CaipAssetId, Hex } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_ASSET_CONFIGS,\n getSupportedAssets,\n TRADING_DEFAULTS,\n} from '../constants/hyperLiquidConfig.js';\nimport {\n CHASE_ORDER_CONFIG,\n HYPERLIQUID_ORDER_LIMITS,\n HYPERLIQUID_TWAP_LIMITS,\n} from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n GetSupportedPathsParams,\n PerpsDebugLogger,\n} from '../types/index.js';\nimport type { OrderType, TpslLinkage } from '../types/perps-types.js';\nimport {\n getTriggerExecution,\n isLimitExecutionOrderType,\n isStrategyOrderType,\n isTriggerOrderType,\n SCALE_ORDER_COUNT,\n} from './orderTypes.js';\n\n/**\n * Optional debug logger for validation functions.\n * When provided, enables detailed logging for debugging.\n * When omitted, validation runs silently.\n */\nexport type ValidationDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Validation utilities for HyperLiquid operations\n */\n\n/**\n * Create standardized error response.\n *\n * @param error - The error that occurred\n * @param defaultResponse - The default response object to use as template\n * @returns The error response with success=false and error message\n */\nexport function createErrorResult<\n TValue extends { success: boolean; error?: string },\n>(error: unknown, defaultResponse: TValue): TValue {\n return {\n ...defaultResponse,\n success: false,\n error:\n error instanceof Error ? error.message : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n}\n\n/**\n * Validate withdrawal parameters.\n *\n * @param params - Withdrawal parameters to validate\n * @param params.assetId - The CAIP asset ID to withdraw\n * @param params.amount - Amount to withdraw as string\n * @param params.destination - Optional destination hex address\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateWithdrawalParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n destination?: Hex;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateWithdrawalParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n hasDestination: Boolean(params.destination),\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateWithdrawalParams: Missing assetId', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateWithdrawalParams: Missing amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateWithdrawalParams: Invalid amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n };\n }\n\n // Validate destination address if provided\n if (params.destination && !isValidHexAddress(params.destination)) {\n debugLogger?.log('validateWithdrawalParams: Invalid destination address', {\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n destination: params.destination,\n isValidHex: isValidHexAddress(params.destination),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n };\n }\n\n debugLogger?.log('validateWithdrawalParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination ?? 'will use user wallet',\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate deposit parameters.\n *\n * @param params - Deposit parameters to validate\n * @param params.assetId - The CAIP asset ID to deposit\n * @param params.amount - Amount to deposit as string\n * @param params.isTestnet - Whether this is a testnet deposit\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateDepositParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n isTestnet?: boolean;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateDepositParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n isTestnet: params.isTestnet,\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateDepositParams: Missing assetId', {\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateDepositParams: Missing amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateDepositParams: Invalid amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n };\n }\n\n // Check minimum deposit amount\n const minimumAmount = params.isTestnet\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n debugLogger?.log('validateDepositParams: Checking minimum amount', {\n amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n network: params.isTestnet ? 'testnet' : 'mainnet',\n });\n\n if (amount < minimumAmount) {\n debugLogger?.log('validateDepositParams: Below minimum deposit', {\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n amount,\n minimumAmount,\n difference: minimumAmount - amount,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n };\n }\n\n debugLogger?.log('validateDepositParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n parsedAmount: amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate asset support for withdrawals using AssetRoute arrays.\n *\n * @param assetId - The CAIP asset ID to validate\n * @param supportedRoutes - Array of supported asset routes\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateAssetSupport(\n assetId: CaipAssetId,\n supportedRoutes: { assetId: CaipAssetId }[],\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateAssetSupport: Checking asset support', {\n assetId,\n supportedRoutesCount: supportedRoutes.length,\n });\n\n const supportedAssetIds = supportedRoutes.map((route) => route.assetId);\n\n // Check if asset is supported\n const isSupported = supportedAssetIds.includes(assetId);\n\n if (!isSupported) {\n // Also check case-insensitive match for contract addresses\n const isSupportedCaseInsensitive = supportedAssetIds.some(\n (supportedId) => supportedId.toLowerCase() === assetId.toLowerCase(),\n );\n\n if (!isSupportedCaseInsensitive) {\n debugLogger?.log('validateAssetSupport: Asset not supported', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n assetId,\n supportedAssetIds,\n checkedCaseInsensitive: true,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n };\n }\n\n debugLogger?.log(\n '⚠️ validateAssetSupport: Asset supported with case mismatch',\n {\n providedAssetId: assetId,\n matchedAssetId: supportedAssetIds.find(\n (id) => id.toLowerCase() === assetId.toLowerCase(),\n ),\n },\n );\n }\n\n debugLogger?.log('validateAssetSupport: Asset is supported', {\n assetId,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate balance against withdrawal amount.\n *\n * @param withdrawAmount - The amount to withdraw\n * @param withdrawableBalance - Max USD that can leave the venue right now\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateBalance(\n withdrawAmount: number,\n withdrawableBalance: number,\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateBalance: Checking balance sufficiency', {\n withdrawAmount,\n withdrawableBalance,\n difference: withdrawableBalance - withdrawAmount,\n });\n\n if (withdrawAmount > withdrawableBalance) {\n const shortfall = withdrawAmount - withdrawableBalance;\n\n debugLogger?.log('validateBalance: Insufficient balance', {\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n withdrawAmount,\n withdrawableBalance,\n shortfall,\n percentageOfAvailable: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n };\n }\n\n const remainingBalance = withdrawableBalance - withdrawAmount;\n debugLogger?.log('validateBalance: Balance is sufficient', {\n withdrawAmount,\n withdrawableBalance,\n remainingBalance,\n percentageUsed: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return { isValid: true };\n}\n\n/**\n * Apply filters to asset paths with comprehensive logging.\n *\n * @param assets - Array of CAIP asset IDs to filter\n * @param params - Filter parameters including chainId, symbol, and assetId\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Filtered array of CAIP asset IDs\n */\nexport function applyPathFilters(\n assets: CaipAssetId[],\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n if (!params) {\n debugLogger?.log(\n 'HyperLiquid: applyPathFilters - no params, returning all assets',\n { assets },\n );\n return assets;\n }\n\n let filtered = assets;\n\n debugLogger?.log('HyperLiquid: applyPathFilters - starting filter', {\n initialAssets: assets,\n filterParams: params,\n });\n\n if (params.chainId) {\n const before = filtered;\n filtered = filtered.filter((asset) =>\n asset.startsWith(params.chainId as string),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - chainId filter', {\n chainId: params.chainId,\n before,\n after: filtered,\n });\n }\n\n // Note: `in` is the idiomatic TypeScript way to narrow a string to\n // `keyof typeof` for indexed access; `hasProperty` types the indexed\n // result as `unknown` and loses the `{ testnet, mainnet }` shape.\n /* eslint-disable-next-line no-restricted-syntax */\n if (params.symbol && params.symbol in HYPERLIQUID_ASSET_CONFIGS) {\n const config =\n HYPERLIQUID_ASSET_CONFIGS[\n params.symbol as keyof typeof HYPERLIQUID_ASSET_CONFIGS\n ];\n const isTestnet = params.isTestnet ?? false;\n const selectedAsset = isTestnet ? config.testnet : config.mainnet;\n const before = filtered;\n filtered = [selectedAsset];\n debugLogger?.log('HyperLiquid: applyPathFilters - symbol filter', {\n symbol: params.symbol,\n isTestnet,\n config,\n selectedAsset,\n before,\n after: filtered,\n });\n }\n\n if (params.assetId) {\n const before = filtered;\n // Use case-insensitive comparison for asset ID matching to handle address case differences\n filtered = filtered.filter(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - assetId filter', {\n assetId: params.assetId,\n before,\n after: filtered,\n exactMatch: before.includes(params.assetId),\n caseInsensitiveMatch: before.some(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n ),\n });\n }\n\n debugLogger?.log('HyperLiquid: applyPathFilters - final result', {\n initialAssets: assets,\n finalFiltered: filtered,\n filterParams: params,\n });\n\n return filtered;\n}\n\n/**\n * Get supported deposit/withdrawal paths with filtering.\n *\n * @param params - Filter parameters including isTestnet, chainId, symbol\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Array of supported CAIP asset IDs\n */\nexport function getSupportedPaths(\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n const isTestnet = params?.isTestnet ?? false;\n const assets = getSupportedAssets(isTestnet);\n const filteredAssets = applyPathFilters(assets, params, debugLogger);\n\n debugLogger?.log('HyperLiquid: getSupportedPaths', {\n isTestnet,\n requestedParams: params,\n allAssets: assets,\n filteredAssets,\n returnType: 'CaipAssetId[]',\n example: filteredAssets[0],\n });\n\n return filteredAssets;\n}\n\n/**\n * Get maximum order value based on leverage and order type.\n * Based on HyperLiquid contract specifications.\n *\n * @param maxLeverage - The maximum leverage for the market\n * @param orderType - The order type; every type follows the limit/market\n * multiplier of its execution mode, so `stop_limit`, `scale` and `chase` are all\n * treated as limit orders and `twap` as a market order\n * @returns Maximum order value in USD\n */\nexport function getMaxOrderValue(\n maxLeverage: number,\n orderType: OrderType,\n): number {\n let marketLimit: number;\n\n if (maxLeverage >= 25) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.HighLeverage;\n } else if (maxLeverage >= 20) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumHighLeverage;\n } else if (maxLeverage >= 10) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumLeverage;\n } else {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.LowLeverage;\n }\n\n // The higher cap follows how the order executes, not whose price it uses: a\n // scale ladder and a chase rest limit orders on the book, so holding them to\n // the tighter market-order cap would bound them by how they were requested\n // rather than by what they do.\n return getTriggerExecution(orderType) === 'limit'\n ? marketLimit * HYPERLIQUID_ORDER_LIMITS.LimitOrderMultiplier\n : marketLimit;\n}\n\n/**\n * The `grouping` value each provider-agnostic linkage corresponds to, used to\n * detect a caller supplying both spellings with different meanings.\n */\nconst TPSL_LINKAGE_GROUPING: Record<\n TpslLinkage,\n 'na' | 'normalTpsl' | 'positionTpsl'\n> = {\n none: 'na',\n order: 'normalTpsl',\n position: 'positionTpsl',\n};\n\n/**\n * The strategy-placement fields of `OrderParams`, as validation sees them.\n *\n * Named so the provider can forward exactly this group to `validateOrderParams`\n * without the field list drifting between the two call sites.\n */\nexport type StrategyOrderValidationParams = {\n twapDuration?: number;\n twapRandomize?: boolean;\n scaleMinPrice?: string;\n scaleMaxPrice?: string;\n scaleNumOrders?: number;\n chaseIntervalMs?: number;\n chaseMaxDurationMs?: number;\n chaseMaxRepricings?: number;\n};\n\n/**\n * Which strategy owns each strategy-only field.\n *\n * Anything a placement does not own is rejected rather than ignored: a `twap`\n * carrying `scaleNumOrders` is a caller mistake, and dropping it silently would\n * execute something other than what was asked for.\n */\nconst STRATEGY_FIELD_OWNER: Record<\n keyof StrategyOrderValidationParams,\n 'twap' | 'scale' | 'chase'\n> = {\n twapDuration: 'twap',\n twapRandomize: 'twap',\n scaleMinPrice: 'scale',\n scaleMaxPrice: 'scale',\n scaleNumOrders: 'scale',\n chaseIntervalMs: 'chase',\n chaseMaxDurationMs: 'chase',\n chaseMaxRepricings: 'chase',\n};\n\n/**\n * Validate the TWAP-specific parameters of a `twap` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateTwapParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (params.twapDuration === undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_REQUIRED,\n };\n }\n\n // The venue validates `twap.m` as a safe integer within these bounds before\n // the request is signed, so checking it here turns an opaque SDK failure into\n // a typed rejection that costs no round trip.\n if (\n !Number.isInteger(params.twapDuration) ||\n params.twapDuration < HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes ||\n params.twapDuration > HYPERLIQUID_TWAP_LIMITS.MaxDurationMinutes\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TWAP_DURATION_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the ladder parameters of a `scale` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateScaleParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n if (\n params.scaleMinPrice === undefined ||\n params.scaleMaxPrice === undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_REQUIRED,\n };\n }\n\n const minPrice = parseFloat(params.scaleMinPrice);\n const maxPrice = parseFloat(params.scaleMaxPrice);\n if (\n !Number.isFinite(minPrice) ||\n !Number.isFinite(maxPrice) ||\n minPrice <= 0 ||\n maxPrice <= minPrice\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID,\n };\n }\n\n if (\n params.scaleNumOrders === undefined ||\n !Number.isInteger(params.scaleNumOrders) ||\n params.scaleNumOrders < SCALE_ORDER_COUNT.min ||\n params.scaleNumOrders > SCALE_ORDER_COUNT.max\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate the polling parameters of a `chase` placement.\n *\n * @param params - Strategy fields supplied by the caller.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateChaseParams(params: StrategyOrderValidationParams): {\n isValid: boolean;\n error?: string;\n} {\n const interval =\n params.chaseIntervalMs ?? CHASE_ORDER_CONFIG.DefaultIntervalMs;\n if (\n !Number.isFinite(interval) ||\n interval < CHASE_ORDER_CONFIG.MinIntervalMs\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_INTERVAL_INVALID,\n };\n }\n\n const maxDuration =\n params.chaseMaxDurationMs ?? CHASE_ORDER_CONFIG.DefaultMaxDurationMs;\n // A window shorter than one poll would place the order and immediately stop\n // chasing it — a plain post-only limit order wearing a chase's name.\n if (!Number.isFinite(maxDuration) || maxDuration < interval) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n const maxRepricings =\n params.chaseMaxRepricings ?? CHASE_ORDER_CONFIG.DefaultMaxRepricings;\n if (!Number.isInteger(maxRepricings) || maxRepricings < 1) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_CHASE_DURATION_INVALID,\n };\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate strategy placement parameters, and the absence of them.\n *\n * Runs before every other order rule so a strategy placement is rejected with a\n * strategy-shaped reason rather than with the trigger/limit rule its shape\n * happens to trip first.\n *\n * @param params - Order parameters to validate.\n * @param params.orderType - The order placement type.\n * @returns Validation result with isValid flag and optional error message.\n */\nfunction validateStrategyOrderParams(\n params: StrategyOrderValidationParams & {\n orderType?: OrderType;\n price?: string;\n triggerPrice?: string;\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n },\n): { isValid: boolean; error?: string } {\n const { orderType } = params;\n const strategy =\n orderType !== undefined && isStrategyOrderType(orderType)\n ? orderType\n : undefined;\n\n // Every strategy-only field must belong to the placement carrying it. This\n // also covers the non-strategy case, where no field has an owner to match.\n const foreignField = (\n Object.keys(STRATEGY_FIELD_OWNER) as (keyof StrategyOrderValidationParams)[]\n ).find(\n (field) =>\n params[field] !== undefined && STRATEGY_FIELD_OWNER[field] !== strategy,\n );\n if (foreignField) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_PARAMS_NOT_SUPPORTED,\n };\n }\n\n if (!strategy) {\n return { isValid: true };\n }\n\n // A strategy owns its own execution: it derives its own prices, rests its own\n // orders, and decides its own time in force. Accepting these fields would\n // mean quietly ignoring them.\n //\n // `clientOrderId` is refused for the same reason and cannot be honoured even\n // in principle: the venue's TWAP action carries no client id, a scale ladder\n // is many orders and a client id must be unique per order, and a chase\n // replaces its order on every re-price. One id cannot name any of them.\n if (\n params.price !== undefined ||\n params.triggerPrice !== undefined ||\n params.timeInForce !== undefined ||\n params.clientOrderId !== undefined ||\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined ||\n params.takeProfitSize !== undefined ||\n params.stopLossSize !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_STRATEGY_FIELD_UNSUPPORTED,\n };\n }\n\n if (strategy === 'twap') {\n return validateTwapParams(params);\n }\n if (strategy === 'scale') {\n return validateScaleParams(params);\n }\n return validateChaseParams(params);\n}\n\n/**\n * Validate order parameters.\n * Basic validation - checks required fields are present.\n * Amount validation (size/USD) is handled by validateOrder.\n *\n * @param params - Order parameters to validate\n * @param params.coin - The trading pair coin symbol\n * @param params.size - The order size as string\n * @param params.price - The order price as string\n * @param params.orderType - The order placement type\n * @param params.triggerPrice - Trigger price; required for trigger placement types and\n * rejected for market/limit orders so a stray value can never be silently dropped\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @param params.tpslLinkage - How an attached TP/SL is linked\n * @param params.grouping - Deprecated protocol-shaped spelling of `tpslLinkage`\n * @param params.timeInForce - Time in force; only a plain limit order can carry one\n * @param params.clientOrderId - Client-provided order ID; a strategy placement cannot carry one\n * @param params.twapDuration - TWAP window in whole minutes\n * @param params.twapRandomize - Whether to randomize the TWAP slice timing\n * @param params.scaleMinPrice - Lowest price in a scale ladder\n * @param params.scaleMaxPrice - Highest price in a scale ladder\n * @param params.scaleNumOrders - How many orders a scale ladder fans out into\n * @param params.chaseIntervalMs - How often a chase re-reads the touch\n * @param params.chaseMaxDurationMs - How long a chase keeps re-pricing\n * @param params.chaseMaxRepricings - Cap on a chase's cancel/replace cycles\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderParams(\n params: StrategyOrderValidationParams & {\n coin?: string;\n size?: string;\n price?: string;\n orderType?: OrderType;\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n tpslLinkage?: TpslLinkage;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n clientOrderId?: string;\n },\n): { isValid: boolean; error?: string } {\n if (!params.coin) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_COIN_REQUIRED,\n };\n }\n\n // Note: Size validation removed - validateOrder handles amount validation using USD as source of truth\n\n // Strategy placements are decided first: their shape trips the limit-price and\n // trigger rules below, and the strategy-shaped reason is the useful one.\n const strategyValidation = validateStrategyOrderParams(params);\n if (!strategyValidation.isValid) {\n return strategyValidation;\n }\n\n const { orderType } = params;\n const isTrigger = orderType !== undefined && isTriggerOrderType(orderType);\n\n // Require price for orders that execute as limit orders (limit, stop_limit,\n // take_profit_limit)\n if (\n orderType !== undefined &&\n isLimitExecutionOrderType(orderType) &&\n !params.price\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,\n };\n }\n\n if (params.price && parseFloat(params.price) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n };\n }\n\n if (isTrigger) {\n if (!params.triggerPrice) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED,\n };\n }\n\n const triggerPrice = parseFloat(params.triggerPrice);\n if (isNaN(triggerPrice) || triggerPrice <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n };\n }\n\n // A trigger placement combined with attached TP/SL children is rejected\n // rather than silently reshaped: the exchange semantics of a triggered\n // parent owning triggered children are not part of this contract.\n // Each field is checked explicitly: a falsy-but-present price (e.g. '') is\n // still an attached TP/SL request and must be rejected, not skipped.\n if (\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_TPSL_UNSUPPORTED,\n };\n }\n // Consistent with the attached-TP/SL check above: a falsy-but-present value\n // (e.g. '') is still a request to place a trigger, not an absent field.\n } else if (params.triggerPrice !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_NOT_SUPPORTED,\n };\n }\n\n // `tpslLinkage` supersedes `grouping`, but two spellings that disagree are a\n // caller mistake — resolving one silently would hide it.\n if (params.tpslLinkage !== undefined && params.grouping !== undefined) {\n const expectedGrouping = TPSL_LINKAGE_GROUPING[params.tpslLinkage];\n if (expectedGrouping !== params.grouping) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_CONFLICT,\n };\n }\n }\n\n const hasAttachedTpsl =\n params.takeProfitPrice !== undefined || params.stopLossPrice !== undefined;\n\n // Every order in a `positionTpsl` batch has to be a trigger order, and no\n // shape of order placement produces one. With an attached TP/SL the batch\n // carries the ordinary parent order the TP/SL protects; without one it is\n // that parent order alone. HyperLiquid rejects both, so the linkage is\n // refused outright — it belongs to `updatePositionTPSL`, applied to the\n // position once the parent has filled.\n const requestsPositionLinkage =\n params.tpslLinkage === 'position' || params.grouping === 'positionTpsl';\n if (requestsPositionLinkage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_POSITION_LINKAGE_UNSUPPORTED,\n };\n }\n\n // `na` grouping submits the attached TP/SL as standalone triggers, bound to\n // neither the parent order nor the resulting position. An unfilled parent\n // then leaves them behind as orphan reduce-only triggers that fire against\n // whatever position happens to exist. An attached TP/SL needs a linkage that\n // links it, so the combination is a caller mistake rather than a mode.\n const requestsNoLinkage =\n params.tpslLinkage === 'none' || params.grouping === 'na';\n if (requestsNoLinkage && hasAttachedTpsl) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_REQUIRED,\n };\n }\n\n // Only a plain limit order rests on the book long enough for a time in force to\n // mean anything: a market order fills immediately and a trigger order's\n // execution is decided when it fires. Rejected here, at step 1 of placement, so\n // it cannot fire after leverage changes or a HIP-3 margin transfer.\n if (params.timeInForce !== undefined && orderType !== 'limit') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED,\n };\n }\n\n const partialTpslValidation = validatePartialTpslSizes(params);\n if (!partialTpslValidation.isValid) {\n return partialTpslValidation;\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate quantity-scoped (partial) TP/SL sizes against the parent order.\n *\n * @param params - Order parameters carrying the TP/SL prices and sizes\n * @param params.size - Parent order size\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @returns Validation result with isValid flag and optional error message\n */\nfunction validatePartialTpslSizes(params: {\n size?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n}): { isValid: boolean; error?: string } {\n const orderSize = params.size ? Math.abs(parseFloat(params.size)) : undefined;\n\n const entries: { size?: string; price?: string }[] = [\n { size: params.takeProfitSize, price: params.takeProfitPrice },\n { size: params.stopLossSize, price: params.stopLossPrice },\n ];\n\n for (const entry of entries) {\n if (entry.size === undefined) {\n continue;\n }\n\n // A size without its price would silently place nothing.\n if (!entry.price) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n const size = parseFloat(entry.size);\n if (isNaN(size) || size <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n if (orderSize !== undefined && !isNaN(orderSize) && size > orderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate coin exists in asset mapping.\n *\n * @param coin - The coin symbol to validate\n * @param coinToAssetId - Map of coin symbols to asset IDs\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateCoinExists(\n coin: string,\n coinToAssetId: Map<string, number>,\n): { isValid: boolean; error?: string } {\n if (!coinToAssetId.has(coin)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_UNKNOWN_COIN,\n };\n }\n\n return { isValid: true };\n}\n"]}
1
+ {"version":3,"file":"hyperLiquidValidation.mjs","sourceRoot":"","sources":["../../src/utils/hyperLiquidValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,wBAAwB;AAGpD,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,gBAAgB,EACjB,2CAA0C;AAC3C,OAAO,EAAE,wBAAwB,EAAE,qCAAoC;AACvE,OAAO,EAAE,iBAAiB,EAAE,+BAA8B;AAM1D,OAAO,EAAE,yBAAyB,EAAE,kBAAkB,EAAE,yBAAwB;AAShF;;GAEG;AAEH;;;;;;GAMG;AACH,MAAM,UAAU,iBAAiB,CAE/B,KAAc,EAAE,eAAuB;IACvC,OAAO;QACL,GAAG,eAAe;QAClB,OAAO,EAAE,KAAK;QACd,KAAK,EACH,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,iBAAiB,CAAC,aAAa;KAC3E,CAAC;AACJ,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,UAAU,wBAAwB,CACtC,MAIC,EACD,WAAmC;IAEnC,WAAW,EAAE,GAAG,CAAC,+CAA+C,EAAE;QAChE,MAAM;QACN,UAAU,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC;QACnC,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC;QACjC,cAAc,EAAE,OAAO,CAAC,MAAM,CAAC,WAAW,CAAC;KAC5C,CAAC,CAAC;IAEH,+BAA+B;IAC/B,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,WAAW,EAAE,GAAG,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L,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,iBAAiB,CAAC,uBAAuB;aACjD,CAAC;QACJ,CAAC;QAED,IAAI,SAAS,KAAK,SAAS,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,IAAI,GAAG,SAAS,EAAE,CAAC;YACrE,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE,iBAAiB,CAAC,uBAAuB;aACjD,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,kBAAkB,CAChC,IAAY,EACZ,aAAkC;IAElC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;QAC7B,OAAO;YACL,OAAO,EAAE,KAAK;YACd,KAAK,EAAE,iBAAiB,CAAC,kBAAkB;SAC5C,CAAC;IACJ,CAAC;IAED,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["import { isValidHexAddress } from '@metamask/utils';\nimport type { CaipAssetId, Hex } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_ASSET_CONFIGS,\n getSupportedAssets,\n TRADING_DEFAULTS,\n} from '../constants/hyperLiquidConfig.js';\nimport { HYPERLIQUID_ORDER_LIMITS } from '../constants/perpsConfig.js';\nimport { PERPS_ERROR_CODES } from '../perpsErrorCodes.js';\nimport type {\n GetSupportedPathsParams,\n PerpsDebugLogger,\n} from '../types/index.js';\nimport type { OrderType, TpslLinkage } from '../types/perps-types.js';\nimport { isLimitExecutionOrderType, isTriggerOrderType } from './orderTypes.js';\n\n/**\n * Optional debug logger for validation functions.\n * When provided, enables detailed logging for debugging.\n * When omitted, validation runs silently.\n */\nexport type ValidationDebugLogger = PerpsDebugLogger | undefined;\n\n/**\n * Validation utilities for HyperLiquid operations\n */\n\n/**\n * Create standardized error response.\n *\n * @param error - The error that occurred\n * @param defaultResponse - The default response object to use as template\n * @returns The error response with success=false and error message\n */\nexport function createErrorResult<\n TValue extends { success: boolean; error?: string },\n>(error: unknown, defaultResponse: TValue): TValue {\n return {\n ...defaultResponse,\n success: false,\n error:\n error instanceof Error ? error.message : PERPS_ERROR_CODES.UNKNOWN_ERROR,\n };\n}\n\n/**\n * Validate withdrawal parameters.\n *\n * @param params - Withdrawal parameters to validate\n * @param params.assetId - The CAIP asset ID to withdraw\n * @param params.amount - Amount to withdraw as string\n * @param params.destination - Optional destination hex address\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateWithdrawalParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n destination?: Hex;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateWithdrawalParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n hasDestination: Boolean(params.destination),\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateWithdrawalParams: Missing assetId', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateWithdrawalParams: Missing amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateWithdrawalParams: Invalid amount', {\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_AMOUNT_POSITIVE,\n };\n }\n\n // Validate destination address if provided\n if (params.destination && !isValidHexAddress(params.destination)) {\n debugLogger?.log('validateWithdrawalParams: Invalid destination address', {\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n destination: params.destination,\n isValidHex: isValidHexAddress(params.destination),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INVALID_DESTINATION,\n };\n }\n\n debugLogger?.log('validateWithdrawalParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n destination: params.destination ?? 'will use user wallet',\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate deposit parameters.\n *\n * @param params - Deposit parameters to validate\n * @param params.assetId - The CAIP asset ID to deposit\n * @param params.amount - Amount to deposit as string\n * @param params.isTestnet - Whether this is a testnet deposit\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateDepositParams(\n params: {\n assetId?: CaipAssetId;\n amount?: string;\n isTestnet?: boolean;\n },\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateDepositParams: Starting validation', {\n params,\n hasAssetId: Boolean(params.assetId),\n hasAmount: Boolean(params.amount),\n isTestnet: params.isTestnet,\n });\n\n // Validate required parameters\n if (!params.assetId) {\n debugLogger?.log('validateDepositParams: Missing assetId', {\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_ASSET_ID_REQUIRED,\n };\n }\n\n // Validate amount\n if (!params.amount) {\n debugLogger?.log('validateDepositParams: Missing amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n params,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_REQUIRED,\n };\n }\n\n const amount = parseFloat(params.amount);\n if (isNaN(amount) || amount <= 0) {\n debugLogger?.log('validateDepositParams: Invalid amount', {\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n amount: params.amount,\n parsedAmount: amount,\n isNaN: isNaN(amount),\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_AMOUNT_POSITIVE,\n };\n }\n\n // Check minimum deposit amount\n const minimumAmount = params.isTestnet\n ? TRADING_DEFAULTS.amount.testnet\n : TRADING_DEFAULTS.amount.mainnet;\n\n debugLogger?.log('validateDepositParams: Checking minimum amount', {\n amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n network: params.isTestnet ? 'testnet' : 'mainnet',\n });\n\n if (amount < minimumAmount) {\n debugLogger?.log('validateDepositParams: Below minimum deposit', {\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n amount,\n minimumAmount,\n difference: minimumAmount - amount,\n });\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.DEPOSIT_MINIMUM_AMOUNT,\n };\n }\n\n debugLogger?.log('validateDepositParams: All validations passed', {\n assetId: params.assetId,\n amount: params.amount,\n parsedAmount: amount,\n minimumAmount,\n isTestnet: params.isTestnet,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate asset support for withdrawals using AssetRoute arrays.\n *\n * @param assetId - The CAIP asset ID to validate\n * @param supportedRoutes - Array of supported asset routes\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateAssetSupport(\n assetId: CaipAssetId,\n supportedRoutes: { assetId: CaipAssetId }[],\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateAssetSupport: Checking asset support', {\n assetId,\n supportedRoutesCount: supportedRoutes.length,\n });\n\n const supportedAssetIds = supportedRoutes.map((route) => route.assetId);\n\n // Check if asset is supported\n const isSupported = supportedAssetIds.includes(assetId);\n\n if (!isSupported) {\n // Also check case-insensitive match for contract addresses\n const isSupportedCaseInsensitive = supportedAssetIds.some(\n (supportedId) => supportedId.toLowerCase() === assetId.toLowerCase(),\n );\n\n if (!isSupportedCaseInsensitive) {\n debugLogger?.log('validateAssetSupport: Asset not supported', {\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n assetId,\n supportedAssetIds,\n checkedCaseInsensitive: true,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_ASSET_NOT_SUPPORTED,\n };\n }\n\n debugLogger?.log(\n '⚠️ validateAssetSupport: Asset supported with case mismatch',\n {\n providedAssetId: assetId,\n matchedAssetId: supportedAssetIds.find(\n (id) => id.toLowerCase() === assetId.toLowerCase(),\n ),\n },\n );\n }\n\n debugLogger?.log('validateAssetSupport: Asset is supported', {\n assetId,\n });\n\n return { isValid: true };\n}\n\n/**\n * Validate balance against withdrawal amount.\n *\n * @param withdrawAmount - The amount to withdraw\n * @param withdrawableBalance - Max USD that can leave the venue right now\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateBalance(\n withdrawAmount: number,\n withdrawableBalance: number,\n debugLogger?: ValidationDebugLogger,\n): { isValid: boolean; error?: string } {\n debugLogger?.log('validateBalance: Checking balance sufficiency', {\n withdrawAmount,\n withdrawableBalance,\n difference: withdrawableBalance - withdrawAmount,\n });\n\n if (withdrawAmount > withdrawableBalance) {\n const shortfall = withdrawAmount - withdrawableBalance;\n\n debugLogger?.log('validateBalance: Insufficient balance', {\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n withdrawAmount,\n withdrawableBalance,\n shortfall,\n percentageOfAvailable: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.WITHDRAW_INSUFFICIENT_BALANCE,\n };\n }\n\n const remainingBalance = withdrawableBalance - withdrawAmount;\n debugLogger?.log('validateBalance: Balance is sufficient', {\n withdrawAmount,\n withdrawableBalance,\n remainingBalance,\n percentageUsed: `${((withdrawAmount / withdrawableBalance) * 100).toFixed(2)}%`,\n });\n\n return { isValid: true };\n}\n\n/**\n * Apply filters to asset paths with comprehensive logging.\n *\n * @param assets - Array of CAIP asset IDs to filter\n * @param params - Filter parameters including chainId, symbol, and assetId\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Filtered array of CAIP asset IDs\n */\nexport function applyPathFilters(\n assets: CaipAssetId[],\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n if (!params) {\n debugLogger?.log(\n 'HyperLiquid: applyPathFilters - no params, returning all assets',\n { assets },\n );\n return assets;\n }\n\n let filtered = assets;\n\n debugLogger?.log('HyperLiquid: applyPathFilters - starting filter', {\n initialAssets: assets,\n filterParams: params,\n });\n\n if (params.chainId) {\n const before = filtered;\n filtered = filtered.filter((asset) =>\n asset.startsWith(params.chainId as string),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - chainId filter', {\n chainId: params.chainId,\n before,\n after: filtered,\n });\n }\n\n // Note: `in` is the idiomatic TypeScript way to narrow a string to\n // `keyof typeof` for indexed access; `hasProperty` types the indexed\n // result as `unknown` and loses the `{ testnet, mainnet }` shape.\n /* eslint-disable-next-line no-restricted-syntax */\n if (params.symbol && params.symbol in HYPERLIQUID_ASSET_CONFIGS) {\n const config =\n HYPERLIQUID_ASSET_CONFIGS[\n params.symbol as keyof typeof HYPERLIQUID_ASSET_CONFIGS\n ];\n const isTestnet = params.isTestnet ?? false;\n const selectedAsset = isTestnet ? config.testnet : config.mainnet;\n const before = filtered;\n filtered = [selectedAsset];\n debugLogger?.log('HyperLiquid: applyPathFilters - symbol filter', {\n symbol: params.symbol,\n isTestnet,\n config,\n selectedAsset,\n before,\n after: filtered,\n });\n }\n\n if (params.assetId) {\n const before = filtered;\n // Use case-insensitive comparison for asset ID matching to handle address case differences\n filtered = filtered.filter(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n );\n debugLogger?.log('HyperLiquid: applyPathFilters - assetId filter', {\n assetId: params.assetId,\n before,\n after: filtered,\n exactMatch: before.includes(params.assetId),\n caseInsensitiveMatch: before.some(\n (asset) => asset.toLowerCase() === params.assetId?.toLowerCase(),\n ),\n });\n }\n\n debugLogger?.log('HyperLiquid: applyPathFilters - final result', {\n initialAssets: assets,\n finalFiltered: filtered,\n filterParams: params,\n });\n\n return filtered;\n}\n\n/**\n * Get supported deposit/withdrawal paths with filtering.\n *\n * @param params - Filter parameters including isTestnet, chainId, symbol\n * @param debugLogger - Optional debug logger for detailed logging\n * @returns Array of supported CAIP asset IDs\n */\nexport function getSupportedPaths(\n params?: GetSupportedPathsParams,\n debugLogger?: ValidationDebugLogger,\n): CaipAssetId[] {\n const isTestnet = params?.isTestnet ?? false;\n const assets = getSupportedAssets(isTestnet);\n const filteredAssets = applyPathFilters(assets, params, debugLogger);\n\n debugLogger?.log('HyperLiquid: getSupportedPaths', {\n isTestnet,\n requestedParams: params,\n allAssets: assets,\n filteredAssets,\n returnType: 'CaipAssetId[]',\n example: filteredAssets[0],\n });\n\n return filteredAssets;\n}\n\n/**\n * Get maximum order value based on leverage and order type.\n * Based on HyperLiquid contract specifications.\n *\n * @param maxLeverage - The maximum leverage for the market\n * @param orderType - The order type; trigger types follow the limit/market\n * multiplier of their execution mode (e.g. `stop_limit` is treated as a limit order)\n * @returns Maximum order value in USD\n */\nexport function getMaxOrderValue(\n maxLeverage: number,\n orderType: OrderType,\n): number {\n let marketLimit: number;\n\n if (maxLeverage >= 25) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.HighLeverage;\n } else if (maxLeverage >= 20) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumHighLeverage;\n } else if (maxLeverage >= 10) {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.MediumLeverage;\n } else {\n marketLimit = HYPERLIQUID_ORDER_LIMITS.MarketOrderLimits.LowLeverage;\n }\n\n return isLimitExecutionOrderType(orderType)\n ? marketLimit * HYPERLIQUID_ORDER_LIMITS.LimitOrderMultiplier\n : marketLimit;\n}\n\n/**\n * The `grouping` value each provider-agnostic linkage corresponds to, used to\n * detect a caller supplying both spellings with different meanings.\n */\nconst TPSL_LINKAGE_GROUPING: Record<\n TpslLinkage,\n 'na' | 'normalTpsl' | 'positionTpsl'\n> = {\n none: 'na',\n order: 'normalTpsl',\n position: 'positionTpsl',\n};\n\n/**\n * Validate order parameters.\n * Basic validation - checks required fields are present.\n * Amount validation (size/USD) is handled by validateOrder.\n *\n * @param params - Order parameters to validate\n * @param params.coin - The trading pair coin symbol\n * @param params.size - The order size as string\n * @param params.price - The order price as string\n * @param params.orderType - The order placement type\n * @param params.triggerPrice - Trigger price; required for trigger placement types and\n * rejected for market/limit orders so a stray value can never be silently dropped\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @param params.tpslLinkage - How an attached TP/SL is linked\n * @param params.grouping - Deprecated protocol-shaped spelling of `tpslLinkage`\n * @param params.timeInForce - Time in force; only a plain limit order can carry one\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateOrderParams(params: {\n coin?: string;\n size?: string;\n price?: string;\n orderType?: OrderType;\n triggerPrice?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n tpslLinkage?: TpslLinkage;\n grouping?: 'na' | 'normalTpsl' | 'positionTpsl';\n timeInForce?: 'GTC' | 'IOC' | 'ALO';\n}): { isValid: boolean; error?: string } {\n if (!params.coin) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_COIN_REQUIRED,\n };\n }\n\n // Note: Size validation removed - validateOrder handles amount validation using USD as source of truth\n\n const { orderType } = params;\n const isTrigger = orderType !== undefined && isTriggerOrderType(orderType);\n\n // Require price for orders that execute as limit orders (limit, stop_limit,\n // take_profit_limit)\n if (\n orderType !== undefined &&\n isLimitExecutionOrderType(orderType) &&\n !params.price\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_LIMIT_PRICE_REQUIRED,\n };\n }\n\n if (params.price && parseFloat(params.price) <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_PRICE_POSITIVE,\n };\n }\n\n if (isTrigger) {\n if (!params.triggerPrice) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_REQUIRED,\n };\n }\n\n const triggerPrice = parseFloat(params.triggerPrice);\n if (isNaN(triggerPrice) || triggerPrice <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_POSITIVE,\n };\n }\n\n // A trigger placement combined with attached TP/SL children is rejected\n // rather than silently reshaped: the exchange semantics of a triggered\n // parent owning triggered children are not part of this contract.\n // Each field is checked explicitly: a falsy-but-present price (e.g. '') is\n // still an attached TP/SL request and must be rejected, not skipped.\n if (\n params.takeProfitPrice !== undefined ||\n params.stopLossPrice !== undefined\n ) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_TPSL_UNSUPPORTED,\n };\n }\n // Consistent with the attached-TP/SL check above: a falsy-but-present value\n // (e.g. '') is still a request to place a trigger, not an absent field.\n } else if (params.triggerPrice !== undefined) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TRIGGER_PRICE_NOT_SUPPORTED,\n };\n }\n\n // `tpslLinkage` supersedes `grouping`, but two spellings that disagree are a\n // caller mistake — resolving one silently would hide it.\n if (params.tpslLinkage !== undefined && params.grouping !== undefined) {\n const expectedGrouping = TPSL_LINKAGE_GROUPING[params.tpslLinkage];\n if (expectedGrouping !== params.grouping) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_CONFLICT,\n };\n }\n }\n\n const hasAttachedTpsl =\n params.takeProfitPrice !== undefined || params.stopLossPrice !== undefined;\n\n // Every order in a `positionTpsl` batch has to be a trigger order, and no\n // shape of order placement produces one. With an attached TP/SL the batch\n // carries the ordinary parent order the TP/SL protects; without one it is\n // that parent order alone. HyperLiquid rejects both, so the linkage is\n // refused outright — it belongs to `updatePositionTPSL`, applied to the\n // position once the parent has filled.\n const requestsPositionLinkage =\n params.tpslLinkage === 'position' || params.grouping === 'positionTpsl';\n if (requestsPositionLinkage) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_POSITION_LINKAGE_UNSUPPORTED,\n };\n }\n\n // `na` grouping submits the attached TP/SL as standalone triggers, bound to\n // neither the parent order nor the resulting position. An unfilled parent\n // then leaves them behind as orphan reduce-only triggers that fire against\n // whatever position happens to exist. An attached TP/SL needs a linkage that\n // links it, so the combination is a caller mistake rather than a mode.\n const requestsNoLinkage =\n params.tpslLinkage === 'none' || params.grouping === 'na';\n if (requestsNoLinkage && hasAttachedTpsl) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_LINKAGE_REQUIRED,\n };\n }\n\n // Only a plain limit order rests on the book long enough for a time in force to\n // mean anything: a market order fills immediately and a trigger order's\n // execution is decided when it fires. Rejected here, at step 1 of placement, so\n // it cannot fire after leverage changes or a HIP-3 margin transfer.\n if (params.timeInForce !== undefined && orderType !== 'limit') {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TIME_IN_FORCE_NOT_SUPPORTED,\n };\n }\n\n const partialTpslValidation = validatePartialTpslSizes(params);\n if (!partialTpslValidation.isValid) {\n return partialTpslValidation;\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate quantity-scoped (partial) TP/SL sizes against the parent order.\n *\n * @param params - Order parameters carrying the TP/SL prices and sizes\n * @param params.size - Parent order size\n * @param params.takeProfitPrice - Attached take profit price\n * @param params.stopLossPrice - Attached stop loss price\n * @param params.takeProfitSize - Partial take profit size\n * @param params.stopLossSize - Partial stop loss size\n * @returns Validation result with isValid flag and optional error message\n */\nfunction validatePartialTpslSizes(params: {\n size?: string;\n takeProfitPrice?: string;\n stopLossPrice?: string;\n takeProfitSize?: string;\n stopLossSize?: string;\n}): { isValid: boolean; error?: string } {\n const orderSize = params.size ? Math.abs(parseFloat(params.size)) : undefined;\n\n const entries: { size?: string; price?: string }[] = [\n { size: params.takeProfitSize, price: params.takeProfitPrice },\n { size: params.stopLossSize, price: params.stopLossPrice },\n ];\n\n for (const entry of entries) {\n if (entry.size === undefined) {\n continue;\n }\n\n // A size without its price would silently place nothing.\n if (!entry.price) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n const size = parseFloat(entry.size);\n if (isNaN(size) || size <= 0) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n\n if (orderSize !== undefined && !isNaN(orderSize) && size > orderSize) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_TPSL_SIZE_INVALID,\n };\n }\n }\n\n return { isValid: true };\n}\n\n/**\n * Validate coin exists in asset mapping.\n *\n * @param coin - The coin symbol to validate\n * @param coinToAssetId - Map of coin symbols to asset IDs\n * @returns Validation result with isValid flag and optional error message\n */\nexport function validateCoinExists(\n coin: string,\n coinToAssetId: Map<string, number>,\n): { isValid: boolean; error?: string } {\n if (!coinToAssetId.has(coin)) {\n return {\n isValid: false,\n error: PERPS_ERROR_CODES.ORDER_UNKNOWN_COIN,\n };\n }\n\n return { isValid: true };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.buildOrdersArray = exports.formatPartialTpslSize = exports.validateOrderPrecision = exports.calculateOrderPriceAndSize = exports.calculateFinalPositionSize = exports.splitScaleSizes = exports.computeScalePriceLadder = exports.computeChaseQuotePrice = exports.getPriceTick = exports.floorToSizeDecimals = exports.getMaxAllowedAmount = exports.calculateMarginRequired = exports.calculatePositionSize = void 0;
3
+ exports.buildOrdersArray = exports.formatPartialTpslSize = exports.validateOrderPrecision = exports.calculateOrderPriceAndSize = exports.calculateFinalPositionSize = exports.floorToSizeDecimals = exports.getMaxAllowedAmount = exports.calculateMarginRequired = exports.calculatePositionSize = void 0;
4
4
  const hyperLiquidConfig_js_1 = require("../constants/hyperLiquidConfig.cjs");
5
5
  const perpsConfig_js_1 = require("../constants/perpsConfig.cjs");
6
6
  const perpsErrorCodes_js_1 = require("../perpsErrorCodes.cjs");
@@ -154,136 +154,6 @@ function floorToSizeDecimals(size, szDecimals) {
154
154
  return units / multiplier;
155
155
  }
156
156
  exports.floorToSizeDecimals = floorToSizeDecimals;
157
- /**
158
- * The smallest price increment the venue will represent at a given price.
159
- *
160
- * HyperLiquid bounds a perp price two ways at once — a decimal-place cap that
161
- * depends on the asset's size precision, and a significant-figure cap — so the
162
- * tick widens as the price grows. Whichever bound is coarser at this price is
163
- * the tick.
164
- *
165
- * @param params - Tick parameters.
166
- * @param params.price - Price to measure the increment at.
167
- * @param params.szDecimals - The asset's size decimal precision.
168
- * @returns The tick size at that price.
169
- */
170
- function getPriceTick(params) {
171
- const { price, szDecimals } = params;
172
- const byDecimals = Math.pow(10, -(perpsConfig_js_1.DECIMAL_PRECISION_CONFIG.MaxPriceDecimals - szDecimals));
173
- const bySignificantFigures = Math.pow(10, Math.floor(Math.log10(Math.abs(price))) -
174
- (perpsConfig_js_1.DECIMAL_PRECISION_CONFIG.MaxSignificantFigures - 1));
175
- return Math.max(byDecimals, bySignificantFigures);
176
- }
177
- exports.getPriceTick = getPriceTick;
178
- /**
179
- * Price a chase order against the book it is chasing.
180
- *
181
- * The venue's own definition: a chase rests one tick *inside* the spread —
182
- * above the best bid for a buy, below the best ask for a sell — except when the
183
- * spread is already a single tick, where there is no room to improve and the
184
- * order joins the touch instead.
185
- *
186
- * Rests inside rather than at the touch because a chase is post-only: sitting
187
- * one tick ahead of the rest of the queue is the whole point, and joining the
188
- * touch would leave it behind every order already resting there.
189
- *
190
- * @param params - Quote parameters.
191
- * @param params.bestBid - Best bid, excluding the chase's own resting order.
192
- * @param params.bestAsk - Best ask, excluding the chase's own resting order.
193
- * @param params.isBuy - Which side the chase rests on.
194
- * @param params.szDecimals - The asset's size decimal precision.
195
- * @returns The formatted price the chase should rest at.
196
- */
197
- function computeChaseQuotePrice(params) {
198
- const { bestBid, bestAsk, isBuy, szDecimals } = params;
199
- const reference = isBuy ? bestBid : bestAsk;
200
- const tick = getPriceTick({ price: reference, szDecimals });
201
- const improved = isBuy ? bestBid + tick : bestAsk - tick;
202
- // A single-tick spread leaves nowhere to improve to: the improved price would
203
- // cross, which a post-only order cannot do. Join the touch instead.
204
- const crosses = isBuy ? improved >= bestAsk : improved <= bestBid;
205
- return (0, hyperLiquidAdapter_js_1.formatHyperLiquidPrice)({
206
- price: crosses ? reference : improved,
207
- szDecimals,
208
- });
209
- }
210
- exports.computeChaseQuotePrice = computeChaseQuotePrice;
211
- /**
212
- * Compute the price ladder a scale placement fans out over.
213
- *
214
- * The ladder is inclusive of both ends — the first rung sits exactly on
215
- * `minPrice`, the last exactly on `maxPrice` — so the range the caller asked
216
- * for is the range that actually reaches the exchange.
217
- *
218
- * @param params - Ladder parameters.
219
- * @param params.minPrice - Lowest price in the ladder.
220
- * @param params.maxPrice - Highest price in the ladder; must exceed `minPrice`.
221
- * @param params.count - Number of rungs.
222
- * @returns The rung prices, ascending.
223
- */
224
- function computeScalePriceLadder(params) {
225
- const { minPrice, maxPrice, count } = params;
226
- if (!Number.isInteger(count) ||
227
- count < orderTypes_js_1.SCALE_ORDER_COUNT.min ||
228
- count > orderTypes_js_1.SCALE_ORDER_COUNT.max) {
229
- throw new Error(perpsErrorCodes_js_1.PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);
230
- }
231
- if (!Number.isFinite(minPrice) ||
232
- !Number.isFinite(maxPrice) ||
233
- minPrice <= 0 ||
234
- maxPrice <= minPrice) {
235
- throw new Error(perpsErrorCodes_js_1.PERPS_ERROR_CODES.ORDER_SCALE_RANGE_INVALID);
236
- }
237
- const step = (maxPrice - minPrice) / (count - 1);
238
- // The top rung is assigned rather than accumulated: `minPrice + step * n`
239
- // drifts, and a ladder that stops short of the caller's maxPrice would quietly
240
- // narrow the range they asked for.
241
- return Array.from({ length: count }, (_unused, index) => index === count - 1 ? maxPrice : minPrice + step * index);
242
- }
243
- exports.computeScalePriceLadder = computeScalePriceLadder;
244
- /**
245
- * Split a scale placement's total size across its ladder rungs.
246
- *
247
- * The split is done in whole units of the asset's size grid rather than in
248
- * decimal sizes: dividing and re-flooring in floating point loses a sub-unit of
249
- * dust on every rung, and a ladder that submits less than the size that was
250
- * validated is not the order the caller placed. Whatever does not divide evenly
251
- * goes onto the first rung, so the slices sum to exactly `totalSize`.
252
- *
253
- * The total is expected to sit on the grid already — `calculateFinalPositionSize`
254
- * floors it there — so rounding onto the grid here only absorbs representation
255
- * error. A total too small to give every rung a whole unit is rejected: placing
256
- * fewer orders than asked for would silently change the strategy.
257
- *
258
- * @param params - Split parameters.
259
- * @param params.totalSize - Total size to distribute.
260
- * @param params.count - Number of rungs.
261
- * @param params.szDecimals - The asset's size decimal precision.
262
- * @returns One size string per rung, in ladder order.
263
- */
264
- function splitScaleSizes(params) {
265
- const { totalSize, count, szDecimals } = params;
266
- // Checked here as well as in `computeScalePriceLadder`: this is exported on
267
- // its own, and a count of zero would otherwise return an empty split while a
268
- // fractional one would return slices that do not sum to the total.
269
- if (!Number.isInteger(count) ||
270
- count < orderTypes_js_1.SCALE_ORDER_COUNT.min ||
271
- count > orderTypes_js_1.SCALE_ORDER_COUNT.max) {
272
- throw new Error(perpsErrorCodes_js_1.PERPS_ERROR_CODES.ORDER_SCALE_COUNT_INVALID);
273
- }
274
- const multiplier = Math.pow(10, szDecimals);
275
- const totalUnits = Math.round(totalSize * multiplier);
276
- if (!Number.isSafeInteger(totalUnits) || totalUnits < count) {
277
- throw new Error(perpsErrorCodes_js_1.PERPS_ERROR_CODES.ORDER_SCALE_SIZE_TOO_SMALL);
278
- }
279
- const sliceUnits = Math.floor(totalUnits / count);
280
- const remainderUnits = totalUnits - sliceUnits * count;
281
- return Array.from({ length: count }, (_unused, index) => (0, hyperLiquidAdapter_js_1.formatHyperLiquidSize)({
282
- size: (index === 0 ? sliceUnits + remainderUnits : sliceUnits) / multiplier,
283
- szDecimals,
284
- }));
285
- }
286
- exports.splitScaleSizes = splitScaleSizes;
287
157
  /**
288
158
  * Calculates final position size using USD as source of truth with price validation
289
159
  *