@metamask-previews/perps-controller 25.0.0-preview-2be370e → 25.0.0-preview-c785ff081
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 +14 -6
- package/dist/PerpsController.d.ts.map +1 -1
- package/dist/PerpsController.js +71 -8
- package/dist/PerpsController.js.map +1 -1
- package/dist/constants/eventNames.d.ts +6 -9
- package/dist/constants/eventNames.d.ts.map +1 -1
- package/dist/constants/eventNames.js +9 -11
- package/dist/constants/eventNames.js.map +1 -1
- package/dist/constants/perpsConfig.d.ts +8 -1
- package/dist/constants/perpsConfig.d.ts.map +1 -1
- package/dist/constants/perpsConfig.js +8 -2
- package/dist/constants/perpsConfig.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
- package/dist/providers/HyperLiquidProvider.js +2 -2
- package/dist/providers/HyperLiquidProvider.js.map +1 -1
- package/dist/providers/LighterProvider.d.ts.map +1 -1
- package/dist/providers/LighterProvider.js +8 -6
- package/dist/providers/LighterProvider.js.map +1 -1
- package/dist/selectors.d.ts +15 -5
- package/dist/selectors.d.ts.map +1 -1
- package/dist/selectors.js +23 -5
- package/dist/selectors.js.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.d.ts.map +1 -1
- package/dist/services/AggregatedOrderBookConnection.js +8 -10
- package/dist/services/AggregatedOrderBookConnection.js.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
- package/dist/services/HyperLiquidSubscriptionService.js +20 -13
- package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
- package/dist/services/MarketDataService.d.ts +5 -2
- package/dist/services/MarketDataService.d.ts.map +1 -1
- package/dist/services/MarketDataService.js +12 -2
- package/dist/services/MarketDataService.js.map +1 -1
- package/dist/types/index.d.ts +4 -3
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/hyperLiquidAdapter.d.ts.map +1 -1
- package/dist/utils/hyperLiquidAdapter.js +2 -13
- package/dist/utils/hyperLiquidAdapter.js.map +1 -1
- package/dist/utils/marketDataTransform.d.ts.map +1 -1
- package/dist/utils/marketDataTransform.js +5 -8
- package/dist/utils/marketDataTransform.js.map +1 -1
- package/dist/utils/marketUtils.d.ts +9 -0
- package/dist/utils/marketUtils.d.ts.map +1 -1
- package/dist/utils/marketUtils.js +12 -0
- package/dist/utils/marketUtils.js.map +1 -1
- package/dist/utils/priceDeviation.d.ts +9 -6
- package/dist/utils/priceDeviation.d.ts.map +1 -1
- package/dist/utils/priceDeviation.js +17 -26
- package/dist/utils/priceDeviation.js.map +1 -1
- package/dist/utils/pricePrecision.d.ts +14 -2
- package/dist/utils/pricePrecision.d.ts.map +1 -1
- package/dist/utils/pricePrecision.js +31 -10
- package/dist/utils/pricePrecision.js.map +1 -1
- package/docs/architecture.md +17 -17
- package/docs/client-contract.md +14 -10
- package/docs/contracts/events.md +4 -2
- package/docs/contracts/feature-flags.md +4 -4
- package/docs/venues/hyperliquid/trading-rules.md +2 -2
- package/docs/venues/lighter/capabilities.md +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"marketUtils.js","sourceRoot":"","sources":["../../src/utils/marketUtils.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,MAAM,uBAAuB,GAAG,aAAa,CAAC;AAC9C,MAAM,kBAAkB,GAAG,QAAQ,CAAC;AAIpC;;;;;GAKG;AACH,MAAM,UAAU,yBAAyB,CAAC,QAGzC;IACC,MAAM,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,QAAQ,CAAC;IAC3C,OAAO;QACL,GAAG,CAAC,SAAS,KAAK,IAAI,IAAI,SAAS,KAAK,SAAS,IAAI,EAAE,SAAS,EAAE,CAAC;QACnE,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,MAAM,CACnB,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QACjD,MAAM,CAAC,IAAI,EAAE,WAAW,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAClD,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type {\n GetMarketDataWithPricesParams,\n GroupedPerpsMarket,\n MarketInfo,\n MarketTypeFilter,\n PerpsMarketData,\n PerpsProviderType,\n} from '../types/index.js';\nimport type { CandleData, CandleStick } from '../types/perps-types.js';\nimport { sortMarkets } from './sortMarkets.js';\n\nconst SAVED_MARKET_KEY_PREFIX = 'market-key:';\nconst SAVED_VENUE_PREFIX = 'venue:';\n\ntype MarketIdentity = Pick<MarketInfo, 'marketKey' | 'priceScale'>;\n\n/**\n * Copy the optional cross-venue identity fields of a snapshot row.\n *\n * @param identity - The snapshot row's optional identity.\n * @returns The identity fields supplied by the backend.\n */\nexport function getSnapshotMarketIdentity(identity: {\n marketKey?: string | null;\n priceScale?: number | null;\n}): MarketIdentity {\n const { marketKey, priceScale } = identity;\n return {\n ...(marketKey !== null && marketKey !== undefined && { marketKey }),\n ...(priceScale !== null && priceScale !== undefined && { priceScale }),\n };\n}\n\nfunction getUnscaledMarketKey(market: MarketIdentity): string | undefined {\n const { marketKey, priceScale } = market;\n return marketKey && priceScale === 1 ? marketKey : undefined;\n}\n\n/**\n * Group rows that share a backend market key and explicitly have unit scale.\n * The first venue supplies the display data and retains its execution symbol.\n * Only a grouped row carries `marketKey`; an ungrouped row omits it, so it is\n * saved by venue and symbol and never as a backend key.\n *\n * @param markets - Venue market rows whose source provider IDs are preserved.\n * @param defaultProvider - Preferred venue for ordering and untagged rows.\n * @returns Display rows in first-seen market order, with the original venue rows.\n */\nexport function groupMarketsByMarketKey(\n markets: readonly PerpsMarketData[],\n defaultProvider: PerpsProviderType,\n): GroupedPerpsMarket[] {\n const groups: Pick<GroupedPerpsMarket, 'marketKey' | 'rowId' | 'venues'>[] =\n [];\n const byKey = new Map<string, PerpsMarketData[]>();\n for (const market of markets) {\n const marketKey = getUnscaledMarketKey(market);\n const venues = marketKey ? byKey.get(marketKey) : undefined;\n if (venues) {\n venues.push(market);\n } else {\n const firstVenue = [market];\n groups.push({\n marketKey,\n rowId: marketKey\n ? `market:${marketKey}`\n : `venue:${market.providerId ?? defaultProvider}:${market.symbol}`,\n venues: firstVenue,\n });\n if (marketKey) {\n byKey.set(marketKey, firstVenue);\n }\n }\n }\n\n return groups.map(({ marketKey, rowId, venues }) => {\n const preferred = venues.findIndex(\n (market) => (market.providerId ?? defaultProvider) === defaultProvider,\n );\n if (preferred > 0) {\n const [primary] = venues.splice(preferred, 1);\n venues.unshift(primary);\n }\n const { marketKey: _venueKey, ...display } = venues[0];\n return { ...display, ...(marketKey && { marketKey }), rowId, venues };\n });\n}\n\n/**\n * Encode a saved market reference without changing the persisted string format.\n * An explicit key can have the same text as a legacy venue symbol.\n *\n * @param symbol - The venue's trading symbol.\n * @param marketKey - The market key when saving a grouped row.\n * @returns A reference for persistence in a watchlist or recently viewed list.\n */\nexport function toSavedPerpsMarketReference(\n symbol: string,\n marketKey?: string,\n): string {\n return marketKey ? `${SAVED_MARKET_KEY_PREFIX}${marketKey}` : symbol;\n}\n\nfunction getVenueReference(\n symbol: string,\n provider: PerpsProviderType | undefined,\n legacyProvider: PerpsProviderType,\n): string {\n return provider && provider !== legacyProvider\n ? `${SAVED_VENUE_PREFIX}${provider}:${symbol}`\n : symbol;\n}\n\n/**\n * Match an explicit key and the saved venue entries of its confirmed rows.\n * Without a key, a row on the legacy venue is saved by its symbol and a row\n * from another venue as `venue:<provider>:<symbol>`, so it never collides with\n * a legacy symbol. With a key, those venue entries of each tagged group row\n * with the same unit-scale key are aliases, so an entry saved before the row\n * grouped still matches. Uses the same legacy-provider default as\n * `resolveSavedPerpsMarkets`.\n *\n * @param symbol - The displayed venue's symbol.\n * @param marketKey - Explicit backend key from a unit-scale row.\n * @param venues - The group's original venue rows.\n * @param legacyProvider - Venue that owned the saved symbols before grouping.\n * @returns The new reference and its venue aliases, when available.\n */\nexport function getPerpsWatchlistReferences(\n symbol: string,\n marketKey?: string,\n venues?: readonly PerpsMarketData[],\n legacyProvider: PerpsProviderType = 'hyperliquid',\n): [reference: string, ...legacyAliases: string[]] {\n if (!marketKey) {\n const provider = venues?.find(\n (venue) => venue.symbol === symbol,\n )?.providerId;\n return [getVenueReference(symbol, provider, legacyProvider)];\n }\n const aliases = (venues ?? [])\n .filter(\n (venue) =>\n venue.providerId !== undefined &&\n getUnscaledMarketKey(venue) === marketKey,\n )\n .map((venue) =>\n getVenueReference(venue.symbol, venue.providerId, legacyProvider),\n );\n return [toSavedPerpsMarketReference(symbol, marketKey), ...aliases];\n}\n\n/**\n * Resolve saved entries to executable venue rows. Legacy symbols keep their\n * original venue when available. Venue references open only that venue's row.\n * Explicit keys follow the current default venue.\n *\n * @param references - Strings read from the watchlist or recently viewed list.\n * @param markets - Current ungrouped market rows.\n * @param defaultProvider - Preferred venue for a market key and for untagged direct rows.\n * @param legacyProvider - Venue that owned the saved symbols before grouping.\n * @returns The resolved venue rows in saved order.\n */\nexport function resolveSavedPerpsMarkets(\n references: readonly string[],\n markets: readonly PerpsMarketData[],\n defaultProvider: PerpsProviderType,\n legacyProvider: PerpsProviderType = 'hyperliquid',\n): PerpsMarketData[] {\n const symbols = new Map<string, PerpsMarketData>();\n const venueSymbols = new Map<string, PerpsMarketData>();\n const backendKeys = new Map<string, PerpsMarketData>();\n for (const market of markets) {\n const provider = market.providerId ?? defaultProvider;\n if (provider === legacyProvider) {\n symbols.set(market.symbol, market);\n }\n venueSymbols.set(\n `${SAVED_VENUE_PREFIX}${provider}:${market.symbol}`,\n market,\n );\n const backendKey = getUnscaledMarketKey(market);\n if (\n backendKey &&\n (!backendKeys.has(backendKey) || provider === defaultProvider)\n ) {\n backendKeys.set(backendKey, market);\n }\n }\n\n const resolved = new Set<PerpsMarketData>();\n for (const reference of references) {\n let market: PerpsMarketData | undefined;\n if (reference.startsWith(SAVED_MARKET_KEY_PREFIX)) {\n market = backendKeys.get(reference.slice(SAVED_MARKET_KEY_PREFIX.length));\n } else if (reference.startsWith(SAVED_VENUE_PREFIX)) {\n market = venueSymbols.get(reference);\n } else {\n market = symbols.get(reference);\n }\n if (market) {\n resolved.add(market);\n }\n }\n return [...resolved];\n}\n\nexport function clonePerpsMarketData(\n markets: PerpsMarketData[],\n): PerpsMarketData[] {\n return markets.map((market) => ({\n ...market,\n ...(market.keywords && { keywords: [...market.keywords] }),\n ...(market.tags && { tags: [...market.tags] }),\n ...(market.categories && { categories: [...market.categories] }),\n ...(market.trend && {\n trend: market.trend.map(([timestamp, price]): [number, string] => [\n timestamp,\n price,\n ]),\n }),\n }));\n}\n\n// ============================================================================\n// Market category classification (pure functions)\n// No service dependencies — pure data transformations that can be tested and\n// reused independently. `matchesCategory` and `getMarketTypeFilter` share the\n// same category model.\n// ============================================================================\n\n/**\n * Whether a market is a HIP-3 (non-main-DEX) market. A `marketSource` DEX id\n * marks a HIP-3 market even when the `isHip3` flag is unset (e.g. partial route\n * params), so both signals are checked. Used as the single HIP-3 signal so the\n * classifiers stay consistent.\n *\n * @param market - The market data to test.\n * @returns True if the market is HIP-3.\n */\nexport const isHip3Market = (\n market: Pick<PerpsMarketData, 'isHip3' | 'marketSource'>,\n): boolean => Boolean(market.isHip3) || Boolean(market.marketSource);\n\n/**\n * Returns true when a market matches the given UI filter category.\n *\n * @param market - The market data to test.\n * @param category - The filter category to test against.\n * @returns Whether the market matches the category.\n */\nexport function matchesCategory(\n market: PerpsMarketData,\n category: MarketTypeFilter,\n): boolean {\n switch (category) {\n case 'all':\n return true;\n case 'new':\n // Explicitly flagged, or an uncategorized HIP-3 market (kept in sync with\n // getMarketTypeFilter's 'new' bucket).\n return (\n market.isNewMarket === true ||\n (isHip3Market(market) && market.marketType === undefined)\n );\n case 'crypto':\n return getMarketTypeFilter(market) === 'crypto';\n case 'memecoin':\n // Derived category: a crypto market that carries the 'memecoin' tag.\n // Aligned with the 'crypto' case above so tagged main-DEX markets\n // still match when their marketType is unset (the common\n // provider-sourced shape prior to Terminal enrichment). Overlaps\n // with 'crypto' by design — memecoins appear under both pills.\n return (\n getMarketTypeFilter(market) === 'crypto' &&\n (market.tags?.includes('memecoin') ?? false)\n );\n default:\n // Every other filter is a 1:1 data-model category match.\n return market.marketType !== undefined && market.marketType === category;\n }\n}\n\n/**\n * Resolve the user-facing category bucket for a market — one of `crypto`,\n * `stock`, `pre-ipo`, `index`, `etf`, `commodity`, `forex`, or `new`. Data-model\n * categories map 1:1. A market with no data-model category is `crypto` when it\n * is main-DEX, or `new` when it is an uncategorized HIP-3 market (`isHip3`, or a\n * `marketSource` DEX id when `isHip3` is unset, e.g. minimal route params).\n * Never returns the `all` sentinel.\n *\n * Centralised as the single source of truth so consumers (e.g. category\n * shortcuts, related markets) share one classification instead of re-deriving\n * it per client and drifting as new categories are added.\n *\n * @param market - The market data to classify.\n * @returns The market type filter bucket.\n */\nexport function getMarketTypeFilter(market: PerpsMarketData): MarketTypeFilter {\n const { marketType } = market;\n if (marketType) {\n return marketType;\n }\n // No data-model category: an uncategorized HIP-3 market is the 'new' bucket;\n // otherwise it's a main-DEX crypto market.\n return isHip3Market(market) ? 'new' : 'crypto';\n}\n\n/**\n * Applies optional category filtering, sorting, and limit to a list of markets.\n *\n * @param markets - Source market array.\n * @param params - Optional filter/sort/limit params.\n * @returns Filtered, sorted, and/or sliced market array.\n */\nexport function applyMarketFilters(\n markets: PerpsMarketData[],\n params?: GetMarketDataWithPricesParams,\n): PerpsMarketData[] {\n let result = markets;\n\n if (params?.categories?.length) {\n const { categories } = params;\n result = result.filter((market) =>\n // A market is included if it matches ANY of the requested categories.\n categories.some((category) => matchesCategory(market, category)),\n );\n }\n\n if (params?.excludeSymbols?.length) {\n const excluded = new Set(params.excludeSymbols);\n result = result.filter((market) => !excluded.has(market.symbol));\n }\n\n if (params?.sortBy) {\n result = sortMarkets({\n markets: result,\n sortBy: params.sortBy,\n direction: params.direction,\n });\n }\n\n if (params?.limit !== undefined) {\n result = result.slice(0, params.limit);\n }\n\n return result;\n}\n\n/**\n * Maximum length for market filter patterns (prevents DoS attacks)\n */\nexport const MAX_MARKET_PATTERN_LENGTH = 100;\n\nexport type MarketPatternMatcher = RegExp | string;\n\nexport type CompiledMarketPattern = {\n pattern: string;\n matcher: MarketPatternMatcher;\n};\n\nexport const escapeRegex = (str: string): string =>\n str.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n\nexport const validateMarketPattern = (pattern: string): boolean => {\n if (!pattern || pattern.trim().length === 0) {\n throw new Error('Market pattern cannot be empty');\n }\n\n const normalizedPattern = pattern.trim();\n\n if (normalizedPattern.length > MAX_MARKET_PATTERN_LENGTH) {\n throw new Error(\n `Market pattern exceeds maximum length (${MAX_MARKET_PATTERN_LENGTH} chars): ${normalizedPattern}`,\n );\n }\n\n const dangerousChars = /[\\\\()[\\]{}^$+?.|]/u;\n if (dangerousChars.test(normalizedPattern)) {\n throw new Error(\n `Market pattern contains invalid regex characters: ${normalizedPattern}`,\n );\n }\n\n const validPattern = /^[a-zA-Z0-9:_\\-*]+$/u;\n if (!validPattern.test(normalizedPattern)) {\n throw new Error(\n `Market pattern contains invalid characters: ${normalizedPattern}`,\n );\n }\n\n return true;\n};\n\nexport const compileMarketPattern = (pattern: string): MarketPatternMatcher => {\n const normalizedPattern = pattern.trim();\n validateMarketPattern(normalizedPattern);\n\n if (normalizedPattern.endsWith(':*')) {\n const prefix = normalizedPattern.slice(0, -2);\n return new RegExp(`^${escapeRegex(prefix)}:`, 'u');\n }\n\n if (!normalizedPattern.includes(':')) {\n return new RegExp(`^${escapeRegex(normalizedPattern)}:`, 'u');\n }\n\n return normalizedPattern;\n};\n\nexport const matchesMarketPattern = (\n symbol: string,\n matcher: MarketPatternMatcher,\n): boolean => {\n if (typeof matcher === 'string') {\n return symbol === matcher;\n }\n\n return matcher.test(symbol);\n};\n\nexport const shouldIncludeMarket = (\n symbol: string,\n dex: string | null,\n hip3Enabled: boolean,\n compiledEnabledPatterns: CompiledMarketPattern[],\n compiledBlockedPatterns: CompiledMarketPattern[],\n): boolean => {\n if (dex === null) {\n return true;\n }\n\n if (!hip3Enabled) {\n return false;\n }\n\n if (compiledEnabledPatterns.length > 0) {\n const whitelisted = compiledEnabledPatterns.some(({ matcher }) =>\n matchesMarketPattern(symbol, matcher),\n );\n if (!whitelisted) {\n return false;\n }\n }\n\n if (compiledBlockedPatterns.length === 0) {\n return true;\n }\n\n const blacklisted = compiledBlockedPatterns.some(({ matcher }) =>\n matchesMarketPattern(symbol, matcher),\n );\n\n return !blacklisted;\n};\n\nexport const getPerpsDisplaySymbol = (symbol: string): string => {\n if (!symbol || typeof symbol !== 'string') {\n return symbol;\n }\n\n const colonIndex = symbol.indexOf(':');\n if (colonIndex > 0 && colonIndex < symbol.length - 1) {\n return symbol.substring(colonIndex + 1);\n }\n\n return symbol;\n};\n\nexport const getPerpsDexFromSymbol = (symbol: string): string | null => {\n if (!symbol || typeof symbol !== 'string') {\n return null;\n }\n\n const colonIndex = symbol.indexOf(':');\n if (colonIndex > 0 && colonIndex < symbol.length - 1) {\n return symbol.substring(0, colonIndex);\n }\n\n return null;\n};\n\ntype FundingCountdownParams = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n};\n\nexport const calculateFundingCountdown = (\n params?: FundingCountdownParams,\n): string => {\n const now = new Date();\n const nowMs = now.getTime();\n\n if (params?.nextFundingTime && params.nextFundingTime > nowMs) {\n const msUntilFunding = params.nextFundingTime - nowMs;\n const hoursUntilFunding = msUntilFunding / (1000 * 60 * 60);\n\n if (hoursUntilFunding <= 1.1) {\n const totalSeconds = Math.floor(msUntilFunding / 1000);\n\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n const formattedHours = String(hours).padStart(2, '0');\n const formattedMinutes = String(minutes).padStart(2, '0');\n const formattedSeconds = String(seconds).padStart(2, '0');\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;\n }\n }\n\n const utcMinutes = now.getUTCMinutes();\n const utcSeconds = now.getUTCSeconds();\n\n const minutesUntilNextHour = 59 - utcMinutes;\n const secondsUntilNextHour = 60 - utcSeconds;\n\n const finalSeconds = secondsUntilNextHour === 60 ? 0 : secondsUntilNextHour;\n const finalMinutes =\n secondsUntilNextHour === 60\n ? minutesUntilNextHour + 1\n : minutesUntilNextHour;\n\n const finalHours = finalMinutes === 60 ? 1 : 0;\n const adjustedMinutes = finalMinutes === 60 ? 0 : finalMinutes;\n\n const formattedHours = String(finalHours).padStart(2, '0');\n const formattedMinutes = String(adjustedMinutes).padStart(2, '0');\n const formattedSeconds = String(finalSeconds).padStart(2, '0');\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;\n};\n\nexport const calculate24hHighLow = (\n candleData: CandleData | null,\n): { high: number; low: number } => {\n if (!candleData?.candles || candleData.candles.length === 0) {\n return { high: 0, low: 0 };\n }\n\n const now = Date.now();\n const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;\n\n let last24hCandles = candleData.candles.filter(\n (candle: CandleStick) => candle.time >= twentyFourHoursAgo,\n );\n\n if (last24hCandles.length === 0) {\n last24hCandles = [...candleData.candles];\n }\n\n const highs = last24hCandles.map((candle: CandleStick) =>\n parseFloat(candle.high),\n );\n const lows = last24hCandles.map((candle: CandleStick) =>\n parseFloat(candle.low),\n );\n\n return {\n high: Math.max(...highs),\n low: Math.min(...lows),\n };\n};\n\nexport const filterMarketsByQuery = (\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] => {\n if (!searchQuery?.trim()) {\n return markets;\n }\n\n const lowerQuery = searchQuery.toLowerCase().trim();\n\n return markets.filter(\n (market) =>\n market.symbol?.toLowerCase().includes(lowerQuery) ||\n market.name?.toLowerCase().includes(lowerQuery),\n );\n};\n"]}
|
|
1
|
+
{"version":3,"file":"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EAAE,CACvD,UAAU,CAAC,MAAM,CAAC,IAAI,CAAC,CACxB,CAAC;IACF,MAAM,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC,CAAC,MAAmB,EAAE,EAAE,CACtD,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CACvB,CAAC;IAEF,OAAO;QACL,IAAI,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACxB,GAAG,EAAE,IAAI,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC;KACvB,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAClC,OAA0B,EAC1B,WAAmB,EACA,EAAE;IACrB,IAAI,CAAC,WAAW,EAAE,IAAI,EAAE,EAAE,CAAC;QACzB,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,MAAM,UAAU,GAAG,WAAW,CAAC,WAAW,EAAE,CAAC,IAAI,EAAE,CAAC;IAEpD,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC;QACjD,MAAM,CAAC,IAAI,EAAE,WAAW,EAAE,CAAC,QAAQ,CAAC,UAAU,CAAC,CAClD,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import type {\n GetMarketDataWithPricesParams,\n GroupedPerpsMarket,\n MarketInfo,\n MarketTypeFilter,\n PerpsMarketData,\n PerpsProviderType,\n} from '../types/index.js';\nimport type { CandleData, CandleStick } from '../types/perps-types.js';\nimport { sortMarkets } from './sortMarkets.js';\n\nconst SAVED_MARKET_KEY_PREFIX = 'market-key:';\nconst SAVED_VENUE_PREFIX = 'venue:';\n\ntype MarketIdentity = Pick<MarketInfo, 'marketKey' | 'priceScale'>;\n\n/**\n * Copy the optional cross-venue identity fields of a snapshot row.\n *\n * @param identity - The snapshot row's optional identity.\n * @returns The identity fields supplied by the backend.\n */\nexport function getSnapshotMarketIdentity(identity: {\n marketKey?: string | null;\n priceScale?: number | null;\n}): MarketIdentity {\n const { marketKey, priceScale } = identity;\n return {\n ...(marketKey !== null && marketKey !== undefined && { marketKey }),\n ...(priceScale !== null && priceScale !== undefined && { priceScale }),\n };\n}\n\nfunction getUnscaledMarketKey(market: MarketIdentity): string | undefined {\n const { marketKey, priceScale } = market;\n return marketKey && priceScale === 1 ? marketKey : undefined;\n}\n\n/**\n * Group rows that share a backend market key and explicitly have unit scale.\n * The first venue supplies the display data and retains its execution symbol.\n * Only a grouped row carries `marketKey`; an ungrouped row omits it, so it is\n * saved by venue and symbol and never as a backend key.\n *\n * @param markets - Venue market rows whose source provider IDs are preserved.\n * @param defaultProvider - Preferred venue for ordering and untagged rows.\n * @returns Display rows in first-seen market order, with the original venue rows.\n */\nexport function groupMarketsByMarketKey(\n markets: readonly PerpsMarketData[],\n defaultProvider: PerpsProviderType,\n): GroupedPerpsMarket[] {\n const groups: Pick<GroupedPerpsMarket, 'marketKey' | 'rowId' | 'venues'>[] =\n [];\n const byKey = new Map<string, PerpsMarketData[]>();\n for (const market of markets) {\n const marketKey = getUnscaledMarketKey(market);\n const venues = marketKey ? byKey.get(marketKey) : undefined;\n if (venues) {\n venues.push(market);\n } else {\n const firstVenue = [market];\n groups.push({\n marketKey,\n rowId: marketKey\n ? `market:${marketKey}`\n : `venue:${market.providerId ?? defaultProvider}:${market.symbol}`,\n venues: firstVenue,\n });\n if (marketKey) {\n byKey.set(marketKey, firstVenue);\n }\n }\n }\n\n return groups.map(({ marketKey, rowId, venues }) => {\n const preferred = venues.findIndex(\n (market) => (market.providerId ?? defaultProvider) === defaultProvider,\n );\n if (preferred > 0) {\n const [primary] = venues.splice(preferred, 1);\n venues.unshift(primary);\n }\n const { marketKey: _venueKey, ...display } = venues[0];\n return { ...display, ...(marketKey && { marketKey }), rowId, venues };\n });\n}\n\n/**\n * Encode a saved market reference without changing the persisted string format.\n * An explicit key can have the same text as a legacy venue symbol.\n *\n * @param symbol - The venue's trading symbol.\n * @param marketKey - The market key when saving a grouped row.\n * @returns A reference for persistence in a watchlist or recently viewed list.\n */\nexport function toSavedPerpsMarketReference(\n symbol: string,\n marketKey?: string,\n): string {\n return marketKey ? `${SAVED_MARKET_KEY_PREFIX}${marketKey}` : symbol;\n}\n\n/**\n * Whether every client can read a saved reference. Mobile and Extension match\n * saved entries by venue symbol, so `market-key:` and `venue:` references stay\n * in local state and are never written to shared storage.\n *\n * @param reference - A saved watchlist entry.\n * @returns True for a bare venue symbol.\n */\nexport function isSharedPerpsMarketReference(reference: string): boolean {\n return (\n !reference.startsWith(SAVED_MARKET_KEY_PREFIX) &&\n !reference.startsWith(SAVED_VENUE_PREFIX)\n );\n}\n\nfunction getVenueReference(\n symbol: string,\n provider: PerpsProviderType | undefined,\n legacyProvider: PerpsProviderType,\n): string {\n return provider && provider !== legacyProvider\n ? `${SAVED_VENUE_PREFIX}${provider}:${symbol}`\n : symbol;\n}\n\n/**\n * Match an explicit key and the saved venue entries of its confirmed rows.\n * Without a key, a row on the legacy venue is saved by its symbol and a row\n * from another venue as `venue:<provider>:<symbol>`, so it never collides with\n * a legacy symbol. With a key, those venue entries of each tagged group row\n * with the same unit-scale key are aliases, so an entry saved before the row\n * grouped still matches. Uses the same legacy-provider default as\n * `resolveSavedPerpsMarkets`.\n *\n * @param symbol - The displayed venue's symbol.\n * @param marketKey - Explicit backend key from a unit-scale row.\n * @param venues - The group's original venue rows.\n * @param legacyProvider - Venue that owned the saved symbols before grouping.\n * @returns The new reference and its venue aliases, when available.\n */\nexport function getPerpsWatchlistReferences(\n symbol: string,\n marketKey?: string,\n venues?: readonly PerpsMarketData[],\n legacyProvider: PerpsProviderType = 'hyperliquid',\n): [reference: string, ...legacyAliases: string[]] {\n if (!marketKey) {\n const provider = venues?.find(\n (venue) => venue.symbol === symbol,\n )?.providerId;\n return [getVenueReference(symbol, provider, legacyProvider)];\n }\n const aliases = (venues ?? [])\n .filter(\n (venue) =>\n venue.providerId !== undefined &&\n getUnscaledMarketKey(venue) === marketKey,\n )\n .map((venue) =>\n getVenueReference(venue.symbol, venue.providerId, legacyProvider),\n );\n return [toSavedPerpsMarketReference(symbol, marketKey), ...aliases];\n}\n\n/**\n * Resolve saved entries to executable venue rows. Legacy symbols keep their\n * original venue when available. Venue references open only that venue's row.\n * Explicit keys follow the current default venue.\n *\n * @param references - Strings read from the watchlist or recently viewed list.\n * @param markets - Current ungrouped market rows.\n * @param defaultProvider - Preferred venue for a market key and for untagged direct rows.\n * @param legacyProvider - Venue that owned the saved symbols before grouping.\n * @returns The resolved venue rows in saved order.\n */\nexport function resolveSavedPerpsMarkets(\n references: readonly string[],\n markets: readonly PerpsMarketData[],\n defaultProvider: PerpsProviderType,\n legacyProvider: PerpsProviderType = 'hyperliquid',\n): PerpsMarketData[] {\n const symbols = new Map<string, PerpsMarketData>();\n const venueSymbols = new Map<string, PerpsMarketData>();\n const backendKeys = new Map<string, PerpsMarketData>();\n for (const market of markets) {\n const provider = market.providerId ?? defaultProvider;\n if (provider === legacyProvider) {\n symbols.set(market.symbol, market);\n }\n venueSymbols.set(\n `${SAVED_VENUE_PREFIX}${provider}:${market.symbol}`,\n market,\n );\n const backendKey = getUnscaledMarketKey(market);\n if (\n backendKey &&\n (!backendKeys.has(backendKey) || provider === defaultProvider)\n ) {\n backendKeys.set(backendKey, market);\n }\n }\n\n const resolved = new Set<PerpsMarketData>();\n for (const reference of references) {\n let market: PerpsMarketData | undefined;\n if (reference.startsWith(SAVED_MARKET_KEY_PREFIX)) {\n market = backendKeys.get(reference.slice(SAVED_MARKET_KEY_PREFIX.length));\n } else if (reference.startsWith(SAVED_VENUE_PREFIX)) {\n market = venueSymbols.get(reference);\n } else {\n market = symbols.get(reference);\n }\n if (market) {\n resolved.add(market);\n }\n }\n return [...resolved];\n}\n\nexport function clonePerpsMarketData(\n markets: PerpsMarketData[],\n): PerpsMarketData[] {\n return markets.map((market) => ({\n ...market,\n ...(market.keywords && { keywords: [...market.keywords] }),\n ...(market.tags && { tags: [...market.tags] }),\n ...(market.categories && { categories: [...market.categories] }),\n ...(market.trend && {\n trend: market.trend.map(([timestamp, price]): [number, string] => [\n timestamp,\n price,\n ]),\n }),\n }));\n}\n\n// ============================================================================\n// Market category classification (pure functions)\n// No service dependencies — pure data transformations that can be tested and\n// reused independently. `matchesCategory` and `getMarketTypeFilter` share the\n// same category model.\n// ============================================================================\n\n/**\n * Whether a market is a HIP-3 (non-main-DEX) market. A `marketSource` DEX id\n * marks a HIP-3 market even when the `isHip3` flag is unset (e.g. partial route\n * params), so both signals are checked. Used as the single HIP-3 signal so the\n * classifiers stay consistent.\n *\n * @param market - The market data to test.\n * @returns True if the market is HIP-3.\n */\nexport const isHip3Market = (\n market: Pick<PerpsMarketData, 'isHip3' | 'marketSource'>,\n): boolean => Boolean(market.isHip3) || Boolean(market.marketSource);\n\n/**\n * Returns true when a market matches the given UI filter category.\n *\n * @param market - The market data to test.\n * @param category - The filter category to test against.\n * @returns Whether the market matches the category.\n */\nexport function matchesCategory(\n market: PerpsMarketData,\n category: MarketTypeFilter,\n): boolean {\n switch (category) {\n case 'all':\n return true;\n case 'new':\n // Explicitly flagged, or an uncategorized HIP-3 market (kept in sync with\n // getMarketTypeFilter's 'new' bucket).\n return (\n market.isNewMarket === true ||\n (isHip3Market(market) && market.marketType === undefined)\n );\n case 'crypto':\n return getMarketTypeFilter(market) === 'crypto';\n case 'memecoin':\n // Derived category: a crypto market that carries the 'memecoin' tag.\n // Aligned with the 'crypto' case above so tagged main-DEX markets\n // still match when their marketType is unset (the common\n // provider-sourced shape prior to Terminal enrichment). Overlaps\n // with 'crypto' by design — memecoins appear under both pills.\n return (\n getMarketTypeFilter(market) === 'crypto' &&\n (market.tags?.includes('memecoin') ?? false)\n );\n default:\n // Every other filter is a 1:1 data-model category match.\n return market.marketType !== undefined && market.marketType === category;\n }\n}\n\n/**\n * Resolve the user-facing category bucket for a market — one of `crypto`,\n * `stock`, `pre-ipo`, `index`, `etf`, `commodity`, `forex`, or `new`. Data-model\n * categories map 1:1. A market with no data-model category is `crypto` when it\n * is main-DEX, or `new` when it is an uncategorized HIP-3 market (`isHip3`, or a\n * `marketSource` DEX id when `isHip3` is unset, e.g. minimal route params).\n * Never returns the `all` sentinel.\n *\n * Centralised as the single source of truth so consumers (e.g. category\n * shortcuts, related markets) share one classification instead of re-deriving\n * it per client and drifting as new categories are added.\n *\n * @param market - The market data to classify.\n * @returns The market type filter bucket.\n */\nexport function getMarketTypeFilter(market: PerpsMarketData): MarketTypeFilter {\n const { marketType } = market;\n if (marketType) {\n return marketType;\n }\n // No data-model category: an uncategorized HIP-3 market is the 'new' bucket;\n // otherwise it's a main-DEX crypto market.\n return isHip3Market(market) ? 'new' : 'crypto';\n}\n\n/**\n * Applies optional category filtering, sorting, and limit to a list of markets.\n *\n * @param markets - Source market array.\n * @param params - Optional filter/sort/limit params.\n * @returns Filtered, sorted, and/or sliced market array.\n */\nexport function applyMarketFilters(\n markets: PerpsMarketData[],\n params?: GetMarketDataWithPricesParams,\n): PerpsMarketData[] {\n let result = markets;\n\n if (params?.categories?.length) {\n const { categories } = params;\n result = result.filter((market) =>\n // A market is included if it matches ANY of the requested categories.\n categories.some((category) => matchesCategory(market, category)),\n );\n }\n\n if (params?.excludeSymbols?.length) {\n const excluded = new Set(params.excludeSymbols);\n result = result.filter((market) => !excluded.has(market.symbol));\n }\n\n if (params?.sortBy) {\n result = sortMarkets({\n markets: result,\n sortBy: params.sortBy,\n direction: params.direction,\n });\n }\n\n if (params?.limit !== undefined) {\n result = result.slice(0, params.limit);\n }\n\n return result;\n}\n\n/**\n * Maximum length for market filter patterns (prevents DoS attacks)\n */\nexport const MAX_MARKET_PATTERN_LENGTH = 100;\n\nexport type MarketPatternMatcher = RegExp | string;\n\nexport type CompiledMarketPattern = {\n pattern: string;\n matcher: MarketPatternMatcher;\n};\n\nexport const escapeRegex = (str: string): string =>\n str.replace(/[.*+?^${}()|[\\]\\\\]/gu, '\\\\$&');\n\nexport const validateMarketPattern = (pattern: string): boolean => {\n if (!pattern || pattern.trim().length === 0) {\n throw new Error('Market pattern cannot be empty');\n }\n\n const normalizedPattern = pattern.trim();\n\n if (normalizedPattern.length > MAX_MARKET_PATTERN_LENGTH) {\n throw new Error(\n `Market pattern exceeds maximum length (${MAX_MARKET_PATTERN_LENGTH} chars): ${normalizedPattern}`,\n );\n }\n\n const dangerousChars = /[\\\\()[\\]{}^$+?.|]/u;\n if (dangerousChars.test(normalizedPattern)) {\n throw new Error(\n `Market pattern contains invalid regex characters: ${normalizedPattern}`,\n );\n }\n\n const validPattern = /^[a-zA-Z0-9:_\\-*]+$/u;\n if (!validPattern.test(normalizedPattern)) {\n throw new Error(\n `Market pattern contains invalid characters: ${normalizedPattern}`,\n );\n }\n\n return true;\n};\n\nexport const compileMarketPattern = (pattern: string): MarketPatternMatcher => {\n const normalizedPattern = pattern.trim();\n validateMarketPattern(normalizedPattern);\n\n if (normalizedPattern.endsWith(':*')) {\n const prefix = normalizedPattern.slice(0, -2);\n return new RegExp(`^${escapeRegex(prefix)}:`, 'u');\n }\n\n if (!normalizedPattern.includes(':')) {\n return new RegExp(`^${escapeRegex(normalizedPattern)}:`, 'u');\n }\n\n return normalizedPattern;\n};\n\nexport const matchesMarketPattern = (\n symbol: string,\n matcher: MarketPatternMatcher,\n): boolean => {\n if (typeof matcher === 'string') {\n return symbol === matcher;\n }\n\n return matcher.test(symbol);\n};\n\nexport const shouldIncludeMarket = (\n symbol: string,\n dex: string | null,\n hip3Enabled: boolean,\n compiledEnabledPatterns: CompiledMarketPattern[],\n compiledBlockedPatterns: CompiledMarketPattern[],\n): boolean => {\n if (dex === null) {\n return true;\n }\n\n if (!hip3Enabled) {\n return false;\n }\n\n if (compiledEnabledPatterns.length > 0) {\n const whitelisted = compiledEnabledPatterns.some(({ matcher }) =>\n matchesMarketPattern(symbol, matcher),\n );\n if (!whitelisted) {\n return false;\n }\n }\n\n if (compiledBlockedPatterns.length === 0) {\n return true;\n }\n\n const blacklisted = compiledBlockedPatterns.some(({ matcher }) =>\n matchesMarketPattern(symbol, matcher),\n );\n\n return !blacklisted;\n};\n\nexport const getPerpsDisplaySymbol = (symbol: string): string => {\n if (!symbol || typeof symbol !== 'string') {\n return symbol;\n }\n\n const colonIndex = symbol.indexOf(':');\n if (colonIndex > 0 && colonIndex < symbol.length - 1) {\n return symbol.substring(colonIndex + 1);\n }\n\n return symbol;\n};\n\nexport const getPerpsDexFromSymbol = (symbol: string): string | null => {\n if (!symbol || typeof symbol !== 'string') {\n return null;\n }\n\n const colonIndex = symbol.indexOf(':');\n if (colonIndex > 0 && colonIndex < symbol.length - 1) {\n return symbol.substring(0, colonIndex);\n }\n\n return null;\n};\n\ntype FundingCountdownParams = {\n nextFundingTime?: number;\n fundingIntervalHours?: number;\n};\n\nexport const calculateFundingCountdown = (\n params?: FundingCountdownParams,\n): string => {\n const now = new Date();\n const nowMs = now.getTime();\n\n if (params?.nextFundingTime && params.nextFundingTime > nowMs) {\n const msUntilFunding = params.nextFundingTime - nowMs;\n const hoursUntilFunding = msUntilFunding / (1000 * 60 * 60);\n\n if (hoursUntilFunding <= 1.1) {\n const totalSeconds = Math.floor(msUntilFunding / 1000);\n\n const hours = Math.floor(totalSeconds / 3600);\n const minutes = Math.floor((totalSeconds % 3600) / 60);\n const seconds = totalSeconds % 60;\n\n const formattedHours = String(hours).padStart(2, '0');\n const formattedMinutes = String(minutes).padStart(2, '0');\n const formattedSeconds = String(seconds).padStart(2, '0');\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;\n }\n }\n\n const utcMinutes = now.getUTCMinutes();\n const utcSeconds = now.getUTCSeconds();\n\n const minutesUntilNextHour = 59 - utcMinutes;\n const secondsUntilNextHour = 60 - utcSeconds;\n\n const finalSeconds = secondsUntilNextHour === 60 ? 0 : secondsUntilNextHour;\n const finalMinutes =\n secondsUntilNextHour === 60\n ? minutesUntilNextHour + 1\n : minutesUntilNextHour;\n\n const finalHours = finalMinutes === 60 ? 1 : 0;\n const adjustedMinutes = finalMinutes === 60 ? 0 : finalMinutes;\n\n const formattedHours = String(finalHours).padStart(2, '0');\n const formattedMinutes = String(adjustedMinutes).padStart(2, '0');\n const formattedSeconds = String(finalSeconds).padStart(2, '0');\n\n return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;\n};\n\nexport const calculate24hHighLow = (\n candleData: CandleData | null,\n): { high: number; low: number } => {\n if (!candleData?.candles || candleData.candles.length === 0) {\n return { high: 0, low: 0 };\n }\n\n const now = Date.now();\n const twentyFourHoursAgo = now - 24 * 60 * 60 * 1000;\n\n let last24hCandles = candleData.candles.filter(\n (candle: CandleStick) => candle.time >= twentyFourHoursAgo,\n );\n\n if (last24hCandles.length === 0) {\n last24hCandles = [...candleData.candles];\n }\n\n const highs = last24hCandles.map((candle: CandleStick) =>\n parseFloat(candle.high),\n );\n const lows = last24hCandles.map((candle: CandleStick) =>\n parseFloat(candle.low),\n );\n\n return {\n high: Math.max(...highs),\n low: Math.min(...lows),\n };\n};\n\nexport const filterMarketsByQuery = (\n markets: PerpsMarketData[],\n searchQuery: string,\n): PerpsMarketData[] => {\n if (!searchQuery?.trim()) {\n return markets;\n }\n\n const lowerQuery = searchQuery.toLowerCase().trim();\n\n return markets.filter(\n (market) =>\n market.symbol?.toLowerCase().includes(lowerQuery) ||\n market.name?.toLowerCase().includes(lowerQuery),\n );\n};\n"]}
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Prices a venue accepts around a reference price under a deviation limit
|
|
3
|
-
* such as `PerpsOrderLimits.maxOraclePriceDeviation`:
|
|
4
|
-
* times the reference
|
|
3
|
+
* such as `PerpsOrderLimits.maxOraclePriceDeviation`: up to `maxDeviation`
|
|
4
|
+
* times the reference away from it on either side, so a price `p` is inside
|
|
5
|
+
* when `|p - reference| / reference <= maxDeviation`. HyperLiquid's rule
|
|
6
|
+
* ("Order price cannot be more than 95% away from the reference price") and
|
|
7
|
+
* `isMarketTradable` use this band. The lower bound never goes below 0.
|
|
8
|
+
* Bounds are computed in exact decimals, so `1 - 0.95` is exactly 0.05.
|
|
5
9
|
*
|
|
6
10
|
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
7
|
-
* @param maxDeviation - Deviation limit as a fraction
|
|
11
|
+
* @param maxDeviation - Deviation limit as a positive fraction.
|
|
8
12
|
* @returns The inclusive band, or undefined when either input is unusable.
|
|
9
13
|
*/
|
|
10
14
|
export declare function getPriceDeviationBand(referencePrice: number, maxDeviation: number): {
|
|
@@ -13,10 +17,9 @@ export declare function getPriceDeviationBand(referencePrice: number, maxDeviati
|
|
|
13
17
|
} | undefined;
|
|
14
18
|
/**
|
|
15
19
|
* Whether a price is outside the inclusive band {@link getPriceDeviationBand}
|
|
16
|
-
* returns
|
|
17
|
-
* reference divided by it.
|
|
20
|
+
* returns, i.e. more than `maxDeviation` times the reference away from it.
|
|
18
21
|
*
|
|
19
|
-
* @param price - Order price.
|
|
22
|
+
* @param price - Order or market price.
|
|
20
23
|
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
21
24
|
* @param maxDeviation - Deviation limit as a fraction, such as
|
|
22
25
|
* `PerpsOrderLimits.maxOraclePriceDeviation`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"priceDeviation.d.ts","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"priceDeviation.d.ts","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CACnC,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,GACnB;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAe1C;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,2BAA2B,CACzC,KAAK,EAAE,MAAM,EACb,cAAc,EAAE,MAAM,EACtB,YAAY,EAAE,MAAM,GACnB,OAAO,CAQT"}
|
|
@@ -1,45 +1,36 @@
|
|
|
1
1
|
import { BigNumber } from 'bignumber.js';
|
|
2
2
|
/**
|
|
3
|
-
*
|
|
3
|
+
* Prices a venue accepts around a reference price under a deviation limit
|
|
4
|
+
* such as `PerpsOrderLimits.maxOraclePriceDeviation`: up to `maxDeviation`
|
|
5
|
+
* times the reference away from it on either side, so a price `p` is inside
|
|
6
|
+
* when `|p - reference| / reference <= maxDeviation`. HyperLiquid's rule
|
|
7
|
+
* ("Order price cannot be more than 95% away from the reference price") and
|
|
8
|
+
* `isMarketTradable` use this band. The lower bound never goes below 0.
|
|
9
|
+
* Bounds are computed in exact decimals, so `1 - 0.95` is exactly 0.05.
|
|
4
10
|
*
|
|
5
|
-
* @param referencePrice -
|
|
6
|
-
* @param maxDeviation - Deviation limit as a fraction.
|
|
7
|
-
* @returns The
|
|
11
|
+
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
12
|
+
* @param maxDeviation - Deviation limit as a positive fraction.
|
|
13
|
+
* @returns The inclusive band, or undefined when either input is unusable.
|
|
8
14
|
*/
|
|
9
|
-
function
|
|
15
|
+
export function getPriceDeviationBand(referencePrice, maxDeviation) {
|
|
10
16
|
if (!Number.isFinite(referencePrice) ||
|
|
11
17
|
referencePrice <= 0 ||
|
|
12
18
|
!Number.isFinite(maxDeviation) ||
|
|
13
|
-
maxDeviation <= 0
|
|
14
|
-
maxDeviation >= 1) {
|
|
19
|
+
maxDeviation <= 0) {
|
|
15
20
|
return undefined;
|
|
16
21
|
}
|
|
17
22
|
const reference = new BigNumber(referencePrice);
|
|
18
|
-
const
|
|
23
|
+
const offset = reference.multipliedBy(maxDeviation);
|
|
19
24
|
return {
|
|
20
|
-
min: reference.
|
|
21
|
-
max: reference.
|
|
25
|
+
min: BigNumber.max(reference.minus(offset), 0).toNumber(),
|
|
26
|
+
max: reference.plus(offset).toNumber(),
|
|
22
27
|
};
|
|
23
28
|
}
|
|
24
|
-
/**
|
|
25
|
-
* Prices a venue accepts around a reference price under a deviation limit
|
|
26
|
-
* such as `PerpsOrderLimits.maxOraclePriceDeviation`: from `1 - maxDeviation`
|
|
27
|
-
* times the reference up to the reference divided by it.
|
|
28
|
-
*
|
|
29
|
-
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
30
|
-
* @param maxDeviation - Deviation limit as a fraction, above 0 and below 1.
|
|
31
|
-
* @returns The inclusive band, or undefined when either input is unusable.
|
|
32
|
-
*/
|
|
33
|
-
export function getPriceDeviationBand(referencePrice, maxDeviation) {
|
|
34
|
-
const bounds = deviationBounds(referencePrice, maxDeviation);
|
|
35
|
-
return bounds && { min: bounds.min.toNumber(), max: bounds.max.toNumber() };
|
|
36
|
-
}
|
|
37
29
|
/**
|
|
38
30
|
* Whether a price is outside the inclusive band {@link getPriceDeviationBand}
|
|
39
|
-
* returns
|
|
40
|
-
* reference divided by it.
|
|
31
|
+
* returns, i.e. more than `maxDeviation` times the reference away from it.
|
|
41
32
|
*
|
|
42
|
-
* @param price - Order price.
|
|
33
|
+
* @param price - Order or market price.
|
|
43
34
|
* @param referencePrice - Oracle price, or the mark price when the oracle is unknown.
|
|
44
35
|
* @param maxDeviation - Deviation limit as a fraction, such as
|
|
45
36
|
* `PerpsOrderLimits.maxOraclePriceDeviation`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"priceDeviation.js","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC
|
|
1
|
+
{"version":3,"file":"priceDeviation.js","sourceRoot":"","sources":["../../src/utils/priceDeviation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,qBAAqB,CACnC,cAAsB,EACtB,YAAoB;IAEpB,IACE,CAAC,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC;QAChC,cAAc,IAAI,CAAC;QACnB,CAAC,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC;QAC9B,YAAY,IAAI,CAAC,EACjB,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IACD,MAAM,SAAS,GAAG,IAAI,SAAS,CAAC,cAAc,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,SAAS,CAAC,YAAY,CAAC,YAAY,CAAC,CAAC;IACpD,OAAO;QACL,GAAG,EAAE,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,QAAQ,EAAE;QACzD,GAAG,EAAE,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE;KACvC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,2BAA2B,CACzC,KAAa,EACb,cAAsB,EACtB,YAAoB;IAEpB,0EAA0E;IAC1E,qCAAqC;IACrC,MAAM,IAAI,GAAG,qBAAqB,CAAC,cAAc,EAAE,YAAY,CAAC,CAAC;IACjE,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,EAAE,CAAC;QAChE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,KAAK,GAAG,IAAI,CAAC,GAAG,IAAI,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC;AAC9C,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\n/**\n * Prices a venue accepts around a reference price under a deviation limit\n * such as `PerpsOrderLimits.maxOraclePriceDeviation`: up to `maxDeviation`\n * times the reference away from it on either side, so a price `p` is inside\n * when `|p - reference| / reference <= maxDeviation`. HyperLiquid's rule\n * (\"Order price cannot be more than 95% away from the reference price\") and\n * `isMarketTradable` use this band. The lower bound never goes below 0.\n * Bounds are computed in exact decimals, so `1 - 0.95` is exactly 0.05.\n *\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a positive fraction.\n * @returns The inclusive band, or undefined when either input is unusable.\n */\nexport function getPriceDeviationBand(\n referencePrice: number,\n maxDeviation: number,\n): { min: number; max: number } | undefined {\n if (\n !Number.isFinite(referencePrice) ||\n referencePrice <= 0 ||\n !Number.isFinite(maxDeviation) ||\n maxDeviation <= 0\n ) {\n return undefined;\n }\n const reference = new BigNumber(referencePrice);\n const offset = reference.multipliedBy(maxDeviation);\n return {\n min: BigNumber.max(reference.minus(offset), 0).toNumber(),\n max: reference.plus(offset).toNumber(),\n };\n}\n\n/**\n * Whether a price is outside the inclusive band {@link getPriceDeviationBand}\n * returns, i.e. more than `maxDeviation` times the reference away from it.\n *\n * @param price - Order or market price.\n * @param referencePrice - Oracle price, or the mark price when the oracle is unknown.\n * @param maxDeviation - Deviation limit as a fraction, such as\n * `PerpsOrderLimits.maxOraclePriceDeviation`.\n * @returns True when the price is outside the band; false when it is inside,\n * on a bound, or an input is missing, so unknown input never blocks an order.\n */\nexport function isPriceOutsideDeviationBand(\n price: number,\n referencePrice: number,\n maxDeviation: number,\n): boolean {\n // Compare with the numbers getPriceDeviationBand returns, so a price on a\n // bound it reports is always inside.\n const band = getPriceDeviationBand(referencePrice, maxDeviation);\n if (band === undefined || !Number.isFinite(price) || price <= 0) {\n return false;\n }\n return price < band.min || price > band.max;\n}\n"]}
|
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
import type { PerpsPricePrecision } from '../types/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Round a price onto a significant-figures grid (Hyperliquid). Integers are
|
|
4
|
+
* kept as they are. Otherwise the decimals are capped, then the significant
|
|
5
|
+
* figures, both rounding half up on the price's decimal form, so 69.9425
|
|
6
|
+
* becomes 69.943 as on hyperliquid.xyz rather than 69.942 from its binary
|
|
7
|
+
* float.
|
|
8
|
+
*
|
|
9
|
+
* @param price - Price in quote units.
|
|
10
|
+
* @param maxDecimals - Maximum decimal places.
|
|
11
|
+
* @param maxSignificantFigures - Maximum significant figures for a fractional price.
|
|
12
|
+
* @returns The rounded price string.
|
|
13
|
+
*/
|
|
14
|
+
export declare function roundToSignificantFiguresGrid(price: number | string, maxDecimals: number, maxSignificantFigures: number): string;
|
|
2
15
|
/**
|
|
3
16
|
* Round a price onto the grid a market accepts, as reported in
|
|
4
17
|
* `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid
|
|
5
|
-
* (Hyperliquid)
|
|
6
|
-
* then the significant figures, giving the same string as
|
|
18
|
+
* (Hyperliquid) uses `roundToSignificantFiguresGrid`, the same rounding as
|
|
7
19
|
* `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up
|
|
8
20
|
* to the nearest multiple of its tick.
|
|
9
21
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pricePrecision.d.ts","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"pricePrecision.d.ts","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AAG7D;;;;;;;;;;;GAWG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,MAAM,GAAG,MAAM,EACtB,WAAW,EAAE,MAAM,EACnB,qBAAqB,EAAE,MAAM,GAC5B,MAAM,CAqBR;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE;IACtC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC;IACvB,cAAc,EAAE,mBAAmB,CAAC;CACrC,GAAG,MAAM,GAAG,SAAS,CAmCrB"}
|
|
@@ -1,10 +1,37 @@
|
|
|
1
1
|
import { BigNumber } from 'bignumber.js';
|
|
2
|
-
import { countSignificantFigures
|
|
2
|
+
import { countSignificantFigures } from './significantFigures.js';
|
|
3
|
+
/**
|
|
4
|
+
* Round a price onto a significant-figures grid (Hyperliquid). Integers are
|
|
5
|
+
* kept as they are. Otherwise the decimals are capped, then the significant
|
|
6
|
+
* figures, both rounding half up on the price's decimal form, so 69.9425
|
|
7
|
+
* becomes 69.943 as on hyperliquid.xyz rather than 69.942 from its binary
|
|
8
|
+
* float.
|
|
9
|
+
*
|
|
10
|
+
* @param price - Price in quote units.
|
|
11
|
+
* @param maxDecimals - Maximum decimal places.
|
|
12
|
+
* @param maxSignificantFigures - Maximum significant figures for a fractional price.
|
|
13
|
+
* @returns The rounded price string.
|
|
14
|
+
*/
|
|
15
|
+
export function roundToSignificantFiguresGrid(price, maxDecimals, maxSignificantFigures) {
|
|
16
|
+
const priceNum = Number.parseFloat(String(price));
|
|
17
|
+
if (Number.isInteger(priceNum)) {
|
|
18
|
+
return priceNum.toString();
|
|
19
|
+
}
|
|
20
|
+
let rounded = new BigNumber(String(priceNum)).decimalPlaces(maxDecimals, BigNumber.ROUND_HALF_UP);
|
|
21
|
+
if (countSignificantFigures(rounded.toFixed()) > maxSignificantFigures) {
|
|
22
|
+
const integerDigits = rounded
|
|
23
|
+
.integerValue(BigNumber.ROUND_DOWN)
|
|
24
|
+
.abs()
|
|
25
|
+
.toFixed()
|
|
26
|
+
.replace(/^0$/u, '').length;
|
|
27
|
+
rounded = rounded.decimalPlaces(Math.max(maxSignificantFigures - integerDigits, 0), BigNumber.ROUND_HALF_UP);
|
|
28
|
+
}
|
|
29
|
+
return rounded.toFixed();
|
|
30
|
+
}
|
|
3
31
|
/**
|
|
4
32
|
* Round a price onto the grid a market accepts, as reported in
|
|
5
33
|
* `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid
|
|
6
|
-
* (Hyperliquid)
|
|
7
|
-
* then the significant figures, giving the same string as
|
|
34
|
+
* (Hyperliquid) uses `roundToSignificantFiguresGrid`, the same rounding as
|
|
8
35
|
* `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up
|
|
9
36
|
* to the nearest multiple of its tick.
|
|
10
37
|
*
|
|
@@ -38,14 +65,8 @@ export function roundPerpsPrice(params) {
|
|
|
38
65
|
const down = exact.minus(remainder);
|
|
39
66
|
rounded = (remainder.multipliedBy(2).gte(tick) ? down.plus(tick) : down).toFixed();
|
|
40
67
|
}
|
|
41
|
-
else if (Number.isInteger(priceNum)) {
|
|
42
|
-
rounded = priceNum.toString();
|
|
43
|
-
}
|
|
44
68
|
else {
|
|
45
|
-
rounded =
|
|
46
|
-
if (countSignificantFigures(rounded) > pricePrecision.maxSignificantFigures) {
|
|
47
|
-
rounded = roundToSignificantFigures(rounded, pricePrecision.maxSignificantFigures);
|
|
48
|
-
}
|
|
69
|
+
rounded = roundToSignificantFiguresGrid(priceNum, pricePrecision.maxDecimals, pricePrecision.maxSignificantFigures);
|
|
49
70
|
}
|
|
50
71
|
return Number.parseFloat(rounded) > 0 ? rounded : undefined;
|
|
51
72
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pricePrecision.js","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,OAAO,
|
|
1
|
+
{"version":3,"file":"pricePrecision.js","sourceRoot":"","sources":["../../src/utils/pricePrecision.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,OAAO,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAElE;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,6BAA6B,CAC3C,KAAsB,EACtB,WAAmB,EACnB,qBAA6B;IAE7B,MAAM,QAAQ,GAAG,MAAM,CAAC,UAAU,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAClD,IAAI,MAAM,CAAC,SAAS,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC/B,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,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,wEAAwE;QACxE,6CAA6C;QAC7C,MAAM,KAAK,GAAG,IAAI,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACtC,OAAO,SAAS,CAAC;QACnB,CAAC;QACD,sEAAsE;QACtE,+DAA+D;QAC/D,MAAM,SAAS,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACrC,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACpC,OAAO,GAAG,CACR,SAAS,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAC7D,CAAC,OAAO,EAAE,CAAC;IACd,CAAC;SAAM,CAAC;QACN,OAAO,GAAG,6BAA6B,CACrC,QAAQ,EACR,cAAc,CAAC,WAAW,EAC1B,cAAc,CAAC,qBAAqB,CACrC,CAAC;IACJ,CAAC;IAED,OAAO,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC9D,CAAC","sourcesContent":["import { BigNumber } from 'bignumber.js';\n\nimport type { PerpsPricePrecision } from '../types/index.js';\nimport { countSignificantFigures } from './significantFigures.js';\n\n/**\n * Round a price onto a significant-figures grid (Hyperliquid). Integers are\n * kept as they are. Otherwise the decimals are capped, then the significant\n * figures, both rounding half up on the price's decimal form, so 69.9425\n * becomes 69.943 as on hyperliquid.xyz rather than 69.942 from its binary\n * float.\n *\n * @param price - Price in quote units.\n * @param maxDecimals - Maximum decimal places.\n * @param maxSignificantFigures - Maximum significant figures for a fractional price.\n * @returns The rounded price string.\n */\nexport function roundToSignificantFiguresGrid(\n price: number | string,\n maxDecimals: number,\n maxSignificantFigures: number,\n): string {\n const priceNum = Number.parseFloat(String(price));\n if (Number.isInteger(priceNum)) {\n return priceNum.toString();\n }\n let rounded = new BigNumber(String(priceNum)).decimalPlaces(\n maxDecimals,\n BigNumber.ROUND_HALF_UP,\n );\n if (countSignificantFigures(rounded.toFixed()) > maxSignificantFigures) {\n const integerDigits = rounded\n .integerValue(BigNumber.ROUND_DOWN)\n .abs()\n .toFixed()\n .replace(/^0$/u, '').length;\n rounded = rounded.decimalPlaces(\n Math.max(maxSignificantFigures - integerDigits, 0),\n BigNumber.ROUND_HALF_UP,\n );\n }\n return rounded.toFixed();\n}\n\n/**\n * Round a price onto the grid a market accepts, as reported in\n * `PerpsOrderCapabilities.pricePrecision`. A `significant_figures` grid\n * (Hyperliquid) uses `roundToSignificantFiguresGrid`, the same rounding as\n * `formatHyperLiquidPrice`. A `fixed_decimals` grid (Lighter) rounds half up\n * to the nearest multiple of its tick.\n *\n * @param params - Rounding parameters.\n * @param params.price - Price in quote units.\n * @param params.pricePrecision - The market's price grid.\n * @returns The rounded price, or undefined when the price is not a positive\n * number, rounds to zero, or the tick is unusable.\n */\nexport function roundPerpsPrice(params: {\n price: number | string;\n pricePrecision: PerpsPricePrecision;\n}): string | undefined {\n const { price, pricePrecision } = params;\n const priceNum = Number.parseFloat(String(price));\n if (!Number.isFinite(priceNum) || priceNum <= 0) {\n return undefined;\n }\n\n let rounded: string;\n if (pricePrecision.type === 'fixed_decimals') {\n const tick = new BigNumber(pricePrecision.tickSize);\n if (!tick.isFinite() || tick.lte(0)) {\n return undefined;\n }\n // Read the caller's decimal string, not its float: 1.004999999999999999\n // would otherwise become 1.005 and round up.\n const exact = new BigNumber(String(price).trim());\n if (!exact.isFinite() || exact.lte(0)) {\n return undefined;\n }\n // Exact remainder, not a quotient: division rounds to 20 decimals and\n // could turn a value just under a half tick into exactly half.\n const remainder = exact.modulo(tick);\n const down = exact.minus(remainder);\n rounded = (\n remainder.multipliedBy(2).gte(tick) ? down.plus(tick) : down\n ).toFixed();\n } else {\n rounded = roundToSignificantFiguresGrid(\n priceNum,\n pricePrecision.maxDecimals,\n pricePrecision.maxSignificantFigures,\n );\n }\n\n return Number.parseFloat(rounded) > 0 ? rounded : undefined;\n}\n"]}
|
package/docs/architecture.md
CHANGED
|
@@ -31,20 +31,20 @@ Code: `src/PerpsController.ts` `PerpsController`; `src/types/index.ts` `PerpsPro
|
|
|
31
31
|
|
|
32
32
|
## What the controller owns
|
|
33
33
|
|
|
34
|
-
| Concern | Where it lives
|
|
35
|
-
| ------------------------------------ |
|
|
36
|
-
| Order, TP/SL, close and margin math | `src/utils/orderCalculations.ts`, `tpslCalculations.ts`, `closeCalculations.ts`, `marginAdjustment.ts`, `positionProtection.ts
|
|
37
|
-
| Fee resolution | `src/services/RewardsIntegrationService.ts`, `src/utils/subscriptionFeeWaiver.ts`
|
|
38
|
-
| Advanced orders (TWAP, chase, scale) | `src/utils/advancedOrders.ts` (rules from `getOrderCapabilities().strategyRules`, validation, previews, ladder sizing, price warnings), `advancedOrderLists.ts` (live lists); actions `subscribeToLiveTwapOrders`, `subscribeToChaseOrderLists`
|
|
39
|
-
| Display formatting | `src/utils/perpsFormatters.ts`; locale number formatting injected as `marketDataFormatters`
|
|
40
|
-
| Venue adapters and validation | `src/utils/hyperLiquidAdapter.ts`, `hyperLiquidOrderBookProcessor.ts`, `hyperLiquidValidation.ts`, `marketDataTransform.ts`, `marketUtils.ts`, `sortMarkets.ts`, `idUtils.ts`, `standaloneInfoClient.ts`
|
|
41
|
-
| Request reliability | `src/utils/providerHealth.ts`, `coalescePerpsRestRequest.ts`, `guardedHyperLiquidClient.ts`
|
|
42
|
-
| Constants | `src/constants/` (`perpsConfig.ts` `PERPS_CONSTANTS`, `hyperLiquidConfig.ts`, `lighterConfig.ts` and others)
|
|
43
|
-
| Connection primitives | `PerpsController` `init`, `disconnect`, `reconnect`, `toggleTestnet`, `switchProvider`
|
|
44
|
-
| State | `PerpsControllerState`, `getDefaultPerpsControllerState`; selectors in `src/selectors.ts`
|
|
45
|
-
| Messenger events | `PerpsControllerEvents`
|
|
46
|
-
| Analytics properties | `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`, `PERPS_EVENT_VALUE`; sent through the injected `metrics`
|
|
47
|
-
| Errors | `src/perpsErrorCodes.ts`, `src/errors.ts`
|
|
34
|
+
| Concern | Where it lives |
|
|
35
|
+
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
36
|
+
| Order, TP/SL, close and margin math | `src/utils/orderCalculations.ts`, `tpslCalculations.ts`, `closeCalculations.ts`, `marginAdjustment.ts`, `positionProtection.ts`, `positionCalculations.ts` (live PnL at a price), `feeAmounts.ts`, `pricePrecision.ts`, `priceDeviation.ts` (oracle band), `orderBookGrouping.ts` and `orderBookSlippage.ts` (book grouping, spread, slippage), `orderFills.ts`, `hyperLiquidScaleOrders.ts`, `accountUtils.ts` (cross-margin tone); actions `calculateFees`, `calculateLiquidationPrice`, `calculateMaintenanceMargin` |
|
|
37
|
+
| Fee resolution | `src/services/RewardsIntegrationService.ts`, `src/utils/subscriptionFeeWaiver.ts` |
|
|
38
|
+
| Advanced orders (TWAP, chase, scale) | `src/utils/advancedOrders.ts` (rules from `getOrderCapabilities().strategyRules`, validation, previews, ladder sizing, price warnings), `advancedOrderLists.ts` (live lists); actions `subscribeToLiveTwapOrders`, `subscribeToChaseOrderLists` |
|
|
39
|
+
| Display formatting | `src/utils/perpsFormatters.ts`; locale number formatting injected as `marketDataFormatters` |
|
|
40
|
+
| Venue adapters and validation | `src/utils/hyperLiquidAdapter.ts`, `hyperLiquidOrderBookProcessor.ts`, `hyperLiquidValidation.ts`, `marketDataTransform.ts`, `marketUtils.ts`, `sortMarkets.ts`, `idUtils.ts`, `standaloneInfoClient.ts` |
|
|
41
|
+
| Request reliability | `src/utils/providerHealth.ts`, `coalescePerpsRestRequest.ts`, `guardedHyperLiquidClient.ts` |
|
|
42
|
+
| Constants | `src/constants/` (`perpsConfig.ts` `PERPS_CONSTANTS`, `hyperLiquidConfig.ts`, `lighterConfig.ts` and others) |
|
|
43
|
+
| Connection primitives | `PerpsController` `init`, `disconnect`, `reconnect`, `toggleTestnet`, `switchProvider` |
|
|
44
|
+
| State | `PerpsControllerState`, `getDefaultPerpsControllerState`; selectors in `src/selectors.ts` |
|
|
45
|
+
| Messenger events | `PerpsControllerEvents` |
|
|
46
|
+
| Analytics properties | `src/constants/eventNames.ts` `PERPS_EVENT_PROPERTY`, `PERPS_EVENT_VALUE`; sent through the injected `metrics` |
|
|
47
|
+
| Errors | `src/perpsErrorCodes.ts`, `src/errors.ts` |
|
|
48
48
|
|
|
49
49
|
Code: `src/utils/`, `src/constants/`, `src/selectors.ts`, `src/PerpsController.ts` `PerpsControllerState`.
|
|
50
50
|
|
|
@@ -130,9 +130,9 @@ Code: `src/services/`; `src/PerpsController.ts` constructor.
|
|
|
130
130
|
|
|
131
131
|
Aggregated reads return the original venue rows. A market served directly from a v4 snapshot carries the provider ID that Core validated. Clients can call `groupMarketsByMarketKey(rows, defaultProvider)` for display. Rows group when they share a backend key and each explicitly has `priceScale: 1`. Each group puts the default venue first when present. Use `rowId` as the display row identity and the selected venue's `providerId` and `symbol` for charts and trading. Rows with missing keys or with missing or non-unit scales remain separate and omit `marketKey`. Saving one stores its bare symbol when it is on the legacy venue, otherwise `venue:<provider>:<symbol>`, never a backend key.
|
|
132
132
|
|
|
133
|
-
`toggleWatchlistMarket`, `isWatchlistMarket` and `recordMarketViewed` take an optional backend key from a unit-scale row. Pass the original group's `venues` as the third argument and the venue that owned saved symbols as the fourth (`legacyProvider`, default HyperLiquid, the same default as `resolveSavedPerpsMarkets`). These actions also match each tagged group row with the same backend key and `priceScale: 1` by the entry it would have saved ungrouped: its symbol on the legacy venue, otherwise `venue:<provider>:<symbol>`. A favorite or recent saved before the row grouped is replaced with the keyed entry. When opening a saved item, pass the saved strings and ungrouped venue rows to `resolveSavedPerpsMarkets`. A legacy symbol requires an exact match on its original venue and stays unresolved while that row is unavailable. A `venue:` reference opens only that venue's row with the same symbol. The resolver defaults legacy ownership to HyperLiquid and accepts the prior venue for entries saved on Lighter. New keyed entries look for unit-scale rows and prefer the configured default venue.
|
|
133
|
+
`toggleWatchlistMarket`, `isWatchlistMarket` and `recordMarketViewed` take an optional backend key from a unit-scale row. Pass the original group's `venues` as the third argument and the venue that owned saved symbols as the fourth (`legacyProvider`, default HyperLiquid, the same default as `resolveSavedPerpsMarkets`). Redux-style clients get the same match from `selectIsWatchlistMarket(state, symbol, marketKey, venues, legacyProvider)`. Direct-mode rows from `getMarketDataWithPrices` carry the active provider as `providerId`, so a direct Lighter row saves as `venue:lighter:<symbol>` even though it never passed through the aggregator. These actions also match each tagged group row with the same backend key and `priceScale: 1` by the entry it would have saved ungrouped: its symbol on the legacy venue, otherwise `venue:<provider>:<symbol>`. A favorite or recent saved before the row grouped is replaced with the keyed entry. When opening a saved item, pass the saved strings and ungrouped venue rows to `resolveSavedPerpsMarkets`. A legacy symbol requires an exact match on its original venue and stays unresolved while that row is unavailable. A `venue:` reference opens only that venue's row with the same symbol. The resolver defaults legacy ownership to HyperLiquid and accepts the prior venue for entries saved on Lighter. New keyed entries look for unit-scale rows and prefer the configured default venue. The HyperLiquid watchlist syncs to AuthenticatedUserStorageService, where Mobile and Extension match entries by symbol, so in that mode a grouped favorite is saved by its venue symbol and keeps the backend key only as an alias. `market-key:` and `venue:` entries stay local and are never written to AUS.
|
|
134
134
|
|
|
135
|
-
With snapshots configured, a missing or expired venue
|
|
135
|
+
With snapshots configured, a missing or expired slice of a registered venue invalidates the aggregated preload. The client can fetch a fresh list from Core.
|
|
136
136
|
|
|
137
137
|
## Platform dependencies
|
|
138
138
|
|
|
@@ -182,7 +182,7 @@ Code: `src/PerpsController-method-action-types.ts`; `src/PerpsController.ts` `ME
|
|
|
182
182
|
|
|
183
183
|
- `startMarketDataPreload()` runs the market and user preloads in parallel at once, then every 5 minutes (`#preloadRefreshMs`).
|
|
184
184
|
- It re-runs both preloads when `isTestnet` or `hip3ConfigVersion` changes, and the user preload on `AccountsController:selectedAccountChange` and `AccountTreeController:selectedAccountGroupChange`.
|
|
185
|
-
- `#performMarketDataPreload` skips during reinitialization or when the entry is newer than `#preloadGuardMs` (30 s). It calls `getMarketDataWithPrices({ standalone: true })` and writes `cachedMarketDataByProvider[providerNetworkKey]`; aggregated mode writes one entry per provider plus an empty sentinel.
|
|
185
|
+
- `#performMarketDataPreload` skips during reinitialization or when the entry is newer than `#preloadGuardMs` (30 s). In aggregated mode it skips only while the aggregate cache is complete: every registered venue has a current slice (with a snapshot URL, HyperLiquid and, once registered, Lighter), and a slice of a venue that did not register this session is ignored. It calls `getMarketDataWithPrices({ standalone: true })` and writes `cachedMarketDataByProvider[providerNetworkKey]`; aggregated mode writes one entry per provider plus an empty sentinel.
|
|
186
186
|
- `#performUserDataPreload` needs a selected EVM address. It skips when the matching entry is newer than 30 s, or exists while the WebSocket is connected. It writes `cachedUserDataByProvider[providerNetworkKey]`.
|
|
187
187
|
- `stopMarketDataPreload()` and `disconnect()` both stop the timer and its subscriptions. After a disconnect, preload restarts only when the client calls `startMarketDataPreload()` again.
|
|
188
188
|
|
package/docs/client-contract.md
CHANGED
|
@@ -15,21 +15,21 @@ Shared answers clients used to keep their own copies of. Each one is exported fr
|
|
|
15
15
|
|
|
16
16
|
`orderLimits`:
|
|
17
17
|
|
|
18
|
-
| Field | HyperLiquid
|
|
19
|
-
| ------------------------- |
|
|
20
|
-
| `sizeDecimals` | market `szDecimals`
|
|
21
|
-
| `minOrderNotionalUsd` | per-order minimum ($10)
|
|
22
|
-
| `minOrderSize` | not reported
|
|
23
|
-
| `minimumAppliesTo` | `all_orders`
|
|
24
|
-
| `scaleOrderCount` | `SCALE_ORDER_COUNT`
|
|
25
|
-
| `twap` | `HYPERLIQUID_TWAP_LIMITS`
|
|
26
|
-
| `maxOraclePriceDeviation` | `0.95` (`
|
|
18
|
+
| Field | HyperLiquid | Lighter |
|
|
19
|
+
| ------------------------- | ------------------------------------------------------- | ------------------------- |
|
|
20
|
+
| `sizeDecimals` | market `szDecimals` | `supported_size_decimals` |
|
|
21
|
+
| `minOrderNotionalUsd` | per-order minimum ($10) | `min_quote_amount` |
|
|
22
|
+
| `minOrderSize` | not reported | `min_base_amount` |
|
|
23
|
+
| `minimumAppliesTo` | `all_orders` | `resting_limit_orders` |
|
|
24
|
+
| `scaleOrderCount` | `SCALE_ORDER_COUNT` | `SCALE_ORDER_COUNT` |
|
|
25
|
+
| `twap` | `HYPERLIQUID_TWAP_LIMITS` | not reported (no TWAP) |
|
|
26
|
+
| `maxOraclePriceDeviation` | `0.95` (`HYPERLIQUID_CONFIG.OraclePriceDeviationLimit`) | not reported |
|
|
27
27
|
|
|
28
28
|
Apply the reported minimums to the orders named by `minimumAppliesTo`. On Lighter, market and IOC orders can go down to one size step. Lighter reports `resting_limit_orders` even when maker minimums are unavailable. It omits both minimums if either is missing or invalid, if either grid is unavailable, or if the maker bounds cannot be met within the venue's wire limits. The largest base size is `(2^48 − 1) × 10^(-sizeDecimals)`, and the largest quote notional is that size times the largest wire price expressed in quote units. A valid grid remains available independently.
|
|
29
29
|
|
|
30
30
|
A verified full close can qualify for an exception to the normal minimum notional. The close must still satisfy the venue's size grid. For example, a HyperLiquid batch close refuses a position whose size rounds down to zero, with `ORDER_SIZE_POSITIVE` on that row.
|
|
31
31
|
|
|
32
|
-
Check a limit price against `maxOraclePriceDeviation` with `isPriceOutsideDeviationBand(price, oraclePrice, maxOraclePriceDeviation)`, or show the accepted range from `getPriceDeviationBand`. Skip the check when the venue omits the limit. Round a price onto the reported grid with `roundPerpsPrice({ price, pricePrecision })`: a HyperLiquid grid gives the same string as `formatHyperLiquidPrice` except that a price rounding to zero returns `undefined` rather than `'0'`, and a Lighter grid rounds the supplied decimal string half up to `tickSize`.
|
|
32
|
+
Check a limit price against `maxOraclePriceDeviation` with `isPriceOutsideDeviationBand(price, oraclePrice, maxOraclePriceDeviation)`, or show the accepted range from `getPriceDeviationBand`. Both use `|price - oracle| / oracle <= maxOraclePriceDeviation`, the same rule as `isMarketTradable` and `PriceUpdate.isTradable`, and Hyperliquid reports the limit the provider was configured with (`fallbackPriceDeviationLimit`, default `0.95`). Skip the check when the venue omits the limit. Round a price onto the reported grid with `roundPerpsPrice({ price, pricePrecision })`: a HyperLiquid grid gives the same string as `formatHyperLiquidPrice` except that a price rounding to zero returns `undefined` rather than `'0'`, and a Lighter grid rounds the supplied decimal string half up to `tickSize`.
|
|
33
33
|
|
|
34
34
|
`attachedTpslGroupLimit` (`{ takeProfit, stopLoss }`) is the most take-profit and stop-loss legs one order can attach. HyperLiquid and Lighter both report one of each.
|
|
35
35
|
|
|
@@ -75,6 +75,10 @@ Pass tiers from `resolveHyperLiquidMarginTiers`; do not assume a default max lev
|
|
|
75
75
|
- For an existing position, `maintenanceMargin` is `crossMarginSummary.maintenanceMargin` (it already includes the position) or `estimateCrossMaintenanceMargin` over every cross position.
|
|
76
76
|
- For an opening order preview, require a current position snapshot confirming there is no existing position in the target market. Keep Mobile's guard for an existing position and for Scale orders. Pass the order price as `markPrice` and the order size as `positionSize`, and add the new position's maintenance at that price to the account's existing maintenance. Show the preview as unavailable when the snapshot is missing or the order adds to, reduces, or flips an existing position.
|
|
77
77
|
|
|
78
|
+
### Open position liquidation price
|
|
79
|
+
|
|
80
|
+
`Position.liquidationPrice` is the venue's figure. `null` on a Cross position means no price reachable at the current account value liquidates it: the cross collateral covers the position's maintenance margin at every positive price. Render it as no liquidation risk (for example "None" or an em dash), never as 0 and never as a loading or error state. It can become a price again when account value falls or the position grows.
|
|
81
|
+
|
|
78
82
|
### Controller liquidation previews
|
|
79
83
|
|
|
80
84
|
`PerpsController.calculateLiquidationPrice` and `PerpsController:calculateLiquidationPrice` return `Promise<string>`. For a HyperLiquid cross opening, pass `marginType: 'cross'`, `asset`, `entryPrice`, `direction`, `leverage` and a positive `positionSize` in base units. In aggregated mode include `providerId: 'hyperliquid'`. The provider reads the selected wallet's current positions and market tiers. Unified uses shared cross equity and spot USDC. Standard uses only the main DEX's cross pool. Standard HIP-3 openings and other account modes are unavailable in this preview.
|
package/docs/contracts/events.md
CHANGED
|
@@ -213,11 +213,13 @@ All keys live in `PERPS_EVENT_PROPERTY`. The constant name is the upper-case key
|
|
|
213
213
|
| UTM attribution | `utm_source`, `utm_medium`, `utm_campaign`, `utm_content`, `utm_term` |
|
|
214
214
|
| Client | `environment_type` |
|
|
215
215
|
| Order funnel and quotes | `order_context`, `order_size_percent`, `limit_price_input_type`, `limit_price_input_preset`, `order_has_tp`, `order_has_sl`, `quote_latency_ms`, `error_reason`, `saved_order`, `default_payment_token`, `default_size_amount`, `default_leverage`, `default_auto_close`, `order_execution_latency_ms`, `screen_context`, `from_token`, `from_chain`, `to_token`, `to_chain` |
|
|
216
|
-
| Search | `search_query`, `results_count`, `result_rank`, `mode`, `current_token`, `query_count`, `time_in_search_ms`, `time_to_tap_ms`, `
|
|
216
|
+
| Search | `search_query`, `results_count`, `result_rank`, `mode`, `current_token`, `query_count`, `time_in_search_ms`, `time_to_tap_ms`, `query_length`, `has_results`, `active_chips` |
|
|
217
217
|
| Interface mode | `perps_mode` |
|
|
218
218
|
| Sort, filter, abandon | `sort_field`, `sort_direction`, `filter_category`, `time_on_screen_ms` |
|
|
219
219
|
| Chase | `fill_pct_at_terminate` |
|
|
220
|
-
| Related markets | `source_market`, `
|
|
220
|
+
| Related markets | `source_market`, `category`, `asset`, `result_rank` |
|
|
221
|
+
|
|
222
|
+
Search events carry the query as `search_query`; there is no separate `query_text` key in Core. `query_count` and `time_in_search_ms` are sent on the abandon event for the whole session, while `active_chips`, `query_length` and `has_results` describe the query event they are sent with. A related-market tap reports the tapped market as `asset` and its one-based slot as `result_rank`; `category` is the collection the list was drawn from, which is neither `market_category` (the market's own category) nor `filter_category` (a list filter).
|
|
221
223
|
|
|
222
224
|
`perps_mode` is the Lite/Pro interface mode (`lite` or `pro`). It is separate from `mode`, which search uses for query intent (`discovery`, `intent` or `browse`).
|
|
223
225
|
|
|
@@ -31,9 +31,9 @@ Code: `src/services/FeatureFlagConfigurationService.ts` `refreshHip3Config`, `re
|
|
|
31
31
|
|
|
32
32
|
## Not read by Core
|
|
33
33
|
|
|
34
|
-
| Name | What Core does instead
|
|
35
|
-
| ------------------------------------- |
|
|
36
|
-
| `perpsPayWithAnyTokenAllowlistAssets` | Read by the client. See the Mobile doc
|
|
37
|
-
| Terminal market list source | Not a flag. A configured `terminalApi.globalSnapshotUrl` makes each active provider read its own schema-v4 snapshot, both venues in aggregated mode. The HyperLiquid snapshot is the HyperLiquid
|
|
34
|
+
| Name | What Core does instead |
|
|
35
|
+
| ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
36
|
+
| `perpsPayWithAnyTokenAllowlistAssets` | Read by the client. See the Mobile doc |
|
|
37
|
+
| Terminal market list source | Not a flag. A configured `terminalApi.globalSnapshotUrl` makes each active provider read its own schema-v4 snapshot, both venues in aggregated mode. The HyperLiquid snapshot is the market list for a direct HyperLiquid `getMarkets` call and for the HyperLiquid rows of `getMarketDataWithPrices` in both modes, except for `skipFilters: true` calls and calls without a snapshot context, which use the provider. Aggregated `getMarkets` returns each venue's provider trading rules and joins only `marketKey` and `priceScale` from that venue's snapshot, matched by venue and market name, so the same symbol on both venues keeps its own identity. The Lighter snapshot adds names, categories, metadata, icons, volume, open interest and `marketKey` to the Lighter provider's rows; prices and trading rules stay with the provider. Core validates each snapshot and falls back to that provider alone when its snapshot is unavailable or invalid. The caller's `useTerminalApi` option chooses the v1 path only when no snapshot URL is set |
|
|
38
38
|
|
|
39
39
|
Code: `src/constants/hyperLiquidConfig.ts` `HIP3_ASSET_MARKET_TYPES`; `src/providers/HyperLiquidProvider.ts`; `src/services/MarketDataService.ts` `getMarkets`, `getMarketDataWithPrices`; `src/services/TerminalMarketService.ts` `fetchGlobalSnapshot`; `src/PerpsController.ts` `#buildGlobalSnapshotContexts`
|