@metamask-previews/perps-controller 24.1.0-preview-e9ac9ffe1 → 24.1.0-preview-70269bbdb

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 (88) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/PerpsController-method-action-types.d.ts +26 -1
  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 +20 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +159 -2
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/eventNames.d.ts +0 -6
  10. package/dist/constants/eventNames.d.ts.map +1 -1
  11. package/dist/constants/eventNames.js +0 -13
  12. package/dist/constants/eventNames.js.map +1 -1
  13. package/dist/constants/hyperLiquidConfig.d.ts +19 -3
  14. package/dist/constants/hyperLiquidConfig.d.ts.map +1 -1
  15. package/dist/constants/hyperLiquidConfig.js +21 -5
  16. package/dist/constants/hyperLiquidConfig.js.map +1 -1
  17. package/dist/constants/performanceMetrics.d.ts +2 -14
  18. package/dist/constants/performanceMetrics.d.ts.map +1 -1
  19. package/dist/constants/performanceMetrics.js +1 -17
  20. package/dist/constants/performanceMetrics.js.map +1 -1
  21. package/dist/constants/perpsConfig.d.ts +27 -0
  22. package/dist/constants/perpsConfig.d.ts.map +1 -1
  23. package/dist/constants/perpsConfig.js +27 -0
  24. package/dist/constants/perpsConfig.js.map +1 -1
  25. package/dist/index.d.ts +7 -5
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +4 -2
  28. package/dist/index.js.map +1 -1
  29. package/dist/perpsErrorCodes.d.ts +2 -0
  30. package/dist/perpsErrorCodes.d.ts.map +1 -1
  31. package/dist/perpsErrorCodes.js +2 -0
  32. package/dist/perpsErrorCodes.js.map +1 -1
  33. package/dist/providers/HyperLiquidProvider.d.ts +7 -3
  34. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  35. package/dist/providers/HyperLiquidProvider.js +161 -103
  36. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  37. package/dist/providers/LighterProvider.d.ts +3 -3
  38. package/dist/providers/LighterProvider.d.ts.map +1 -1
  39. package/dist/providers/LighterProvider.js +20 -9
  40. package/dist/providers/LighterProvider.js.map +1 -1
  41. package/dist/services/TerminalMarketService.d.ts.map +1 -1
  42. package/dist/services/TerminalMarketService.js +4 -2
  43. package/dist/services/TerminalMarketService.js.map +1 -1
  44. package/dist/services/TradingService.js +11 -9
  45. package/dist/services/TradingService.js.map +1 -1
  46. package/dist/types/index.d.ts +107 -2
  47. package/dist/types/index.d.ts.map +1 -1
  48. package/dist/types/index.js +0 -1
  49. package/dist/types/index.js.map +1 -1
  50. package/dist/utils/advancedOrderLists.d.ts +104 -0
  51. package/dist/utils/advancedOrderLists.d.ts.map +1 -0
  52. package/dist/utils/advancedOrderLists.js +421 -0
  53. package/dist/utils/advancedOrderLists.js.map +1 -0
  54. package/dist/utils/advancedOrders.d.ts +275 -0
  55. package/dist/utils/advancedOrders.d.ts.map +1 -0
  56. package/dist/utils/advancedOrders.js +639 -0
  57. package/dist/utils/advancedOrders.js.map +1 -0
  58. package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
  59. package/dist/utils/hyperLiquidAdapter.js +4 -1
  60. package/dist/utils/hyperLiquidAdapter.js.map +1 -1
  61. package/dist/utils/hyperLiquidValidation.d.ts.map +1 -1
  62. package/dist/utils/hyperLiquidValidation.js +22 -57
  63. package/dist/utils/hyperLiquidValidation.js.map +1 -1
  64. package/dist/utils/index.d.ts +2 -0
  65. package/dist/utils/index.d.ts.map +1 -1
  66. package/dist/utils/index.js +2 -0
  67. package/dist/utils/index.js.map +1 -1
  68. package/dist/utils/lighterScaleOrders.d.ts.map +1 -1
  69. package/dist/utils/lighterScaleOrders.js +16 -65
  70. package/dist/utils/lighterScaleOrders.js.map +1 -1
  71. package/dist/utils/perpsFormatters.d.ts +29 -4
  72. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  73. package/dist/utils/perpsFormatters.js +51 -5
  74. package/dist/utils/perpsFormatters.js.map +1 -1
  75. package/docs/README.md +28 -0
  76. package/docs/architecture.md +256 -0
  77. package/docs/contracts/events.md +267 -0
  78. package/docs/contracts/feature-flags.md +39 -0
  79. package/docs/contracts/traces.md +83 -0
  80. package/docs/formatting.md +82 -0
  81. package/docs/tpsl.md +89 -0
  82. package/docs/venues/hyperliquid/README.md +27 -0
  83. package/docs/venues/hyperliquid/init-flow.md +116 -0
  84. package/docs/venues/hyperliquid/order-types.md +60 -0
  85. package/docs/venues/hyperliquid/trading-rules.md +77 -0
  86. package/docs/venues/lighter/api-keys.md +58 -0
  87. package/docs/venues/lighter/capabilities.md +74 -0
  88. package/package.json +4 -3
@@ -0,0 +1,82 @@
1
+ # Perps display formatting
2
+
3
+ The display formatters and price ranges are exported from `@metamask/perps-controller`.
4
+
5
+ ## General rules
6
+
7
+ - Display prices show at most 6 decimals (`DECIMAL_PRECISION_CONFIG.MaxPriceDecimals`, the HyperLiquid limit). Two paths differ. A calculated TP/SL trigger price keeps 8 decimals below $0.01 (`TP_SL_PRECISION_CONFIG`), and an order price sent to HyperLiquid keeps at most 6 − `szDecimals` (see [venues/hyperliquid/trading-rules.md](./venues/hyperliquid/trading-rules.md)).
8
+ - Range conditions use |v|.
9
+ - `formatPerpsFiat` strips trailing zeros unless the caller passes `stripTrailingZeros: false`. With `PRICE_RANGES_UNIVERSAL` it strips every trailing zero. With `PRICE_RANGES_MINIMAL_VIEW`, the default, it strips only an all-zero `.00`.
10
+ - With `PRICE_RANGES_UNIVERSAL` only, significant digits are 6 above $100,000, 5 from $0.01 to $100,000 and 4 below $0.01.
11
+
12
+ Code: `src/constants/perpsConfig.ts` `DECIMAL_PRECISION_CONFIG`, `TP_SL_PRECISION_CONFIG`; `src/utils/perpsFormatters.ts` `formatPerpsFiat`, `formatWithSignificantDigits`.
13
+
14
+ ## `PRICE_RANGES_UNIVERSAL`
15
+
16
+ Callers opt in by passing `{ ranges: PRICE_RANGES_UNIVERSAL }` to `formatPerpsFiat`. `formatPerpsOrderBookPrice` with no ladder format and `formatPerpsCompact` for order-book USD below 1,000 use it. The first matching row wins.
17
+
18
+ | \|v\| | Sig digits | Decimals (min, max) | Threshold | Examples |
19
+ | --------- | ---------- | ------------------- | --------------------------------------- | ---------------------------------------- |
20
+ | > 100,000 | 6 | 0, 0 | 100,000 | 123456.78 → $123,457 |
21
+ | > 10,000 | 5 | 0, 0 | 10,000 | 12345.67 → $12,346 |
22
+ | > 1,000 | 5 | 0, 1 | 1,000 | 1234.56 → $1,234.6 |
23
+ | > 100 | 5 | 0, 2 | 100 | 123.456 → $123.46 |
24
+ | > 10 | 5 | 0, 4 | 10 | 12.34567 → $12.346 |
25
+ | ≥ 0.01 | 5 | 2, 6 | 0.01 | 1.3445555 → $1.3446, 0.333333 → $0.33333 |
26
+ | < 0.01 | 4 | 2, 6 | 0.000001 (`PRICE_THRESHOLD.VERY_SMALL`) | 0.004236 → $0.004236 |
27
+
28
+ - Stripping runs after significant-digit rounding, so the minimum of 2 decimals does not hold: 1.5 → $1.5.
29
+ - A non-zero value below its row's threshold renders `<` plus the threshold at the decimals the rounding chose. 0.0000006 and 0.0000004 both render `<$0`.
30
+
31
+ Code: `src/utils/perpsFormatters.ts` `PRICE_RANGES_UNIVERSAL`, `PRICE_THRESHOLD`, `FiatRangeConfig`.
32
+
33
+ ## `PRICE_RANGES_MINIMAL_VIEW`
34
+
35
+ The default `ranges`. Every value gets exactly 2 decimals, and an all-zero `.00` is dropped.
36
+
37
+ | Input | Output |
38
+ | ------ | --------- |
39
+ | 1250 | $1,250 |
40
+ | 1250.1 | $1,250.10 |
41
+ | 13.4 | $13.40 |
42
+ | 0.004 | <$0.01 |
43
+ | -0.004 | -<$0.01 |
44
+
45
+ Code: `src/utils/perpsFormatters.ts` `PRICE_RANGES_MINIMAL_VIEW`.
46
+
47
+ ## Missing value or real zero
48
+
49
+ `undefined`, `null`, an empty or non-numeric string, `NaN` and an infinite value count as missing and render a placeholder from `PERPS_CONSTANTS`. A real `0` renders as a number, so the two never look alike.
50
+
51
+ | Formatter | Missing | Zero |
52
+ | ----------------------------------------------- | ------------------------------------------- | ------------------ |
53
+ | `formatPerpsFiat` | `$---` (`--` with `symbol: false`) | `$0` |
54
+ | `formatPnl` | `$---` | `+$0.00` |
55
+ | `formatPositionSize` | `--` | `0` |
56
+ | `formatPercentage` | `--%` | `+0.00%` |
57
+ | `formatFundingRate` | `--%` (empty string with `showZero: false`) | `0.0000%` |
58
+ | `formatFeeBps` | `--` | `0 bps` |
59
+ | `formatLiquidationDistance` | `--%` | |
60
+ | `formatCrossMarginRatio` | `--%` | `0%` |
61
+ | `formatPerpsCompact` | `$---` (`--` for `orderBookSize`) | `$0.00` (`volume`) |
62
+ | `formatPerpsOrderBookPrice` | `$---` (`--` with `symbol: false`) | |
63
+ | `formatPositionFunding`, `formatFundingPayment` | `$---` | |
64
+ | `formatPerpsDuration` | `--` | `0 sec` |
65
+
66
+ A value that rounds to zero at the shown precision counts as zero for the sign, so no sign mode shows `-0.00`.
67
+
68
+ Code: `src/utils/perpsFormatters.ts` `_parseDisplayNumber`, `_signPrefix`, `PerpsSignDisplay`; `src/constants/perpsConfig.ts` `PERPS_CONSTANTS.FallbackPriceDisplay`, `FallbackPercentageDisplay`, `FallbackDataDisplay`.
69
+
70
+ ## Fixed decimals and locale
71
+
72
+ - Non-price values take `decimals` from `PERPS_DISPLAY_PRECISION`, for example `Pnl` 2, `RoePercent` 1, `FundingRatePercent` 4, `CrossMarginRatioPercent` 1.
73
+ - `formatCrossMarginRatio` takes a ratio (`0.174` renders `17.4%`) and renders it with the locale's percent style; `decimals` is the most decimals shown, and trailing zeros are dropped (`0.63` renders `63%`), so the `%` placement follows the locale. `formatPercentage`, `formatFundingRate` and `formatLiquidationDistance` append a bare `%` to a fixed-decimal number.
74
+ - Locale separators come from the `formatters` option, built by the client with `createFormatters({ locale })` from `@metamask/client-utils`. Without it the formatters use `en-US`.
75
+
76
+ Code: `src/constants/perpsConfig.ts` `PERPS_DISPLAY_PRECISION`; `src/utils/perpsFormatters.ts` `PerpsIntlFormatters`, `PerpsDisplayFormatOptions`.
77
+
78
+ ## Durations
79
+
80
+ `formatPerpsDuration(durationMs, { formatters?, unitDisplay? })` renders TWAP running and elapsed time, slice intervals and chase windows. It rounds to whole seconds and shows each non-zero day, hour, minute and second in the locale's `Intl.NumberFormat` unit style, `short` by default: 90 minutes renders `1 hr 30 min`, and `unitDisplay: 'long'` renders 5 minutes as `5 minutes`.
81
+
82
+ Code: `src/utils/perpsFormatters.ts` `formatPerpsDuration`, `PerpsDurationFormatOptions`.
package/docs/tpsl.md ADDED
@@ -0,0 +1,89 @@
1
+ # TP/SL linkage
2
+
3
+ There are two mechanisms for putting a take-profit or stop-loss on a position. They are not interchangeable. They size differently and fail differently.
4
+
5
+ | | Order-linked | Position-linked |
6
+ | ----------------------------- | ---------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
7
+ | HyperLiquid grouping | `normalTpsl` | `positionTpsl`; `na` when a partial size is given |
8
+ | Controller entry point | `placeOrder` with `takeProfitPrice` / `stopLossPrice` in `OrderParams` | `updatePositionTPSL` |
9
+ | Submitted | in the same exchange batch as the parent order | as a separate request, after a position exists |
10
+ | Size sent | the parent order size, frozen at submission; a partial size is clamped to it | `'0'` (the whole position) when `TP_SL_CONFIG.UsePositionBoundTpsl` is on and no partial size is given; otherwise an explicit size floored to the size grid |
11
+ | Requires an existing position | no | yes |
12
+ | Races the position stream | no | yes |
13
+
14
+ How the venue resizes or rejects triggers after a scale-in or a partial fill is HyperLiquid behaviour; the controller does not encode it.
15
+
16
+ Code: `src/utils/orderCalculations.ts` `buildOrdersArray`; `src/providers/HyperLiquidProvider.ts` `placeOrder`, `updatePositionTPSL`, `#replacePositionTpsl`.
17
+
18
+ ## Order-linked (`placeOrder`)
19
+
20
+ - Linkage comes from `OrderParams.tpslLinkage` (`order`, `position`, `none`), mapped by `adaptTpslLinkageToGrouping`. It wins over the deprecated `grouping`.
21
+ - With neither set, `buildOrdersArray` applies the default `grouping ?? ((takeProfitPrice ?? stopLossPrice) ? 'normalTpsl' : 'na')`. Omitting the field selects order-linked placement.
22
+ - Children are reduce-only (`r: true`) on the opposite side.
23
+ - The TP child is a limit trigger (`isMarket: false`) with `p` = TP price.
24
+ - The SL child is a market trigger (`isMarket: true`) with `p` = SL price moved 10% against the close (`ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps`, 1000 bps).
25
+ - `formatTpslSize` returns the parent's `formattedSize` for a whole-order TP/SL. A partial `takeProfitSize` / `stopLossSize` is clamped to the parent and floored to `szDecimals`.
26
+
27
+ | Error | When |
28
+ | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
+ | `ORDER_TPSL_POSITION_LINKAGE_UNSUPPORTED` | `tpslLinkage: 'position'` or `grouping: 'positionTpsl'` on `placeOrder`, with or without a TP/SL. HyperLiquid requires every order in a `positionTpsl` batch to be a trigger, and the parent is not. |
30
+ | `ORDER_TPSL_LINKAGE_REQUIRED` | `tpslLinkage: 'none'` or `grouping: 'na'` with a TP/SL. It would leave orphan reduce-only triggers if the parent never fills. |
31
+ | `ORDER_TPSL_LINKAGE_CONFLICT` | `tpslLinkage` and `grouping` both set and disagree |
32
+ | `ORDER_TPSL_SIZE_INVALID` | Partial size without its price, not positive, larger than the order, or zero after flooring |
33
+
34
+ Code: `src/utils/hyperLiquidAdapter.ts` `adaptTpslLinkageToGrouping`; `src/utils/orderCalculations.ts` `buildOrdersArray`, `formatTpslSize`, `formatPartialTpslSize`; `src/utils/hyperLiquidValidation.ts` `validateOrderParams`; `src/types/index.ts` `OrderParams.tpslLinkage`, `OrderParams.grouping`.
35
+
36
+ ## Position-linked (`updatePositionTPSL`)
37
+
38
+ ### Lookup
39
+
40
+ `updatePositionTPSL` and `replacePositionTPSLLeg` share `#replacePositionTpsl`, which reads the position through `#getPositionsForOperation(dex, { revalidateMissingSymbol: symbol })`. Errors below come back as an `OrderResult` with `success: false` and the code in `error`; the methods do not throw them.
41
+
42
+ | Current DEX slice | Result |
43
+ | -------------------------------------------- | ---------------------------------------------------------------------- |
44
+ | Published on this connection, symbol present | WebSocket slice, no request |
45
+ | Published on this connection, symbol missing | One REST read of that DEX (since 16.1.0) |
46
+ | Not published on this connection | REST read of that DEX. Close and margin operations take this path too. |
47
+ | REST read gets no answer | `PROVIDER_NOT_AVAILABLE` |
48
+ | Position still absent | `POSITION_NOT_FOUND` |
49
+
50
+ - "Published on this connection" is a connection-epoch check (`stampedEpoch === getConnectionEpoch()`), not a recency check. A stale size on a symbol already in the slice is used as is.
51
+ - Only `updatePositionTPSL` and `replacePositionTPSLLeg` opt into the missing-symbol read. `closePosition`, `closePositions` and the margin operations fail closed on a miss in a current slice.
52
+ - The `position` argument is diagnostic. A size that differs from the lookup only writes a debug log.
53
+ - `expectedPosition` (`size`, `entryPrice`) is enforced. A missing position or a mismatch fails with `TPSL_UPDATE_FAILED`.
54
+
55
+ ### Orders
56
+
57
+ - A whole-position update sends size `'0'` with grouping `positionTpsl` while `UsePositionBoundTpsl` is on.
58
+ - A partial update (`takeProfitSize` / `stopLossSize`) sends an explicit size floored to `szDecimals` with grouping `na`, validated against the position size.
59
+ - Legs are reduce-only on the side that closes the position. The TP leg is a limit trigger with `p` = TP price. The SL leg is a market trigger with `p` = SL price, no slippage offset.
60
+ - `replacePositionTPSLLeg` replaces one leg. Its leg is a limit trigger when `limitPrice` is given; otherwise a market trigger capped at the trigger moved by `maxSlippageBps` (default `DefaultTpslSlippageBps`).
61
+ - Before placing, the update cancels every standalone reduce-only trigger on the symbol, not only the ones it placed. TP/SL children of a pending order are kept.
62
+
63
+ Code: `src/providers/HyperLiquidProvider.ts` `updatePositionTPSL`, `#replacePositionTpsl`, `replacePositionTPSLLeg`, `#getPositionsForOperation`; `src/utils/hyperLiquidValidation.ts` `createErrorResult`; `src/services/HyperLiquidSubscriptionService.ts` `getCachedPositionsForDex`, `#isPositionDexFresh`; `src/utils/positionProtection.ts` `assertExpectedPosition`; `src/types/index.ts` `UpdatePositionTPSLParams`.
64
+
65
+ ## Config
66
+
67
+ | Constant | Value | Effect |
68
+ | ---------------------------------------------- | -------------------------------------------------- | -------------------------------------------------------------------------------- |
69
+ | `TP_SL_CONFIG.UsePositionBoundTpsl` | `true` | Whole-position updates send size `'0'`; off, they send the floored position size |
70
+ | `ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps` | 1000 | SL child limit price; default cap of a market-executing trigger |
71
+ | `TP_SL_PRECISION_CONFIG` | 8 dp below $0.01, 6 below $1, 4 below $100, else 2 | Decimals of a calculated trigger price |
72
+
73
+ Code: `src/constants/perpsConfig.ts` `TP_SL_CONFIG`, `ORDER_SLIPPAGE_CONFIG`, `TP_SL_PRECISION_CONFIG`.
74
+
75
+ ## Rules for callers
76
+
77
+ 1. Do not rely on the `position` argument to avoid `POSITION_NOT_FOUND`. Pass `expectedPosition` to make the update conditional.
78
+ 2. Do not pass position linkage to `placeOrder`. It is rejected.
79
+ 3. Moving a case between the two mechanisms changes sizing, not only timing.
80
+
81
+ ## History
82
+
83
+ - 15.1.0 ([core#10037](https://github.com/MetaMask/core/pull/10037)) made the lookup cache-first and fail-closed, and the caller snapshot became a log line.
84
+ - 16.0.0 ([core#10083](https://github.com/MetaMask/core/pull/10083)) added the provider-neutral code `POSITION_NOT_FOUND`.
85
+ - Before 16.1.0, a call fired right after a fill failed with no network read. 16.1.0 ([core#10101](https://github.com/MetaMask/core/pull/10101)) makes `updatePositionTPSL` revalidate once over HTTP when the symbol is missing.
86
+
87
+ The client decision between the two mechanisms, its hooks and the stream wait are in [metamask-mobile/docs/perps/perps-tpsl-attachment.md](https://github.com/MetaMask/metamask-mobile/blob/main/docs/perps/perps-tpsl-attachment.md).
88
+
89
+ Code: `CHANGELOG.md`.
@@ -0,0 +1,27 @@
1
+ # HyperLiquid
2
+
3
+ HyperLiquid's own documentation is the source for its API and trading rules. Copies go stale; link the source instead.
4
+
5
+ | Topic | Official page |
6
+ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
7
+ | Exchange endpoint | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/exchange-endpoint |
8
+ | Info endpoint | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/info-endpoint |
9
+ | WebSocket subscriptions | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/websocket/subscriptions |
10
+ | Rate limits and user limits | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/rate-limits-and-user-limits |
11
+ | Tick and lot size | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/tick-and-lot-size |
12
+ | Asset IDs | https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api/asset-ids |
13
+ | Fees | https://hyperliquid.gitbook.io/hyperliquid-docs/trading/fees |
14
+ | Margining | https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margining |
15
+ | Margin tiers | https://hyperliquid.gitbook.io/hyperliquid-docs/trading/margin-tiers |
16
+ | Portfolio margin | https://hyperliquid.gitbook.io/hyperliquid-docs/trading/portfolio-margin |
17
+ | Account abstraction modes | https://hyperliquid.gitbook.io/hyperliquid-docs/trading/account-abstraction-modes |
18
+ | HIP-1, native tokens | https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-1-native-token-standard |
19
+ | HIP-2, Hyperliquidity | https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-2-hyperliquidity |
20
+ | HIP-3, builder-deployed perps | https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/hip-3-builder-deployed-perpetuals |
21
+ | Frontend checks | https://hyperliquid.gitbook.io/hyperliquid-docs/hyperliquid-improvement-proposals-hips/frontend-checks |
22
+
23
+ How our provider uses HyperLiquid (init calls, order types, trading rules we encode) is in this folder:
24
+
25
+ - [init-flow.md](./init-flow.md)
26
+ - [order-types.md](./order-types.md)
27
+ - [trading-rules.md](./trading-rules.md)
@@ -0,0 +1,116 @@
1
+ # HyperLiquid init flow
2
+
3
+ Which client entry point starts the flow, and when, is client code. Controller registration and `PerpsController.init()` are in [architecture.md](../../architecture.md). This page covers what `HyperLiquidProvider` calls on HyperLiquid.
4
+
5
+ ```mermaid
6
+ sequenceDiagram
7
+ participant C as PerpsController
8
+ participant HLP as HyperLiquidProvider
9
+ participant SS as SubscriptionService
10
+ participant API as HyperLiquid API
11
+
12
+ C->>HLP: a provider method that needs setup
13
+ HLP->>HLP: #ensureReady()
14
+ Note over HLP: SDK clients (#ensureClientsInitialized), no info calls
15
+ Note over HLP: Phase 1, asset mapping
16
+ HLP->>API: perpDexs (via #dexDiscoveryCache)
17
+ par each enabled DEX, Promise.allSettled
18
+ HLP->>API: metaAndAssetCtxs(dex)
19
+ end
20
+ HLP->>SS: setDexMetaCache, setDexAssetCtxsCache
21
+ Note over HLP: Phase 2, unified account
22
+ HLP->>API: userNonFundingLedgerUpdates (registration probe)
23
+ HLP->>API: userAbstraction
24
+ Note over HLP: Phase 3, separate: getMarketDataWithPrices calls #ensureReady() first
25
+ HLP->>SS: allMids snapshot, asset contexts
26
+ HLP->>API: allMids / metaAndAssetCtxs only on a miss
27
+ ```
28
+
29
+ ## `initialize()` and `#ensureReady()`
30
+
31
+ - `PerpsController.init()` does not call `initialize()`. `#ensureReady()` creates the SDK clients through `#ensureClientsInitialized` on first use. `initialize()` does the same and makes no info call.
32
+ - Most provider methods run `#ensureReady()` lazily; `getPositions()` only initializes the SDK clients. Concurrent callers share `#ensureReadyPromise`.
33
+ - `#ensureReadyPromise` is dropped, so the next caller runs setup again, when setup throws, when DEX discovery was degraded, when the unified-account step needs a retry, or during the transport cooldown.
34
+
35
+ Code: `src/providers/HyperLiquidProvider.ts` `initialize`, `#ensureClientsInitialized`, `#ensureReady`.
36
+
37
+ ## Phase 1, asset mapping
38
+
39
+ `#buildAssetMapping` runs when `#symbolToAssetId` is empty or DEX discovery is incomplete.
40
+
41
+ 1. `#getValidatedDexs` returns the main DEX only when `hip3Enabled` is off. Otherwise it reads `perpDexs` once and `DexDiscoveryCacheManager` filters it by the HIP-3 config on testnet and by the DEXes the market allowlist names on mainnet, unless `AutoDiscoverAll` is set. Concurrent callers share one pending request. A failed read returns the main DEX only and is not cached.
42
+ 2. For each DEX not already in `#cachedMetaByDex`, `metaAndAssetCtxs` (not `meta`), in parallel with `Promise.allSettled`.
43
+ 3. `#symbolToAssetId` is filled. `#cacheDexMetadata` writes the provider cache and hands meta and asset contexts to the subscription service.
44
+
45
+ The DEX count depends on `perpDexs`, `hip3Enabled` and the allowlist, so the call count is not fixed.
46
+
47
+ Code: `src/providers/HyperLiquidProvider.ts` `#buildAssetMapping`, `#getValidatedDexs`, `#fetchValidatedDexsInternal`, `#cacheDexMetadata`; `src/services/DexDiscoveryCacheManager.ts`.
48
+
49
+ ## Phase 2, unified account
50
+
51
+ `#ensureReady` calls `#ensureUnifiedAccountEnabled` unless the provider is disconnected or in the transport cooldown. Software wallets run it with signing allowed; wallets where `requiresSignatureConfirmation()` is true (hardware, QR) run it without.
52
+
53
+ - Skipped when `TradingReadinessCache` holds a final outcome for this network and address. Deferred, unregistered and retry outcomes are not final, so the next entry reads again.
54
+ - `userNonFundingLedgerUpdates` probes whether the wallet is registered on HyperLiquid. A positive answer is cached. An unregistered wallet is skipped.
55
+ - `userAbstraction` reads the mode.
56
+
57
+ | Mode | Action at init |
58
+ | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
59
+ | `unifiedAccount`, `portfolioMargin` | No write; success cached |
60
+ | `default`, `disabled`, signing allowed | `userToMultiSigSigners` probe, then silent `agentSetAbstraction`. A multi-sig account is skipped and cached as final. |
61
+ | `default`, `disabled`, signing not allowed | Deferred to action time; cache untouched |
62
+ | Any other mode, including `dexAbstraction` | Log and skip |
63
+
64
+ Referral (`referral`) and builder-fee approval (`maxBuilderFee`) do not run at init. `#ensureReadyForTrading` runs them before the first trade or withdrawal.
65
+
66
+ Code: `src/providers/HyperLiquidProvider.ts` `#ensureUnifiedAccountEnabled`, `#isWalletOnHyperliquid`, `#getAccountSupportForContext`, `#ensureReadyForTrading`, `#ensureReferralSet`, `#ensureBuilderFeeApproval`; `src/utils/hyperLiquidAbstraction.ts` `shouldDeferUnifiedAccountSetup`; `src/services/TradingReadinessCache.ts`.
67
+
68
+ ## Phase 3, `getMarketDataWithPrices`
69
+
70
+ 1. Awaits `#ensureReady`, so the meta cache is filled first.
71
+ 2. Uses the HTTP info client.
72
+ 3. Per DEX with cached meta, takes asset contexts from the subscription service cache. When their length differs from the universe length it refetches `metaAndAssetCtxs`.
73
+ 4. Per DEX without cached meta, `#fetchSingleDexFresh` calls `metaAndAssetCtxs`.
74
+ 5. Mid prices come from the WebSocket `allMids` snapshot; REST `allMids` runs only when no snapshot exists.
75
+
76
+ Code: `src/providers/HyperLiquidProvider.ts` `getMarketDataWithPrices`, `#fetchSingleDexFresh`, `#getAllMids`; `src/services/HyperLiquidSubscriptionService.ts` `getLastAllMidsSnapshot`, `getDexAssetCtxsCache`.
77
+
78
+ ## Caches
79
+
80
+ | Cache | Owner | Key for main DEX | Holds |
81
+ | -------------------- | -------------------------- | ---------------- | --------------------------------------------------------------------------------------------------- |
82
+ | `#symbolToAssetId` | Provider | | Symbol to asset ID |
83
+ | `#cachedMetaByDex` | Provider | `null` | `MetaResponse` per DEX |
84
+ | `#dexDiscoveryCache` | `DexDiscoveryCacheManager` | | Raw and validated `perpDexs` |
85
+ | `#dexMetaCache` | Subscription service | `''` | Meta, written only when the provider also has asset contexts. On a miss the service fetches `meta`. |
86
+ | `#dexAssetCtxsCache` | Subscription service | `''` | Asset contexts used by `getMarketDataWithPrices` |
87
+
88
+ What `disconnect()` clears is in [architecture.md](../../architecture.md).
89
+
90
+ Code: `src/providers/HyperLiquidProvider.ts` `#symbolToAssetId`, `#cachedMetaByDex`, `#dexDiscoveryCache`; `src/services/HyperLiquidSubscriptionService.ts` `setDexMetaCache`, `setDexAssetCtxsCache`, `#dexMetaCache`, `#dexAssetCtxsCache`.
91
+
92
+ ## Transports
93
+
94
+ | Client | Transport | Use |
95
+ | -------------------------------------------------------------------- | --------- | -------------------------------------------------------------------- |
96
+ | `ExchangeClient` | HTTP | Writes (orders, approvals) |
97
+ | `InfoClient` (`#infoClient`, default) | WebSocket | Reads such as `perpDexs` and `metaAndAssetCtxs` during asset mapping |
98
+ | `InfoClient` (`#infoClientHttp`, `getInfoClient({ useHttp: true })`) | HTTP | Market data, REST position reads, price fallback |
99
+ | `SubscriptionClient` | WebSocket | Live channels |
100
+
101
+ `getInfoClient` throws when the clients are not initialized. The provider picks the transport per call; the controller never sees it.
102
+
103
+ Code: `src/services/HyperLiquidClientService.ts` `#createAllClients`, `#createHttpClients`, `getInfoClient`.
104
+
105
+ ## Subscriptions
106
+
107
+ | Channel | Scope | Feeds |
108
+ | -------------------- | ------------------ | ---------------------------------- |
109
+ | `clearinghouseState` | Per DEX | Positions and account |
110
+ | `openOrders` | Per DEX | Orders |
111
+ | `webData3` | User | Open-interest caps only |
112
+ | `allMids` | Global and per DEX | Mid prices |
113
+ | `assetCtxs` | Per DEX | Funding, open interest, mark price |
114
+ | `fastAssetCtxs` | Global | Price updates |
115
+
116
+ Code: `src/services/HyperLiquidSubscriptionService.ts` `#ensureClearinghouseStateSubscription`, `#ensureOpenOrdersSubscription`, `#ensureGlobalAllMidsSubscription`, `#createDexAllMidsSubscription`, `#createAssetCtxsSubscription`, `#ensureGlobalFastAssetCtxsSubscription`.
@@ -0,0 +1,60 @@
1
+ # HyperLiquid order types
2
+
3
+ How `HyperLiquidProvider` turns `OrderParams` into HyperLiquid SDK orders. HyperLiquid's own order types and time-in-force rules are on the exchange endpoint page linked from [README.md](./README.md).
4
+
5
+ ## Order shape
6
+
7
+ Each order is `{ a, b, p, s, r, t, c }`.
8
+
9
+ | Field | Value |
10
+ | ----- | ----------------------------------------------------- |
11
+ | `a` | Asset ID (see [trading-rules.md](./trading-rules.md)) |
12
+ | `b` | `isBuy` |
13
+ | `p` | Price formatted by `formatHyperLiquidPrice` |
14
+ | `s` | Size formatted by `formatHyperLiquidSize` |
15
+ | `r` | `reduceOnly ?? false` |
16
+ | `t` | Order type, below |
17
+ | `c` | `clientOrderId`, when given |
18
+
19
+ The request also carries `grouping` (`na`, `normalTpsl`, `positionTpsl`) and, when a builder fee applies, `builder: { b, f }` with `f` in tenths of a basis point. The types come from the SDK `OrderParameters`.
20
+
21
+ Code: `src/utils/orderCalculations.ts` `buildOrdersArray`; `src/types/hyperliquid-types.ts` `SDKOrderParams`; `src/providers/HyperLiquidProvider.ts` `#submitOrderWithRollback`, `#getBuilderOrderContext`.
22
+
23
+ ## Main order type
24
+
25
+ | `orderType` | SDK `t` | `p` |
26
+ | ----------------------------------- | ----------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
27
+ | `market` | `{ limit: { tif: 'FrontendMarket' } }` | Live price moved by `maxSlippageBps` (default `DefaultMarketSlippageBps`, 300) |
28
+ | `limit` | `{ limit: { tif } }`, `tif` from `timeInForce`: `GTC` → `Gtc` (default), `IOC` → `Ioc`, `ALO` → `Alo` | Limit price, no slippage |
29
+ | `stop_market`, `take_profit_market` | `{ trigger: { isMarket: true, triggerPx, tpsl } }` | Trigger price moved by `maxSlippageBps` (default `DefaultTpslSlippageBps`, 1000) |
30
+ | `stop_limit`, `take_profit_limit` | `{ trigger: { isMarket: false, triggerPx, tpsl } }` | Limit price |
31
+
32
+ - There is no pure market order. A market order is an aggressive limit at the slippage-adjusted price with `FrontendMarket`.
33
+ - A buy moves the price up by the slippage, a sell moves it down.
34
+ - `tpsl` is `sl` for stop types and `tp` for take-profit types.
35
+
36
+ | Error | When |
37
+ | ----------------------------------- | ------------------------------------------------------------ |
38
+ | `ORDER_TIME_IN_FORCE_NOT_SUPPORTED` | `timeInForce` on anything but `limit` |
39
+ | `ORDER_LIMIT_PRICE_REQUIRED` | `limit`, `stop_limit` or `take_profit_limit` without a price |
40
+ | `ORDER_TRIGGER_PRICE_REQUIRED` | Trigger type without `triggerPrice` |
41
+ | `ORDER_TRIGGER_PRICE_POSITIVE` | Trigger price not positive, or zero at the asset's precision |
42
+
43
+ Code: `src/utils/orderCalculations.ts` `calculateOrderPriceAndSize`, `buildMainOrderTypeField`, `formatTriggerPrice`; `src/utils/orderTypes.ts` `toSDKTimeInForce`, `isTriggerOrderType`, `isLimitExecutionOrderType`, `TRIGGER_ORDER_TYPES`.
44
+
45
+ ## Other placement paths
46
+
47
+ | Path | Order type |
48
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
49
+ | Attached TP/SL | TP child limit trigger, SL child market trigger. See [tpsl.md](../../tpsl.md). |
50
+ | `updatePositionTPSL` legs | See [tpsl.md](../../tpsl.md) |
51
+ | `closePosition` | Through `#placeOrder` with `reduceOnly: true`; `orderType` defaults to `market`, so `FrontendMarket` |
52
+ | `closePositions` (batch) | `{ limit: { tif: 'Ioc' } }`, `r: true`, price moved by `DefaultMarketSlippageBps` |
53
+ | Scale ladder | `Gtc` limit per rung |
54
+ | Chase | `Alo` (post-only), so it rests at the touch instead of crossing |
55
+ | `editOrder` | Limit keeps `timeInForce` through `toSDKTimeInForce`; market uses `FrontendMarket`. Trigger and strategy edits are rejected (`ORDER_EDIT_TRIGGER_UNSUPPORTED`, `ORDER_EDIT_STRATEGY_UNSUPPORTED`) |
56
+ | TWAP | `exchangeClient.twapOrder` with duration and randomize; no time in force |
57
+
58
+ The SDK's `LiquidationMarket` time in force is not used.
59
+
60
+ Code: `src/providers/HyperLiquidProvider.ts` `closePosition`, `closePositions`, `#placeScaleOrder`, `#restChaseOrder`, `editOrder`, `#placeTwapOrder`.
@@ -0,0 +1,77 @@
1
+ # HyperLiquid trading rules in code
2
+
3
+ Only the venue rules our code encodes. Everything else (margin tiers, HIP-1 tokens, open-interest caps, venue error strings) is on the official pages linked from [README.md](./README.md).
4
+
5
+ ## Fees
6
+
7
+ | Rule | Constant | Value |
8
+ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------ |
9
+ | Base taker rate, Tier 0 | `FEE_RATES.taker` | 0.045% |
10
+ | Base maker rate, Tier 0 | `FEE_RATES.maker` | 0.015% |
11
+ | HIP-3 multiplier | `deployerFeeScale < 1 ? scale + 1 : scale × 2`, times `HIP3_FEE_CONFIG.GrowthModeScale` (0.1) in growth mode | 2× at scale 1.0 without growth mode |
12
+ | HIP-3 scale when `perpDexs` has none | `HIP3_FEE_CONFIG.DefaultDeployerFeeScale` | 1.0 |
13
+ | MetaMask builder fee ceiling | `BUILDER_FEE_CONFIG.MaxFeeTenthsBps` | 100 tenths of a bp (10 bps), sent as `builder.f` |
14
+
15
+ - `calculateFees` charges the maker rate only for a limit-executing maker order or a chase, otherwise the taker rate, then applies the HIP-3 multiplier.
16
+ - The builder fee sent with an order is the ceiling reduced by the discount from the unified fee resolution (`RewardsIntegrationService.resolveFee`: rewards, grant or subscription), floored to whole tenths of a bp (`#getDiscountedBuilderFee`, `quantizeBuilderFeeTenthsBps`).
17
+
18
+ Code: `src/constants/hyperLiquidConfig.ts` `FEE_RATES`, `HIP3_FEE_CONFIG`, `BUILDER_FEE_CONFIG`; `src/providers/HyperLiquidProvider.ts` `calculateFees`, `#calculateHip3FeeMultiplier`, `#getDiscountedBuilderFee`, `setUserFeeResolution`; `src/services/TradingService.ts`; `src/services/RewardsIntegrationService.ts` `resolveFee`; `src/utils/subscriptionFeeWaiver.ts` `quantizeBuilderFeeTenthsBps`.
19
+
20
+ ## Slippage
21
+
22
+ | Use | Constant | Value |
23
+ | -------------------------------------------------- | ------------------------------------------------ | --------------------------------------- |
24
+ | Market orders, batch close, USD-sizing price guard | `ORDER_SLIPPAGE_CONFIG.DefaultMarketSlippageBps` | 300 bps (3%) |
25
+ | SL child and market-executing triggers | `ORDER_SLIPPAGE_CONFIG.DefaultTpslSlippageBps` | 1000 bps (10%) |
26
+ | Limit orders | `ORDER_SLIPPAGE_CONFIG.DefaultLimitSlippageBps` | 100 bps (1%); defined, not read by Core |
27
+
28
+ A caller's `maxSlippageBps` replaces the default. For an order sized from `usdAmount` with `priceAtCalculation`, a price move larger than the tolerance since the calculation throws a price-moved error before signing.
29
+
30
+ Code: `src/constants/perpsConfig.ts` `ORDER_SLIPPAGE_CONFIG`; `src/utils/orderCalculations.ts` `calculateFinalPositionSize`, `calculateOrderPriceAndSize`.
31
+
32
+ ## Order validation
33
+
34
+ | Rule | Constant | Error |
35
+ | -------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------- | ------------------------------- |
36
+ | Minimum order value $10, every DEX | `TRADING_DEFAULTS.amount.mainnet`, `.testnet` | `ORDER_SIZE_MIN` |
37
+ | Maximum order value by market max leverage: ≥ 25x $15M, ≥ 20x $5M, ≥ 10x $2M, else $500K; limit-executing orders 10× | `HYPERLIQUID_ORDER_LIMITS` | `ORDER_MAX_VALUE_EXCEEDED` |
38
+ | TWAP duration 5 to 1440 minutes | `HYPERLIQUID_TWAP_LIMITS.MinDurationMinutes`, `.MaxDurationMinutes` | `ORDER_TWAP_DURATION_INVALID` |
39
+ | TWAP total at least $100 | `HYPERLIQUID_TWAP_LIMITS.MinNotionalUsd` | `ORDER_TWAP_NOTIONAL_TOO_SMALL` |
40
+
41
+ - The minimum checks `usdAmount` when given, else size × `currentPrice`. Without `currentPrice` it uses the limit price for limit-executing orders and the trigger price for market triggers. A full close skips it.
42
+ - The venue's "Order must have minimum value of $10" rejection maps to `ORDER_SIZE_MIN` for opening orders. Reduce-only and strategy orders keep the venue error.
43
+ - The maximum is checked when `currentPrice` and `leverage` are given.
44
+
45
+ Code: `src/providers/HyperLiquidProvider.ts` `validateOrder`, `#placeOrder`, `#placeTwapOrder`; `src/utils/hyperLiquidValidation.ts` `getMaxOrderValue`; `src/constants/hyperLiquidConfig.ts` `TRADING_DEFAULTS`; `src/constants/perpsConfig.ts` `HYPERLIQUID_ORDER_LIMITS`, `HYPERLIQUID_TWAP_LIMITS`.
46
+
47
+ ## Price and size format
48
+
49
+ | Rule | Constant |
50
+ | ---------------------------------------------------------------------------------------- | ---------------------------------------------------- |
51
+ | Integer prices pass through unchanged | |
52
+ | Other prices keep at most 6 − `szDecimals` decimals | `DECIMAL_PRECISION_CONFIG.MaxPriceDecimals` (6) |
53
+ | Then at most 5 significant figures | `DECIMAL_PRECISION_CONFIG.MaxSignificantFigures` (5) |
54
+ | Sizes keep `szDecimals`, trailing zeros removed; TP/SL and reduce-only sizes are floored | |
55
+
56
+ `formatHyperLiquidPrice` does not check tick divisibility. It is exported from the package.
57
+
58
+ Code: `src/utils/hyperLiquidAdapter.ts` `formatHyperLiquidPrice`, `formatHyperLiquidSize`; `src/utils/orderCalculations.ts` `floorToSizeDecimals`, `formatPartialTpslSize`.
59
+
60
+ ## Asset IDs
61
+
62
+ | Market | Asset ID | Constant |
63
+ | -------------- | -------------------------------------------------------------- | ---------------------------------------------------- |
64
+ | Main DEX perps | Universe index | |
65
+ | HIP-3 perps | 100000 + `perpDexIndex` × 10000 + index (xyz index 0 → 110000) | `HIP3_ASSET_ID_CONFIG.BaseAssetId`, `.DexMultiplier` |
66
+ | Spot | 10000 + pair index | `SPOT_ASSET_ID_OFFSET` |
67
+
68
+ Code: `src/utils/hyperLiquidAdapter.ts` `calculateHip3AssetId`; `src/constants/hyperLiquidConfig.ts` `HIP3_ASSET_ID_CONFIG`, `SPOT_ASSET_ID_OFFSET`.
69
+
70
+ ## Margin and collateral
71
+
72
+ - Cross margin is offered on main-DEX and HIP-3 markets unless the venue marks them `onlyIsolated` or sets a `marginMode` other than `normal` (`noCross`, `strictIsolated`).
73
+ - Without Unified Account, adding to an isolated HIP-3 position transfers the whole position's margin before the order, because the venue checks it against the full position. Adding to a Cross position transfers only the new order's margin.
74
+ - HIP-3 DEXs whose collateral is not USDC are excluded from market data and order placement.
75
+ - With Unified Account or portfolio margin, HyperLiquid moves HIP-3 collateral itself. Otherwise `#handleHip3PreOrder` moves it with `exchangeClient.sendAsset` before the order.
76
+
77
+ Code: `src/providers/HyperLiquidProvider.ts` `#isCrossMarginSupported`, `#isUsdcCollateralDex`, `#excludeNonUsdcCollateralResults`, `#handleHip3PreOrder`, `#transferBetweenDexs`.
@@ -0,0 +1,58 @@
1
+ # Lighter trading keys
2
+
3
+ Your Ethereum address owns your Lighter account. Orders use a separate trading key registered with Lighter in a numbered API-key slot. `LighterProvider` selects the slot and registers the key. The client's `LighterSignerBridge` creates and stores keys and reports which slots it can recover; Core never receives a private key.
4
+
5
+ Key derivation, key storage and Mobile's env variables are in [metamask-mobile/docs/perps/lighter-api-keys.md](https://github.com/MetaMask/metamask-mobile/blob/main/docs/perps/lighter-api-keys.md).
6
+
7
+ ## Config
8
+
9
+ | Input | Source | Default |
10
+ | ---------------------- | ------------------------------------------------------------------------ | ----------------------------------- |
11
+ | Preferred slot | `providerCredentials.lighter.apiKeyIndex` | 7 (`LIGHTER_DEFAULT_API_KEY_INDEX`) |
12
+ | Trading slots | `LIGHTER_MIN_TRADING_API_KEY_INDEX`, `LIGHTER_MAX_TRADING_API_KEY_INDEX` | 2 to 254 |
13
+ | Account index override | `providerCredentials.lighter.accountIndexTestnet`, `accountIndexMainnet` | Discovered from the address |
14
+
15
+ - Without an override, `#ensureAccountIndex` reads `getAccountsByL1Address` and takes the sub-account with the lowest index.
16
+ - An override or discovered account must be a Standard account owned by the selected address. Anything else is refused.
17
+ - With no `signerBridge`, the provider is read-only.
18
+
19
+ Code: `src/constants/lighterConfig.ts` `LIGHTER_DEFAULT_API_KEY_INDEX`, `LIGHTER_MIN_TRADING_API_KEY_INDEX`, `LIGHTER_MAX_TRADING_API_KEY_INDEX`; `src/types/index.ts` `LighterCredentials`; `src/providers/LighterProvider.ts` `#ensureAccountIndex`, `#assertStandardAccount`, `#assertAccountOwnership`.
20
+
21
+ ## Slot selection
22
+
23
+ `#signerCandidates` builds the ordered list of slots to try.
24
+
25
+ 1. A pending registration pins the list to its slot.
26
+ 2. A bridge with neither `getRecoverableKeyIndices` nor `getStoredKeyIndices` gets the preferred slot only.
27
+ 3. Otherwise the provider reads the venue's registered keys (`getApiKeys`) and asks the bridge which of the preferred and occupied slots in 2 to 254 it can recover. `getRecoverableKeyIndices` wins when both hooks exist.
28
+ 4. The list is recoverable occupied slots, recoverable free slots, the preferred slot if free, then every other free slot. Wallet-derived recovery keeps free slots in order; storage-only discovery starts them at a random offset.
29
+ 5. When the bridge recovers nothing, the preferred slot is occupied and a free slot exists, setup stops with "No recoverable Lighter trading key is available from this wallet or local storage. Use an existing registered device."
30
+
31
+ With a discovery-capable bridge, a preferred slot outside 2 to 254 drops out of the list without an error.
32
+
33
+ Code: `src/providers/LighterProvider.ts` `#signerCandidates`; `src/types/lighter-types.ts` `LighterSignerBridge.getRecoverableKeyIndices`, `getStoredKeyIndices`.
34
+
35
+ ## Recovery and reuse
36
+
37
+ `#setupSignerForAccount` runs under a process mutex per network and account. For each candidate it creates the bridge client and compares its public key with the venue (`#venueKeyStatus`).
38
+
39
+ | Venue slot | Action |
40
+ | ------------------------------------ | -------------------------------------------------------- |
41
+ | Holds this device's key (`matching`) | Reuse it; no registration and no new slot |
42
+ | Empty (`available`) | Register this key |
43
+ | Holds a different key (`occupied`) | Skip it. Another device or application may still use it. |
44
+
45
+ A bridge without recovery hooks that meets an occupied slot fails with a reconnect hint. When every candidate is skipped, setup fails with "No available Lighter trading key slot. Remove an unused API key in Lighter, then reconnect."
46
+
47
+ Code: `src/providers/LighterProvider.ts` `#setupSigner`, `#setupSignerForAccount`, `#venueKeyStatus`.
48
+
49
+ ## Registration
50
+
51
+ 1. The bridge's `ChangePubKey` plaintext is signed by the Ethereum wallet with `personal_sign` (EIP-191), then the bridge signs the L2 transaction.
52
+ 2. With a recovery-capable bridge (`getRecoverableKeyIndices` or `getStoredKeyIndices`), the pending registration (slot, public key, tx hash, nonce, expiry) is written to `diskCache` before dispatch.
53
+ 3. Such a bridge then waits in `#waitForRegisteredKey`, which polls the venue every 250 ms for up to 10 s until the slot shows this key. A different key fails setup. A timeout returns "Lighter trading key registration is still pending; reconnect to check its status".
54
+ 4. On reconnect the pending slot is checked first. A matching key clears the record. A failed or expired unsent transaction clears it. Otherwise it stays pending.
55
+
56
+ A bridge without those hooks submits the transaction directly, with no pending record and no visibility wait.
57
+
58
+ Code: `src/providers/LighterProvider.ts` `#registerVenueKey`, `#waitForRegisteredKey`, `#loadPendingKeyRegistration`, `#reconcilePendingKeyRegistration`; `src/constants/lighterConfig.ts` `LIGHTER_KEY_REGISTRATION_VISIBILITY_TIMEOUT_MS`, `LIGHTER_KEY_REGISTRATION_VISIBILITY_POLL_MS`.