@metamask-previews/perps-controller 8.2.0-preview-b2742a2fc → 8.3.0-preview-a8fd340
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.
- package/CHANGELOG.md +24 -1
- package/dist/PerpsController.cjs +46 -10
- package/dist/PerpsController.cjs.map +1 -1
- package/dist/PerpsController.d.cts.map +1 -1
- package/dist/PerpsController.d.mts.map +1 -1
- package/dist/PerpsController.mjs +46 -10
- package/dist/PerpsController.mjs.map +1 -1
- package/dist/constants/hyperLiquidConfig.cjs +7 -0
- package/dist/constants/hyperLiquidConfig.cjs.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.cts +1 -0
- package/dist/constants/hyperLiquidConfig.d.cts.map +1 -1
- package/dist/constants/hyperLiquidConfig.d.mts +1 -0
- package/dist/constants/hyperLiquidConfig.d.mts.map +1 -1
- package/dist/constants/hyperLiquidConfig.mjs +7 -0
- package/dist/constants/hyperLiquidConfig.mjs.map +1 -1
- package/dist/constants/perpsConfig.cjs +11 -1
- package/dist/constants/perpsConfig.cjs.map +1 -1
- package/dist/constants/perpsConfig.d.cts +10 -0
- package/dist/constants/perpsConfig.d.cts.map +1 -1
- package/dist/constants/perpsConfig.d.mts +10 -0
- package/dist/constants/perpsConfig.d.mts.map +1 -1
- package/dist/constants/perpsConfig.mjs +10 -0
- package/dist/constants/perpsConfig.mjs.map +1 -1
- package/dist/index.cjs +4 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/providers/HyperLiquidProvider.cjs +6 -3
- package/dist/providers/HyperLiquidProvider.cjs.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.cts +1 -0
- package/dist/providers/HyperLiquidProvider.d.cts.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.mts +1 -0
- package/dist/providers/HyperLiquidProvider.d.mts.map +1 -1
- package/dist/providers/HyperLiquidProvider.mjs +7 -4
- package/dist/providers/HyperLiquidProvider.mjs.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.cjs +16 -3
- package/dist/services/HyperLiquidSubscriptionService.cjs.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.cts +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.cts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.mts +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.mts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.mjs +17 -4
- package/dist/services/HyperLiquidSubscriptionService.mjs.map +1 -1
- package/dist/services/MarketDataService.cjs +100 -7
- package/dist/services/MarketDataService.cjs.map +1 -1
- package/dist/services/MarketDataService.d.cts +10 -1
- package/dist/services/MarketDataService.d.cts.map +1 -1
- package/dist/services/MarketDataService.d.mts +10 -1
- package/dist/services/MarketDataService.d.mts.map +1 -1
- package/dist/services/MarketDataService.mjs +100 -7
- package/dist/services/MarketDataService.mjs.map +1 -1
- package/dist/services/TerminalMarketService.cjs +195 -0
- package/dist/services/TerminalMarketService.cjs.map +1 -0
- package/dist/services/TerminalMarketService.d.cts +36 -0
- package/dist/services/TerminalMarketService.d.cts.map +1 -0
- package/dist/services/TerminalMarketService.d.mts +36 -0
- package/dist/services/TerminalMarketService.d.mts.map +1 -0
- package/dist/services/TerminalMarketService.mjs +191 -0
- package/dist/services/TerminalMarketService.mjs.map +1 -0
- package/dist/types/index.cjs.map +1 -1
- package/dist/types/index.d.cts +82 -0
- package/dist/types/index.d.cts.map +1 -1
- package/dist/types/index.d.mts +82 -0
- package/dist/types/index.d.mts.map +1 -1
- package/dist/types/index.mjs.map +1 -1
- package/dist/utils/marketDataTransform.cjs +44 -9
- package/dist/utils/marketDataTransform.cjs.map +1 -1
- package/dist/utils/marketDataTransform.d.cts +28 -0
- package/dist/utils/marketDataTransform.d.cts.map +1 -1
- package/dist/utils/marketDataTransform.d.mts +28 -0
- package/dist/utils/marketDataTransform.d.mts.map +1 -1
- package/dist/utils/marketDataTransform.mjs +42 -8
- package/dist/utils/marketDataTransform.mjs.map +1 -1
- package/dist/utils/marketSearch.cjs +28 -2
- package/dist/utils/marketSearch.cjs.map +1 -1
- package/dist/utils/marketSearch.d.cts +4 -3
- package/dist/utils/marketSearch.d.cts.map +1 -1
- package/dist/utils/marketSearch.d.mts +4 -3
- package/dist/utils/marketSearch.d.mts.map +1 -1
- package/dist/utils/marketSearch.mjs +28 -2
- package/dist/utils/marketSearch.mjs.map +1 -1
- package/package.json +3 -2
|
@@ -10,6 +10,34 @@ import type { AllMidsResponse, PerpsUniverse, PerpsAssetCtx, PredictedFunding }
|
|
|
10
10
|
* @returns Open interest in USD, or NaN if invalid
|
|
11
11
|
*/
|
|
12
12
|
export declare function calculateOpenInterestUSD(openInterest: string | number | undefined, currentPrice: string | number | undefined): number;
|
|
13
|
+
/**
|
|
14
|
+
* Determine whether a market is currently tradable based on how far its market
|
|
15
|
+
* (mid) price has drifted from the oracle (reference) price.
|
|
16
|
+
*
|
|
17
|
+
* HyperLiquid rejects orders when the order price is more than 95% away from the
|
|
18
|
+
* reference price ("Order price cannot be more than 95% away from the reference
|
|
19
|
+
* price"). This most often affects HIP-3 builder-deployed markets, which can become
|
|
20
|
+
* temporarily untradable when their mid price diverges far from the oracle price.
|
|
21
|
+
* Clients use this signal to proactively warn the user (e.g. a "trading unavailable"
|
|
22
|
+
* banner) instead of letting the order fail on submission.
|
|
23
|
+
*
|
|
24
|
+
* Note: the deviation limit is a HyperLiquid protocol rule. Other providers may have
|
|
25
|
+
* different rules and should compute tradability accordingly.
|
|
26
|
+
*
|
|
27
|
+
* @param params - The parameters for the tradability check.
|
|
28
|
+
* @param params.midPrice - Current market/mid price.
|
|
29
|
+
* @param params.oraclePrice - Current oracle/reference price.
|
|
30
|
+
* @param params.deviationLimit - Max allowed deviation as a decimal fraction
|
|
31
|
+
* (defaults to HyperLiquid's 0.95). A market is untradable when
|
|
32
|
+
* `abs(midPrice - oraclePrice) / oraclePrice > deviationLimit`.
|
|
33
|
+
* @returns `true` when the market is tradable (or when prices are unavailable, so the
|
|
34
|
+
* absence of data never blocks trading); `false` when the deviation exceeds the limit.
|
|
35
|
+
*/
|
|
36
|
+
export declare function isMarketTradable(params: {
|
|
37
|
+
midPrice: number | undefined;
|
|
38
|
+
oraclePrice: number | undefined;
|
|
39
|
+
deviationLimit?: number;
|
|
40
|
+
}): boolean;
|
|
13
41
|
/**
|
|
14
42
|
* HyperLiquid-specific market data structure
|
|
15
43
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketDataTransform.d.mts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,SAAS,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,EAAE,eAAe,CAAC;IACzB,iBAAiB,CAAC,EAAE,gBAAgB,EAAE,CAAC;CACxC,CAAC;AA8GF;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAClC,eAAe,EAAE,
|
|
1
|
+
{"version":3,"file":"marketDataTransform.d.mts","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,eAAe,EACf,UAAU,EACV,oBAAoB,EACrB,2BAAiB;AAClB,OAAO,KAAK,EACV,eAAe,EACf,aAAa,EACb,aAAa,EACb,gBAAgB,EACjB,uCAAmC;AAGpC;;;;;;;;GAQG;AACH,wBAAgB,wBAAwB,CACtC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,EACzC,YAAY,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,GACxC,MAAM,CAeR;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE;IACvC,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,WAAW,EAAE,MAAM,GAAG,SAAS,CAAC;IAChC,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB,GAAG,OAAO,CAuBV;AAED;;GAEG;AACH,MAAM,MAAM,qBAAqB,GAAG;IAClC,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,SAAS,EAAE,aAAa,EAAE,CAAC;IAC3B,OAAO,EAAE,eAAe,CAAC;IACzB,iBAAiB,CAAC,EAAE,gBAAgB,EAAE,CAAC;CACxC,CAAC;AA8GF;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,qBAAqB,EACtC,UAAU,EAAE,oBAAoB,EAChC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,CAAC,EAC7C,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAClC,eAAe,EAAE,CAwGnB;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAC1B,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,oBAAoB,GAC/B,MAAM,CAeR"}
|
|
@@ -28,6 +28,45 @@ export function calculateOpenInterestUSD(openInterest, currentPrice) {
|
|
|
28
28
|
}
|
|
29
29
|
return openInterestNum * priceNum;
|
|
30
30
|
}
|
|
31
|
+
/**
|
|
32
|
+
* Determine whether a market is currently tradable based on how far its market
|
|
33
|
+
* (mid) price has drifted from the oracle (reference) price.
|
|
34
|
+
*
|
|
35
|
+
* HyperLiquid rejects orders when the order price is more than 95% away from the
|
|
36
|
+
* reference price ("Order price cannot be more than 95% away from the reference
|
|
37
|
+
* price"). This most often affects HIP-3 builder-deployed markets, which can become
|
|
38
|
+
* temporarily untradable when their mid price diverges far from the oracle price.
|
|
39
|
+
* Clients use this signal to proactively warn the user (e.g. a "trading unavailable"
|
|
40
|
+
* banner) instead of letting the order fail on submission.
|
|
41
|
+
*
|
|
42
|
+
* Note: the deviation limit is a HyperLiquid protocol rule. Other providers may have
|
|
43
|
+
* different rules and should compute tradability accordingly.
|
|
44
|
+
*
|
|
45
|
+
* @param params - The parameters for the tradability check.
|
|
46
|
+
* @param params.midPrice - Current market/mid price.
|
|
47
|
+
* @param params.oraclePrice - Current oracle/reference price.
|
|
48
|
+
* @param params.deviationLimit - Max allowed deviation as a decimal fraction
|
|
49
|
+
* (defaults to HyperLiquid's 0.95). A market is untradable when
|
|
50
|
+
* `abs(midPrice - oraclePrice) / oraclePrice > deviationLimit`.
|
|
51
|
+
* @returns `true` when the market is tradable (or when prices are unavailable, so the
|
|
52
|
+
* absence of data never blocks trading); `false` when the deviation exceeds the limit.
|
|
53
|
+
*/
|
|
54
|
+
export function isMarketTradable(params) {
|
|
55
|
+
const { midPrice, oraclePrice, deviationLimit = HYPERLIQUID_CONFIG.OraclePriceDeviationLimit, } = params;
|
|
56
|
+
// Without usable prices we cannot assess deviation — default to tradable so missing
|
|
57
|
+
// data never blocks the user. A non-positive price means "no data" (e.g. the transient
|
|
58
|
+
// zero price emitted before the first real tick), not an untradable market.
|
|
59
|
+
if (midPrice === undefined ||
|
|
60
|
+
oraclePrice === undefined ||
|
|
61
|
+
isNaN(midPrice) ||
|
|
62
|
+
isNaN(oraclePrice) ||
|
|
63
|
+
midPrice <= 0 ||
|
|
64
|
+
oraclePrice <= 0) {
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
const deviation = Math.abs(midPrice - oraclePrice) / oraclePrice;
|
|
68
|
+
return deviation <= deviationLimit;
|
|
69
|
+
}
|
|
31
70
|
/**
|
|
32
71
|
* Calculate 24h percentage change
|
|
33
72
|
* Shows -100% when current price is missing but previous price exists
|
|
@@ -144,15 +183,10 @@ export function transformMarketData(hyperLiquidData, formatters, assetMarketType
|
|
|
144
183
|
// HIP-3 markets have a DEX prefix (e.g., xyz:TSLA, flx:GOLD)
|
|
145
184
|
// Crypto markets (HIP-2) don't have a prefix (e.g., BTC, ETH)
|
|
146
185
|
const isHip3 = Boolean(dex);
|
|
147
|
-
// Determine market type from explicit mapping
|
|
148
|
-
|
|
149
|
-
// Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to "New" tab
|
|
150
|
-
// Main DEX crypto also has no marketType
|
|
151
|
-
const explicitMarketType = assetMarketTypes?.[symbol];
|
|
152
|
-
const marketType = explicitMarketType;
|
|
186
|
+
// Determine market type from explicit static mapping
|
|
187
|
+
const marketType = assetMarketTypes?.[symbol];
|
|
153
188
|
// Mark as "new" if it's a HIP-3 market but not explicitly categorized
|
|
154
|
-
|
|
155
|
-
const isNewMarket = isHip3 && !explicitMarketType;
|
|
189
|
+
const isNewMarket = isHip3 && !marketType;
|
|
156
190
|
return {
|
|
157
191
|
symbol,
|
|
158
192
|
name: getHyperLiquidAssetName(symbol, assetNames),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketDataTransform.mjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACxB,2CAAuC;AACxC,OAAO,EAAE,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AAG,CAAC,MAAM,CAAC,EAAE;QAC7D,MAAM,EAAE,UAAU,CAAC,oBAAoB;KACxC,CAAC,CAAC;IAEH,2DAA2D;IAC3D,MAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACtD,OAAO,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC;AAC5E,CAAC","sourcesContent":["/**\n * Market data transformation utilities.\n *\n * Portable: no mobile-specific imports.\n * Formatters are injected via MarketDataFormatters interface.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_CONFIG,\n getHyperLiquidAssetName,\n} from '../constants/hyperLiquidConfig';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\n\n/**\n * Calculate open interest in USD\n * Open interest from HyperLiquid is in contracts/units, not USD\n * To get USD value, multiply by current price\n *\n * @param openInterest - Raw open interest value in contracts/units\n * @param currentPrice - Current price of the asset\n * @returns Open interest in USD, or NaN if invalid\n */\nexport function calculateOpenInterestUSD(\n openInterest: string | number | undefined,\n currentPrice: string | number | undefined,\n): number {\n if (openInterest === undefined || currentPrice === undefined) {\n return NaN;\n }\n\n const openInterestNum =\n typeof openInterest === 'string' ? parseFloat(openInterest) : openInterest;\n const priceNum =\n typeof currentPrice === 'string' ? parseFloat(currentPrice) : currentPrice;\n\n if (isNaN(openInterestNum) || isNaN(priceNum)) {\n return NaN;\n }\n\n return openInterestNum * priceNum;\n}\n\n/**\n * HyperLiquid-specific market data structure\n */\nexport type HyperLiquidMarketData = {\n universe: PerpsUniverse[];\n assetCtxs: PerpsAssetCtx[];\n allMids: AllMidsResponse;\n predictedFundings?: PredictedFunding[];\n};\n\n/**\n * Parameters for calculating 24h percentage change\n */\ntype CalculateChange24hPercentParams = {\n hasCurrentPrice: boolean;\n currentPrice: number;\n prevDayPrice: number;\n};\n\n/**\n * Calculate 24h percentage change\n * Shows -100% when current price is missing but previous price exists\n *\n * @param params - The parameters for calculating the 24h change.\n * @returns The 24h percentage change value.\n */\nfunction calculateChange24hPercent(\n params: CalculateChange24hPercentParams,\n): number {\n const { hasCurrentPrice, currentPrice, prevDayPrice } = params;\n\n if (!hasCurrentPrice) {\n return prevDayPrice > 0 ? -100 : 0;\n }\n\n if (prevDayPrice <= 0) {\n return 0;\n }\n\n return ((currentPrice - prevDayPrice) / prevDayPrice) * 100;\n}\n\n/**\n * Funding data extracted from predicted fundings\n */\ntype FundingData = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n predictedFundingRate?: number;\n};\n\n/**\n * Parameters for extracting funding data\n */\ntype ExtractFundingDataParams = {\n predictedFundings?: PredictedFunding[];\n symbol: string;\n exchangeName?: string;\n};\n\n/**\n * Extract funding data for a symbol from predicted fundings.\n * Looks for specified exchange first, falls back to first available.\n *\n * @param params - Parameters for extracting funding data\n * @param params.predictedFundings - Array of predicted funding data\n * @param params.symbol - Asset symbol to extract funding for\n * @param params.exchangeName - Exchange to prioritize (defaults to HyperLiquid's 'HlPerp')\n * @returns Funding data including next funding time, interval, and predicted rate\n */\nfunction extractFundingData(params: ExtractFundingDataParams): FundingData {\n const {\n predictedFundings,\n symbol,\n exchangeName = HYPERLIQUID_CONFIG.ExchangeName,\n } = params;\n\n const result: FundingData = {};\n\n if (!predictedFundings) {\n return result;\n }\n\n const fundingData = predictedFundings.find(\n ([assetSymbol]) => assetSymbol === symbol,\n );\n\n if (\n !fundingData?.[1] ||\n !Array.isArray(fundingData[1]) ||\n fundingData[1].length === 0\n ) {\n return result;\n }\n\n // Look for specified exchange (e.g., 'HlPerp' for HyperLiquid)\n const targetExchange = fundingData[1].find(\n (exchange: unknown) =>\n Array.isArray(exchange) && exchange[0] === exchangeName,\n );\n\n if (targetExchange?.[1]) {\n result.nextFundingTime = targetExchange[1].nextFundingTime;\n result.fundingIntervalHours = targetExchange[1].fundingIntervalHours;\n result.predictedFundingRate = parseFloat(targetExchange[1].fundingRate);\n return result;\n }\n\n // Fallback to first exchange if target not found\n const firstExchange = fundingData[1][0];\n if (Array.isArray(firstExchange) && firstExchange[1]) {\n result.nextFundingTime = firstExchange[1].nextFundingTime;\n result.fundingIntervalHours = firstExchange[1].fundingIntervalHours;\n }\n\n return result;\n}\n\n/**\n * Transform raw HyperLiquid market data to UI-friendly format\n *\n * @param hyperLiquidData - Raw data from HyperLiquid API\n * @param formatters - Injectable formatters for platform-agnostic formatting\n * @param assetMarketTypes - Optional mapping of asset symbols to market types\n * @param assetNames - Optional mapping of asset symbols to human-readable names.\n * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to\n * their ticker symbol.\n * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\n assetNames?: Record<string, string>,\n): PerpsMarketData[] {\n const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;\n\n return universe.map((asset, index) => {\n const symbol = asset.name;\n const currentPrice = parseFloat(allMids[symbol]);\n\n // Find matching asset context for additional data\n // The assetCtxs array is aligned with universe array by index\n const assetCtx = assetCtxs[index];\n\n // Calculate 24h change\n const prevDayPrice = assetCtx ? parseFloat(assetCtx.prevDayPx) : 0;\n\n // Handle missing current price data\n const hasCurrentPrice = !isNaN(currentPrice);\n const effectiveCurrentPrice = hasCurrentPrice ? currentPrice : 0;\n\n // For dollar change: show $0.00 when current price is missing\n const change24h = hasCurrentPrice\n ? effectiveCurrentPrice - prevDayPrice\n : 0;\n\n // For percentage: show -100% when current price is missing but previous price exists\n const change24hPercent = calculateChange24hPercent({\n hasCurrentPrice,\n currentPrice: effectiveCurrentPrice,\n prevDayPrice,\n });\n\n // Format volume (dayNtlVlm is daily notional volume)\n // If assetCtx is missing or dayNtlVlm is not available, use NaN to indicate missing data\n const volume = assetCtx?.dayNtlVlm ? parseFloat(assetCtx.dayNtlVlm) : NaN;\n\n // Calculate open interest in USD\n const openInterest = calculateOpenInterestUSD(\n assetCtx?.openInterest,\n currentPrice,\n );\n\n // Get current funding rate from assetCtx - this is the actual current funding rate\n let fundingRate: number | undefined;\n\n if (assetCtx && hasProperty(assetCtx, 'funding')) {\n fundingRate = parseFloat(assetCtx.funding);\n }\n\n // Extract funding timing and predicted rate\n const fundingData = extractFundingData({\n predictedFundings,\n symbol,\n });\n\n // Use current funding rate from assetCtx, not predicted\n // The predicted rate is for the next funding period\n if (!fundingRate && fundingData.predictedFundingRate !== undefined) {\n fundingRate = fundingData.predictedFundingRate;\n }\n\n // Extract DEX and base symbol for display\n // e.g., \"flx:TSLA\" → { dex: \"flx\", symbol: \"TSLA\" }\n const { dex } = parseAssetName(symbol);\n const marketSource = dex ?? undefined;\n\n // HIP-3 markets have a DEX prefix (e.g., xyz:TSLA, flx:GOLD)\n // Crypto markets (HIP-2) don't have a prefix (e.g., BTC, ETH)\n const isHip3 = Boolean(dex);\n\n // Determine market type from explicit mapping only\n // Only explicitly mapped HIP-3 markets get a marketType (e.g., 'xyz:GOLD' → 'commodity')\n // Unmapped HIP-3 markets (e.g., 'hyna:BTC') have no marketType - they go to \"New\" tab\n // Main DEX crypto also has no marketType\n const explicitMarketType = assetMarketTypes?.[symbol];\n const marketType: MarketType | undefined = explicitMarketType;\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n // New markets are always HIP-3 (non-crypto) that haven't been assigned a category yet\n const isNewMarket = isHip3 && !explicitMarketType;\n\n return {\n symbol,\n name: getHyperLiquidAssetName(symbol, assetNames),\n maxLeverage: `${asset.maxLeverage}x`,\n price: isNaN(currentPrice)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatPerpsFiat(currentPrice, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: isNaN(change24h)\n ? PERPS_CONSTANTS.ZeroAmountDetailedDisplay\n : formatChange(change24h, formatters),\n change24hPercent: isNaN(change24hPercent)\n ? '0.00%'\n : formatters.formatPercentage(change24hPercent),\n volume: isNaN(volume)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(volume),\n openInterest: isNaN(openInterest)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(openInterest),\n nextFundingTime: fundingData.nextFundingTime,\n fundingIntervalHours: fundingData.fundingIntervalHours,\n fundingRate,\n marketSource,\n marketType,\n isHip3,\n isNewMarket,\n };\n });\n}\n\n/**\n * Format 24h change with sign.\n * Uses more decimal places for smaller amounts to show meaningful precision.\n *\n * @param change - The price change value to format\n * @param formatters - Injectable formatters\n * @returns Formatted change string with sign and dollar symbol\n */\nexport function formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change)) {\n return '$0.00';\n }\n if (change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n\n // Remove $ sign and add it back with proper sign placement\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"marketDataTransform.mjs","sourceRoot":"","sources":["../../src/utils/marketDataTransform.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,WAAW,EAAE,wBAAwB;AAE9C,OAAO,EACL,kBAAkB,EAClB,uBAAuB,EACxB,2CAAuC;AACxC,OAAO,EAAE,eAAe,EAAE,qCAAiC;AAY3D,OAAO,EAAE,cAAc,EAAE,iCAA6B;AAEtD;;;;;;;;GAQG;AACH,MAAM,UAAU,wBAAwB,CACtC,YAAyC,EACzC,YAAyC;IAEzC,IAA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;;;;;;;GAOG;AACH,MAAM,UAAU,YAAY,CAC1B,MAAc,EACd,UAAgC;IAEhC,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QACvC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,IAAI,MAAM,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,SAAS,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;QAC7D,MAAM,EAAE,UAAU,CAAC,oBAAoB;KACxC,CAAC,CAAC;IAEH,2DAA2D;IAC3D,MAAM,kBAAkB,GAAG,SAAS,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;IACtD,OAAO,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC,CAAC,CAAC,KAAK,kBAAkB,EAAE,CAAC;AAC5E,CAAC","sourcesContent":["/**\n * Market data transformation utilities.\n *\n * Portable: no mobile-specific imports.\n * Formatters are injected via MarketDataFormatters interface.\n */\nimport { hasProperty } from '@metamask/utils';\n\nimport {\n HYPERLIQUID_CONFIG,\n getHyperLiquidAssetName,\n} from '../constants/hyperLiquidConfig';\nimport { PERPS_CONSTANTS } from '../constants/perpsConfig';\nimport type {\n PerpsMarketData,\n MarketType,\n MarketDataFormatters,\n} from '../types';\nimport type {\n AllMidsResponse,\n PerpsUniverse,\n PerpsAssetCtx,\n PredictedFunding,\n} from '../types/hyperliquid-types';\nimport { parseAssetName } from './hyperLiquidAdapter';\n\n/**\n * Calculate open interest in USD\n * Open interest from HyperLiquid is in contracts/units, not USD\n * To get USD value, multiply by current price\n *\n * @param openInterest - Raw open interest value in contracts/units\n * @param currentPrice - Current price of the asset\n * @returns Open interest in USD, or NaN if invalid\n */\nexport function calculateOpenInterestUSD(\n openInterest: string | number | undefined,\n currentPrice: string | number | undefined,\n): number {\n if (openInterest === undefined || currentPrice === undefined) {\n return NaN;\n }\n\n const openInterestNum =\n typeof openInterest === 'string' ? parseFloat(openInterest) : openInterest;\n const priceNum =\n typeof currentPrice === 'string' ? parseFloat(currentPrice) : currentPrice;\n\n if (isNaN(openInterestNum) || isNaN(priceNum)) {\n return NaN;\n }\n\n return openInterestNum * priceNum;\n}\n\n/**\n * Determine whether a market is currently tradable based on how far its market\n * (mid) price has drifted from the oracle (reference) price.\n *\n * HyperLiquid rejects orders when the order price is more than 95% away from the\n * reference price (\"Order price cannot be more than 95% away from the reference\n * price\"). This most often affects HIP-3 builder-deployed markets, which can become\n * temporarily untradable when their mid price diverges far from the oracle price.\n * Clients use this signal to proactively warn the user (e.g. a \"trading unavailable\"\n * banner) instead of letting the order fail on submission.\n *\n * Note: the deviation limit is a HyperLiquid protocol rule. Other providers may have\n * different rules and should compute tradability accordingly.\n *\n * @param params - The parameters for the tradability check.\n * @param params.midPrice - Current market/mid price.\n * @param params.oraclePrice - Current oracle/reference price.\n * @param params.deviationLimit - Max allowed deviation as a decimal fraction\n * (defaults to HyperLiquid's 0.95). A market is untradable when\n * `abs(midPrice - oraclePrice) / oraclePrice > deviationLimit`.\n * @returns `true` when the market is tradable (or when prices are unavailable, so the\n * absence of data never blocks trading); `false` when the deviation exceeds the limit.\n */\nexport function isMarketTradable(params: {\n midPrice: number | undefined;\n oraclePrice: number | undefined;\n deviationLimit?: number;\n}): boolean {\n const {\n midPrice,\n oraclePrice,\n deviationLimit = HYPERLIQUID_CONFIG.OraclePriceDeviationLimit,\n } = params;\n\n // Without usable prices we cannot assess deviation — default to tradable so missing\n // data never blocks the user. A non-positive price means \"no data\" (e.g. the transient\n // zero price emitted before the first real tick), not an untradable market.\n if (\n midPrice === undefined ||\n oraclePrice === undefined ||\n isNaN(midPrice) ||\n isNaN(oraclePrice) ||\n midPrice <= 0 ||\n oraclePrice <= 0\n ) {\n return true;\n }\n\n const deviation = Math.abs(midPrice - oraclePrice) / oraclePrice;\n return deviation <= deviationLimit;\n}\n\n/**\n * HyperLiquid-specific market data structure\n */\nexport type HyperLiquidMarketData = {\n universe: PerpsUniverse[];\n assetCtxs: PerpsAssetCtx[];\n allMids: AllMidsResponse;\n predictedFundings?: PredictedFunding[];\n};\n\n/**\n * Parameters for calculating 24h percentage change\n */\ntype CalculateChange24hPercentParams = {\n hasCurrentPrice: boolean;\n currentPrice: number;\n prevDayPrice: number;\n};\n\n/**\n * Calculate 24h percentage change\n * Shows -100% when current price is missing but previous price exists\n *\n * @param params - The parameters for calculating the 24h change.\n * @returns The 24h percentage change value.\n */\nfunction calculateChange24hPercent(\n params: CalculateChange24hPercentParams,\n): number {\n const { hasCurrentPrice, currentPrice, prevDayPrice } = params;\n\n if (!hasCurrentPrice) {\n return prevDayPrice > 0 ? -100 : 0;\n }\n\n if (prevDayPrice <= 0) {\n return 0;\n }\n\n return ((currentPrice - prevDayPrice) / prevDayPrice) * 100;\n}\n\n/**\n * Funding data extracted from predicted fundings\n */\ntype FundingData = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n predictedFundingRate?: number;\n};\n\n/**\n * Parameters for extracting funding data\n */\ntype ExtractFundingDataParams = {\n predictedFundings?: PredictedFunding[];\n symbol: string;\n exchangeName?: string;\n};\n\n/**\n * Extract funding data for a symbol from predicted fundings.\n * Looks for specified exchange first, falls back to first available.\n *\n * @param params - Parameters for extracting funding data\n * @param params.predictedFundings - Array of predicted funding data\n * @param params.symbol - Asset symbol to extract funding for\n * @param params.exchangeName - Exchange to prioritize (defaults to HyperLiquid's 'HlPerp')\n * @returns Funding data including next funding time, interval, and predicted rate\n */\nfunction extractFundingData(params: ExtractFundingDataParams): FundingData {\n const {\n predictedFundings,\n symbol,\n exchangeName = HYPERLIQUID_CONFIG.ExchangeName,\n } = params;\n\n const result: FundingData = {};\n\n if (!predictedFundings) {\n return result;\n }\n\n const fundingData = predictedFundings.find(\n ([assetSymbol]) => assetSymbol === symbol,\n );\n\n if (\n !fundingData?.[1] ||\n !Array.isArray(fundingData[1]) ||\n fundingData[1].length === 0\n ) {\n return result;\n }\n\n // Look for specified exchange (e.g., 'HlPerp' for HyperLiquid)\n const targetExchange = fundingData[1].find(\n (exchange: unknown) =>\n Array.isArray(exchange) && exchange[0] === exchangeName,\n );\n\n if (targetExchange?.[1]) {\n result.nextFundingTime = targetExchange[1].nextFundingTime;\n result.fundingIntervalHours = targetExchange[1].fundingIntervalHours;\n result.predictedFundingRate = parseFloat(targetExchange[1].fundingRate);\n return result;\n }\n\n // Fallback to first exchange if target not found\n const firstExchange = fundingData[1][0];\n if (Array.isArray(firstExchange) && firstExchange[1]) {\n result.nextFundingTime = firstExchange[1].nextFundingTime;\n result.fundingIntervalHours = firstExchange[1].fundingIntervalHours;\n }\n\n return result;\n}\n\n/**\n * Transform raw HyperLiquid market data to UI-friendly format\n *\n * @param hyperLiquidData - Raw data from HyperLiquid API\n * @param formatters - Injectable formatters for platform-agnostic formatting\n * @param assetMarketTypes - Optional mapping of asset symbols to market types\n * @param assetNames - Optional mapping of asset symbols to human-readable names.\n * Defaults to the bundled HYPERLIQUID_ASSET_NAMES; unmapped assets fall back to\n * their ticker symbol.\n * @returns Transformed market data ready for UI consumption\n */\nexport function transformMarketData(\n hyperLiquidData: HyperLiquidMarketData,\n formatters: MarketDataFormatters,\n assetMarketTypes?: Record<string, MarketType>,\n assetNames?: Record<string, string>,\n): PerpsMarketData[] {\n const { universe, assetCtxs, allMids, predictedFundings } = hyperLiquidData;\n\n return universe.map((asset, index) => {\n const symbol = asset.name;\n const currentPrice = parseFloat(allMids[symbol]);\n\n // Find matching asset context for additional data\n // The assetCtxs array is aligned with universe array by index\n const assetCtx = assetCtxs[index];\n\n // Calculate 24h change\n const prevDayPrice = assetCtx ? parseFloat(assetCtx.prevDayPx) : 0;\n\n // Handle missing current price data\n const hasCurrentPrice = !isNaN(currentPrice);\n const effectiveCurrentPrice = hasCurrentPrice ? currentPrice : 0;\n\n // For dollar change: show $0.00 when current price is missing\n const change24h = hasCurrentPrice\n ? effectiveCurrentPrice - prevDayPrice\n : 0;\n\n // For percentage: show -100% when current price is missing but previous price exists\n const change24hPercent = calculateChange24hPercent({\n hasCurrentPrice,\n currentPrice: effectiveCurrentPrice,\n prevDayPrice,\n });\n\n // Format volume (dayNtlVlm is daily notional volume)\n // If assetCtx is missing or dayNtlVlm is not available, use NaN to indicate missing data\n const volume = assetCtx?.dayNtlVlm ? parseFloat(assetCtx.dayNtlVlm) : NaN;\n\n // Calculate open interest in USD\n const openInterest = calculateOpenInterestUSD(\n assetCtx?.openInterest,\n currentPrice,\n );\n\n // Get current funding rate from assetCtx - this is the actual current funding rate\n let fundingRate: number | undefined;\n\n if (assetCtx && hasProperty(assetCtx, 'funding')) {\n fundingRate = parseFloat(assetCtx.funding);\n }\n\n // Extract funding timing and predicted rate\n const fundingData = extractFundingData({\n predictedFundings,\n symbol,\n });\n\n // Use current funding rate from assetCtx, not predicted\n // The predicted rate is for the next funding period\n if (!fundingRate && fundingData.predictedFundingRate !== undefined) {\n fundingRate = fundingData.predictedFundingRate;\n }\n\n // Extract DEX and base symbol for display\n // e.g., \"flx:TSLA\" → { dex: \"flx\", symbol: \"TSLA\" }\n const { dex } = parseAssetName(symbol);\n const marketSource = dex ?? undefined;\n\n // HIP-3 markets have a DEX prefix (e.g., xyz:TSLA, flx:GOLD)\n // Crypto markets (HIP-2) don't have a prefix (e.g., BTC, ETH)\n const isHip3 = Boolean(dex);\n\n // Determine market type from explicit static mapping\n const marketType: MarketType | undefined = assetMarketTypes?.[symbol];\n\n // Mark as \"new\" if it's a HIP-3 market but not explicitly categorized\n const isNewMarket = isHip3 && !marketType;\n\n return {\n symbol,\n name: getHyperLiquidAssetName(symbol, assetNames),\n maxLeverage: `${asset.maxLeverage}x`,\n price: isNaN(currentPrice)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatPerpsFiat(currentPrice, {\n ranges: formatters.priceRangesUniversal,\n }),\n change24h: isNaN(change24h)\n ? PERPS_CONSTANTS.ZeroAmountDetailedDisplay\n : formatChange(change24h, formatters),\n change24hPercent: isNaN(change24hPercent)\n ? '0.00%'\n : formatters.formatPercentage(change24hPercent),\n volume: isNaN(volume)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(volume),\n openInterest: isNaN(openInterest)\n ? PERPS_CONSTANTS.FallbackPriceDisplay\n : formatters.formatVolume(openInterest),\n nextFundingTime: fundingData.nextFundingTime,\n fundingIntervalHours: fundingData.fundingIntervalHours,\n fundingRate,\n marketSource,\n marketType,\n isHip3,\n isNewMarket,\n };\n });\n}\n\n/**\n * Format 24h change with sign.\n * Uses more decimal places for smaller amounts to show meaningful precision.\n *\n * @param change - The price change value to format\n * @param formatters - Injectable formatters\n * @returns Formatted change string with sign and dollar symbol\n */\nexport function formatChange(\n change: number,\n formatters: MarketDataFormatters,\n): string {\n if (isNaN(change) || !isFinite(change)) {\n return '$0.00';\n }\n if (change === 0) {\n return '$0.00';\n }\n\n const formatted = formatters.formatPerpsFiat(Math.abs(change), {\n ranges: formatters.priceRangesUniversal,\n });\n\n // Remove $ sign and add it back with proper sign placement\n const valueWithoutDollar = formatted.replace('$', '');\n return change > 0 ? `+$${valueWithoutDollar}` : `-$${valueWithoutDollar}`;\n}\n"]}
|
|
@@ -33,11 +33,36 @@ function fieldRank(value, query) {
|
|
|
33
33
|
}
|
|
34
34
|
return null;
|
|
35
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Rank an array of keyword strings against a normalized query.
|
|
38
|
+
* Returns the best (lowest) rank found across all keywords, or null.
|
|
39
|
+
*
|
|
40
|
+
* @param keywords - Array of keyword strings; may be undefined.
|
|
41
|
+
* @param query - Already trimmed, lower-cased, non-empty query.
|
|
42
|
+
* @returns The best match tier across all keywords, or null when none match.
|
|
43
|
+
*/
|
|
44
|
+
function keywordsRank(keywords, query) {
|
|
45
|
+
if (!keywords || keywords.length === 0) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
let best = null;
|
|
49
|
+
for (const keyword of keywords) {
|
|
50
|
+
const rank = fieldRank(keyword, query);
|
|
51
|
+
if (rank === MarketMatchRank.Exact) {
|
|
52
|
+
return rank;
|
|
53
|
+
}
|
|
54
|
+
if (rank !== null && (best === null || rank < best)) {
|
|
55
|
+
best = rank;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return best;
|
|
59
|
+
}
|
|
36
60
|
/**
|
|
37
61
|
* Compute the best (lowest) relevance rank for a market against a search query,
|
|
38
|
-
* considering
|
|
62
|
+
* considering its ticker symbol, human-readable name, and optional keywords
|
|
63
|
+
* from Terminal API metadata.
|
|
39
64
|
*
|
|
40
|
-
* @param market - Market to score (uses `symbol` and `
|
|
65
|
+
* @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).
|
|
41
66
|
* @param searchQuery - User search text (trimmed/cased internally).
|
|
42
67
|
* @returns The match rank, or null when the market does not match (or the query
|
|
43
68
|
* is empty/whitespace).
|
|
@@ -50,6 +75,7 @@ function getMarketMatchRank(market, searchQuery) {
|
|
|
50
75
|
const ranks = [
|
|
51
76
|
fieldRank(market.symbol, query),
|
|
52
77
|
fieldRank(market.name, query),
|
|
78
|
+
keywordsRank(market.keywords, query),
|
|
53
79
|
].filter((rank) => rank !== null);
|
|
54
80
|
return ranks.length > 0 ? Math.min(...ranks) : null;
|
|
55
81
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketSearch.cjs","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":";;;AAkBA;;GAEG;AACH,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,uDAAS,CAAA;IACT,yDAAU,CAAA;IACV,+DAAa,CAAA;AACf,CAAC,EAJW,eAAe,+BAAf,eAAe,QAI1B;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAChB,KAAyB,EACzB,KAAa;IAEb,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC;IAC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,OAA0B,EAC1B,WAAmB;IAEnB,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,MAAM,KAAK,GAAG,WAAW,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC;IAE/C,MAAM,OAAO,GAAyD,EAAE,CAAC;IACzE,OAAO,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE;QACzB,MAAM,IAAI,GAAG,kBAAkB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;QAC/C,IAAI,IAAI,KAAK,IAAI,EAAE,CAAC;YAClB,OAAO,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACjC,CAAC;IACH,CAAC,CAAC,CAAC;IAEH,8EAA8E;IAC9E,8DAA8D;IAC9D,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;IACxC,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;AAC9C,CAAC;AArBD,gDAqBC","sourcesContent":["/**\n * Market search ranking (TAT-2413).\n *\n * Provisional, standalone helper layered on the same match semantics as\n * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol\n * and human-readable name). It adds the one thing `filterMarketsByQuery` does\n * not: relevance ranking — exact matches first, then prefix, then substring;\n * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope\n * for v1).\n *\n * Kept in its own file so it can be promoted or relocated later without touching\n * the shared `marketUtils`. A market matches here (rank !== null) iff\n * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.\n *\n * Portable: no platform-specific imports.\n */\nimport type { PerpsMarketData } from '../types';\n\n/**\n * Relevance tier for a market/query match. Lower values sort first.\n */\nexport enum MarketMatchRank {\n Exact = 0,\n Prefix = 1,\n Substring = 2,\n}\n\n/**\n * Rank a single field value against a normalized query.\n *\n * @param value - Field value (e.g. symbol or name); may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The match tier, or null when the field does not match.\n */\nfunction fieldRank(\n value: string | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!value) {\n return null;\n }\n const normalized = value.toLowerCase();\n if (normalized === query) {\n return MarketMatchRank.Exact;\n }\n if (normalized.startsWith(query)) {\n return MarketMatchRank.Prefix;\n }\n if (normalized.includes(query)) {\n return MarketMatchRank.Substring;\n }\n return null;\n}\n\n/**\n * Rank an array of keyword strings against a normalized query.\n * Returns the best (lowest) rank found across all keywords, or null.\n *\n * @param keywords - Array of keyword strings; may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The best match tier across all keywords, or null when none match.\n */\nfunction keywordsRank(\n keywords: string[] | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!keywords || keywords.length === 0) {\n return null;\n }\n let best: MarketMatchRank | null = null;\n for (const keyword of keywords) {\n const rank = fieldRank(keyword, query);\n if (rank === MarketMatchRank.Exact) {\n return rank;\n }\n if (rank !== null && (best === null || rank < best)) {\n best = rank;\n }\n }\n return best;\n}\n\n/**\n * Compute the best (lowest) relevance rank for a market against a search query,\n * considering its ticker symbol, human-readable name, and optional keywords\n * from Terminal API metadata.\n *\n * @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).\n * @param searchQuery - User search text (trimmed/cased internally).\n * @returns The match rank, or null when the market does not match (or the query\n * is empty/whitespace).\n */\nexport function getMarketMatchRank(\n market: Pick<PerpsMarketData, 'symbol' | 'name' | 'keywords'>,\n searchQuery: string,\n): MarketMatchRank | null {\n if (!searchQuery?.trim()) {\n return null;\n }\n const query = searchQuery.toLowerCase().trim();\n const ranks = [\n fieldRank(market.symbol, query),\n fieldRank(market.name, query),\n keywordsRank(market.keywords, query),\n ].filter((rank): rank is MarketMatchRank => rank !== null);\n\n return ranks.length > 0 ? Math.min(...ranks) : null;\n}\n\n/**\n * Filter and rank markets by a search query, matching the human-readable name or\n * ticker symbol. Exact matches sort first, then prefix, then substring; markets\n * sharing a rank keep their input order (stable). An empty/whitespace query\n * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.\n *\n * @param markets - Markets to search.\n * @param searchQuery - User search text.\n * @returns Matching markets ordered by relevance.\n */\nexport function rankMarketsByQuery(\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] {\n if (!searchQuery?.trim()) {\n return markets;\n }\n const query = searchQuery.toLowerCase().trim();\n\n const matches: { market: PerpsMarketData; rank: MarketMatchRank }[] = [];\n markets.forEach((market) => {\n const rank = getMarketMatchRank(market, query);\n if (rank !== null) {\n matches.push({ market, rank });\n }\n });\n\n // Stable sort by rank only; Array.prototype.sort is stable in modern engines,\n // so equal-rank markets retain their original relative order.\n matches.sort((a, b) => a.rank - b.rank);\n return matches.map((match) => match.market);\n}\n"]}
|
|
@@ -25,14 +25,15 @@ export declare enum MarketMatchRank {
|
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* Compute the best (lowest) relevance rank for a market against a search query,
|
|
28
|
-
* considering
|
|
28
|
+
* considering its ticker symbol, human-readable name, and optional keywords
|
|
29
|
+
* from Terminal API metadata.
|
|
29
30
|
*
|
|
30
|
-
* @param market - Market to score (uses `symbol` and `
|
|
31
|
+
* @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).
|
|
31
32
|
* @param searchQuery - User search text (trimmed/cased internally).
|
|
32
33
|
* @returns The match rank, or null when the market does not match (or the query
|
|
33
34
|
* is empty/whitespace).
|
|
34
35
|
*/
|
|
35
|
-
export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name'>, searchQuery: string): MarketMatchRank | null;
|
|
36
|
+
export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name' | 'keywords'>, searchQuery: string): MarketMatchRank | null;
|
|
36
37
|
/**
|
|
37
38
|
* Filter and rank markets by a search query, matching the human-readable name or
|
|
38
39
|
* ticker symbol. Exact matches sort first, then prefix, then substring; markets
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketSearch.d.cts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;
|
|
1
|
+
{"version":3,"file":"marketSearch.d.cts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;AAyDD;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC,EAC7D,WAAW,EAAE,MAAM,GAClB,eAAe,GAAG,IAAI,CAYxB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,eAAe,EAAE,EAC1B,WAAW,EAAE,MAAM,GAClB,eAAe,EAAE,CAkBnB"}
|
|
@@ -25,14 +25,15 @@ export declare enum MarketMatchRank {
|
|
|
25
25
|
}
|
|
26
26
|
/**
|
|
27
27
|
* Compute the best (lowest) relevance rank for a market against a search query,
|
|
28
|
-
* considering
|
|
28
|
+
* considering its ticker symbol, human-readable name, and optional keywords
|
|
29
|
+
* from Terminal API metadata.
|
|
29
30
|
*
|
|
30
|
-
* @param market - Market to score (uses `symbol` and `
|
|
31
|
+
* @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).
|
|
31
32
|
* @param searchQuery - User search text (trimmed/cased internally).
|
|
32
33
|
* @returns The match rank, or null when the market does not match (or the query
|
|
33
34
|
* is empty/whitespace).
|
|
34
35
|
*/
|
|
35
|
-
export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name'>, searchQuery: string): MarketMatchRank | null;
|
|
36
|
+
export declare function getMarketMatchRank(market: Pick<PerpsMarketData, 'symbol' | 'name' | 'keywords'>, searchQuery: string): MarketMatchRank | null;
|
|
36
37
|
/**
|
|
37
38
|
* Filter and rank markets by a search query, matching the human-readable name or
|
|
38
39
|
* ticker symbol. Exact matches sort first, then prefix, then substring; markets
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketSearch.d.mts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;
|
|
1
|
+
{"version":3,"file":"marketSearch.d.mts","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,OAAO,KAAK,EAAE,eAAe,EAAE,2BAAiB;AAEhD;;GAEG;AACH,oBAAY,eAAe;IACzB,KAAK,IAAI;IACT,MAAM,IAAI;IACV,SAAS,IAAI;CACd;AAyDD;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,MAAM,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC,EAC7D,WAAW,EAAE,MAAM,GAClB,eAAe,GAAG,IAAI,CAYxB;AAED;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,eAAe,EAAE,EAC1B,WAAW,EAAE,MAAM,GAClB,eAAe,EAAE,CAkBnB"}
|
|
@@ -30,11 +30,36 @@ function fieldRank(value, query) {
|
|
|
30
30
|
}
|
|
31
31
|
return null;
|
|
32
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Rank an array of keyword strings against a normalized query.
|
|
35
|
+
* Returns the best (lowest) rank found across all keywords, or null.
|
|
36
|
+
*
|
|
37
|
+
* @param keywords - Array of keyword strings; may be undefined.
|
|
38
|
+
* @param query - Already trimmed, lower-cased, non-empty query.
|
|
39
|
+
* @returns The best match tier across all keywords, or null when none match.
|
|
40
|
+
*/
|
|
41
|
+
function keywordsRank(keywords, query) {
|
|
42
|
+
if (!keywords || keywords.length === 0) {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
let best = null;
|
|
46
|
+
for (const keyword of keywords) {
|
|
47
|
+
const rank = fieldRank(keyword, query);
|
|
48
|
+
if (rank === MarketMatchRank.Exact) {
|
|
49
|
+
return rank;
|
|
50
|
+
}
|
|
51
|
+
if (rank !== null && (best === null || rank < best)) {
|
|
52
|
+
best = rank;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return best;
|
|
56
|
+
}
|
|
33
57
|
/**
|
|
34
58
|
* Compute the best (lowest) relevance rank for a market against a search query,
|
|
35
|
-
* considering
|
|
59
|
+
* considering its ticker symbol, human-readable name, and optional keywords
|
|
60
|
+
* from Terminal API metadata.
|
|
36
61
|
*
|
|
37
|
-
* @param market - Market to score (uses `symbol` and `
|
|
62
|
+
* @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).
|
|
38
63
|
* @param searchQuery - User search text (trimmed/cased internally).
|
|
39
64
|
* @returns The match rank, or null when the market does not match (or the query
|
|
40
65
|
* is empty/whitespace).
|
|
@@ -47,6 +72,7 @@ export function getMarketMatchRank(market, searchQuery) {
|
|
|
47
72
|
const ranks = [
|
|
48
73
|
fieldRank(market.symbol, query),
|
|
49
74
|
fieldRank(market.name, query),
|
|
75
|
+
keywordsRank(market.keywords, query),
|
|
50
76
|
].filter((rank) => rank !== null);
|
|
51
77
|
return ranks.length > 0 ? Math.min(...ranks) : null;
|
|
52
78
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketSearch.mjs","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,uDAAS,CAAA;IACT,yDAAU,CAAA;IACV,+DAAa,CAAA;AACf,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAChB,KAAyB,EACzB,KAAa;IAEb,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IACvC,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;QACzB,OAAO,eAAe,CAAC,KAAK,CAAC;IAC/B,CAAC;IACD,IAAI,UAAU,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,eAAe,CAAC,MAAM,CAAC;IAChC,CAAC;IACD,IAAI,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,eAAe,CAAC,SAAS,CAAC;IACnC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED
|
|
1
|
+
{"version":3,"file":"marketSearch.mjs","sourceRoot":"","sources":["../../src/utils/marketSearch.ts"],"names":[],"mappings":"AAkBA;;GAEG;AACH,MAAM,CAAN,IAAY,eAIX;AAJD,WAAY,eAAe;IACzB,uDAAS,CAAA;IACT,yDAAU,CAAA;IACV,+DAAa,CAAA;AACf,CAAC,EAJW,eAAe,KAAf,eAAe,QAI1B;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAChB,KAAyB,EACzB,KAAa;IAEb,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,OAAO,IAAI,CAAC;IACd,CAAC;IACD,MAAM,UAAU,GAAG,KAAK,CAAC,WAAW,EAAE,CAAC;IACvC,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antics as\n * `filterMarketsByQuery` (case-insensitive substring on a market's ticker symbol\n * and human-readable name). It adds the one thing `filterMarketsByQuery` does\n * not: relevance ranking — exact matches first, then prefix, then substring;\n * ties keep their input order (stable). No fuzzy/phonetic matching (out of scope\n * for v1).\n *\n * Kept in its own file so it can be promoted or relocated later without touching\n * the shared `marketUtils`. A market matches here (rank !== null) iff\n * `filterMarketsByQuery` would include it, so the two stay behaviorally aligned.\n *\n * Portable: no platform-specific imports.\n */\nimport type { PerpsMarketData } from '../types';\n\n/**\n * Relevance tier for a market/query match. Lower values sort first.\n */\nexport enum MarketMatchRank {\n Exact = 0,\n Prefix = 1,\n Substring = 2,\n}\n\n/**\n * Rank a single field value against a normalized query.\n *\n * @param value - Field value (e.g. symbol or name); may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The match tier, or null when the field does not match.\n */\nfunction fieldRank(\n value: string | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!value) {\n return null;\n }\n const normalized = value.toLowerCase();\n if (normalized === query) {\n return MarketMatchRank.Exact;\n }\n if (normalized.startsWith(query)) {\n return MarketMatchRank.Prefix;\n }\n if (normalized.includes(query)) {\n return MarketMatchRank.Substring;\n }\n return null;\n}\n\n/**\n * Rank an array of keyword strings against a normalized query.\n * Returns the best (lowest) rank found across all keywords, or null.\n *\n * @param keywords - Array of keyword strings; may be undefined.\n * @param query - Already trimmed, lower-cased, non-empty query.\n * @returns The best match tier across all keywords, or null when none match.\n */\nfunction keywordsRank(\n keywords: string[] | undefined,\n query: string,\n): MarketMatchRank | null {\n if (!keywords || keywords.length === 0) {\n return null;\n }\n let best: MarketMatchRank | null = null;\n for (const keyword of keywords) {\n const rank = fieldRank(keyword, query);\n if (rank === MarketMatchRank.Exact) {\n return rank;\n }\n if (rank !== null && (best === null || rank < best)) {\n best = rank;\n }\n }\n return best;\n}\n\n/**\n * Compute the best (lowest) relevance rank for a market against a search query,\n * considering its ticker symbol, human-readable name, and optional keywords\n * from Terminal API metadata.\n *\n * @param market - Market to score (uses `symbol`, `name`, and optional `keywords`).\n * @param searchQuery - User search text (trimmed/cased internally).\n * @returns The match rank, or null when the market does not match (or the query\n * is empty/whitespace).\n */\nexport function getMarketMatchRank(\n market: Pick<PerpsMarketData, 'symbol' | 'name' | 'keywords'>,\n searchQuery: string,\n): MarketMatchRank | null {\n if (!searchQuery?.trim()) {\n return null;\n }\n const query = searchQuery.toLowerCase().trim();\n const ranks = [\n fieldRank(market.symbol, query),\n fieldRank(market.name, query),\n keywordsRank(market.keywords, query),\n ].filter((rank): rank is MarketMatchRank => rank !== null);\n\n return ranks.length > 0 ? Math.min(...ranks) : null;\n}\n\n/**\n * Filter and rank markets by a search query, matching the human-readable name or\n * ticker symbol. Exact matches sort first, then prefix, then substring; markets\n * sharing a rank keep their input order (stable). An empty/whitespace query\n * returns the markets unchanged (no filtering), matching `filterMarketsByQuery`.\n *\n * @param markets - Markets to search.\n * @param searchQuery - User search text.\n * @returns Matching markets ordered by relevance.\n */\nexport function rankMarketsByQuery(\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] {\n if (!searchQuery?.trim()) {\n return markets;\n }\n const query = searchQuery.toLowerCase().trim();\n\n const matches: { market: PerpsMarketData; rank: MarketMatchRank }[] = [];\n markets.forEach((market) => {\n const rank = getMarketMatchRank(market, query);\n if (rank !== null) {\n matches.push({ market, rank });\n }\n });\n\n // Stable sort by rank only; Array.prototype.sort is stable in modern engines,\n // so equal-rank markets retain their original relative order.\n matches.sort((a, b) => a.rank - b.rank);\n return matches.map((match) => match.market);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/perps-controller",
|
|
3
|
-
"version": "8.
|
|
3
|
+
"version": "8.3.0-preview-a8fd340",
|
|
4
4
|
"description": "Controller for perpetual trading functionality in MetaMask",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|
|
@@ -100,6 +100,7 @@
|
|
|
100
100
|
"@metamask/base-controller": "^9.1.0",
|
|
101
101
|
"@metamask/controller-utils": "^12.3.0",
|
|
102
102
|
"@metamask/messenger": "^1.2.0",
|
|
103
|
+
"@metamask/superstruct": "^3.1.0",
|
|
103
104
|
"@metamask/utils": "^11.11.0",
|
|
104
105
|
"@nktkas/hyperliquid": "^0.32.2",
|
|
105
106
|
"bignumber.js": "^9.1.2",
|
|
@@ -107,7 +108,7 @@
|
|
|
107
108
|
"uuid": "^8.3.2"
|
|
108
109
|
},
|
|
109
110
|
"devDependencies": {
|
|
110
|
-
"@metamask/account-tree-controller": "^7.5.
|
|
111
|
+
"@metamask/account-tree-controller": "^7.5.3",
|
|
111
112
|
"@metamask/auto-changelog": "^6.1.0",
|
|
112
113
|
"@metamask/geolocation-controller": "^0.1.3",
|
|
113
114
|
"@metamask/keyring-controller": "^27.1.0",
|