@metamask-previews/perps-controller 22.3.0-preview-04cf473 → 22.3.0-preview-a2a3d82

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/PerpsController-method-action-types.d.ts +19 -1
  3. package/dist/PerpsController-method-action-types.d.ts.map +1 -1
  4. package/dist/PerpsController-method-action-types.js.map +1 -1
  5. package/dist/PerpsController.d.ts +16 -1
  6. package/dist/PerpsController.d.ts.map +1 -1
  7. package/dist/PerpsController.js +32 -0
  8. package/dist/PerpsController.js.map +1 -1
  9. package/dist/constants/perpsConfig.d.ts +16 -0
  10. package/dist/constants/perpsConfig.d.ts.map +1 -1
  11. package/dist/constants/perpsConfig.js +24 -0
  12. package/dist/constants/perpsConfig.js.map +1 -1
  13. package/dist/index.d.ts +4 -4
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/providers/AggregatedPerpsProvider.d.ts +10 -1
  18. package/dist/providers/AggregatedPerpsProvider.d.ts.map +1 -1
  19. package/dist/providers/AggregatedPerpsProvider.js +20 -0
  20. package/dist/providers/AggregatedPerpsProvider.js.map +1 -1
  21. package/dist/providers/HyperLiquidProvider.d.ts +10 -1
  22. package/dist/providers/HyperLiquidProvider.d.ts.map +1 -1
  23. package/dist/providers/HyperLiquidProvider.js +20 -0
  24. package/dist/providers/HyperLiquidProvider.js.map +1 -1
  25. package/dist/services/HyperLiquidSubscriptionService.d.ts +22 -1
  26. package/dist/services/HyperLiquidSubscriptionService.d.ts.map +1 -1
  27. package/dist/services/HyperLiquidSubscriptionService.js +90 -0
  28. package/dist/services/HyperLiquidSubscriptionService.js.map +1 -1
  29. package/dist/types/index.d.ts +43 -0
  30. package/dist/types/index.d.ts.map +1 -1
  31. package/dist/types/index.js.map +1 -1
  32. package/dist/utils/perpsFormatters.d.ts +125 -53
  33. package/dist/utils/perpsFormatters.d.ts.map +1 -1
  34. package/dist/utils/perpsFormatters.js +345 -202
  35. package/dist/utils/perpsFormatters.js.map +1 -1
  36. package/package.json +2 -1
@@ -1,55 +1,200 @@
1
1
  /**
2
- * Portable perps decimal formatters.
2
+ * Portable perps display formatters.
3
3
  *
4
- * These are the canonical implementations, exported from the controller so
5
- * extension and any future consumer can import them directly.
6
- * No mobile-specific imports — safe to sync to Core.
4
+ * These are the canonical perps display rules, exported from the controller
5
+ * so Mobile, Extension and Terminal format every displayed perps value the
6
+ * same way: price ranges, precision constants, sign and placeholder rules.
7
+ * Each formatter takes one options object (`formatters`, `decimals`, `sign`)
8
+ * and renders the shared placeholder from `PERPS_CONSTANTS` for a missing
9
+ * value.
7
10
  *
8
- * Intl.NumberFormat instances are cached in a module-level Map keyed by
9
- * serialized options, avoiding repeated construction costs.
11
+ * The locale-aware `Intl` formatting comes from the client: pass
12
+ * `createFormatters({ locale })` from `@metamask/client-utils` (built once per
13
+ * locale) as `formatters`. This package does not depend on client-utils; it
14
+ * only needs the `PerpsIntlFormatters` shape. Without `formatters`, an
15
+ * `en-US` fallback keeps the legacy call signatures working.
10
16
  */
11
- import { DECIMAL_PRECISION_CONFIG, FUNDING_RATE_CONFIG, PERPS_CONSTANTS, } from '../constants/perpsConfig.js';
12
- // Module-level Intl.NumberFormat cache (keyed by serialized options).
13
- const _fmtCache = new Map();
14
- function _formatCurrency(value, currency, opts) {
15
- const key = `${currency}:${opts.minimumFractionDigits}:${opts.maximumFractionDigits}`;
16
- let formatter = _fmtCache.get(key);
17
+ import { DECIMAL_PRECISION_CONFIG, FUNDING_RATE_CONFIG, PERPS_CONSTANTS, PERPS_DISPLAY_PRECISION, } from '../constants/perpsConfig.js';
18
+ /**
19
+ * `Intl.NumberFormat` cache of the `en-US` fallback, keyed by options.
20
+ * Constructing a formatter costs far more than formatting, so none is built
21
+ * per call. Bounded by the option sets the formatters use.
22
+ */
23
+ const _fallbackFormatCache = new Map();
24
+ function _getFallbackFormat(options) {
25
+ const key = JSON.stringify(options);
26
+ let formatter = _fallbackFormatCache.get(key);
17
27
  if (!formatter) {
18
- formatter = new Intl.NumberFormat('en-US', {
19
- style: 'currency',
20
- currency,
21
- currencyDisplay: 'narrowSymbol',
22
- minimumFractionDigits: opts.minimumFractionDigits,
23
- maximumFractionDigits: opts.maximumFractionDigits,
24
- });
25
- _fmtCache.set(key, formatter);
28
+ formatter = new Intl.NumberFormat('en-US', options);
29
+ _fallbackFormatCache.set(key, formatter);
30
+ }
31
+ return formatter;
32
+ }
33
+ /**
34
+ * `en-US` formatters used when the caller passes no `formatters`, so the
35
+ * legacy call signatures keep their output.
36
+ */
37
+ const _fallbackFormatters = {
38
+ formatNumber: (value, options = {}) => _getFallbackFormat(options).format(value),
39
+ formatCurrency: (value, currency, options = {}) => _getFallbackFormat({ style: 'currency', currency, ...options }).format(value),
40
+ };
41
+ /**
42
+ * Parses a displayable number. Missing input (`undefined`, `null`, an empty or
43
+ * non-numeric string, `NaN` or an infinite value) returns `undefined`.
44
+ *
45
+ * @param value - The raw value.
46
+ * @returns The finite number, or `undefined` when the value is missing.
47
+ */
48
+ function _parseDisplayNumber(value) {
49
+ let parsed = Number.NaN;
50
+ if (typeof value === 'number') {
51
+ parsed = value;
52
+ }
53
+ else if (typeof value === 'string') {
54
+ parsed = Number.parseFloat(value);
55
+ }
56
+ return Number.isFinite(parsed) ? parsed : undefined;
57
+ }
58
+ /**
59
+ * Returns the sign prefix for a value.
60
+ *
61
+ * @param value - The signed value.
62
+ * @param isZero - Whether the value rounds to zero at the displayed precision.
63
+ * @param sign - The sign display mode.
64
+ * @returns `+`, `-` or an empty string.
65
+ */
66
+ function _signPrefix(value, isZero, sign) {
67
+ if (sign === 'never') {
68
+ return '';
69
+ }
70
+ if (isZero) {
71
+ return sign === 'always' ? '+' : '';
72
+ }
73
+ if (value < 0) {
74
+ return '-';
26
75
  }
27
- return formatter.format(value);
76
+ return sign === 'auto' ? '' : '+';
28
77
  }
29
78
  /**
30
- * Internal equivalent of the mobile formatWithThreshold utility.
31
- * Formats a currency value, returning "<$X.XX" for values below threshold.
79
+ * Formats a non-negative number with the locale's separators. Callers that
80
+ * must keep `toFixed` rounding pass a value already rounded with it.
81
+ *
82
+ * @param formatters - Locale-bound formatters.
83
+ * @param value - Non-negative value.
84
+ * @param minimumFractionDigits - Fraction digits always shown.
85
+ * @param maximumFractionDigits - Fraction digits at most shown.
86
+ * @param useGrouping - Whether to group thousands as the locale does.
87
+ * @returns The formatted number.
88
+ */
89
+ function _formatDecimal(formatters, value, minimumFractionDigits, maximumFractionDigits, useGrouping) {
90
+ return formatters.formatNumber(value, {
91
+ minimumFractionDigits,
92
+ maximumFractionDigits,
93
+ // Omitted keeps the locale's own grouping rule (es: "1234,5", "12.345,7")
94
+ ...(useGrouping ? {} : { useGrouping: false }),
95
+ });
96
+ }
97
+ /**
98
+ * The magnitude of `value` rounded with `toFixed`, as the decimal formatters
99
+ * (size, percentage, funding) display it.
100
+ *
101
+ * @param value - The signed value.
102
+ * @param decimals - Fraction digits shown.
103
+ * @returns The rounded non-negative value.
104
+ */
105
+ function _roundedMagnitude(value, decimals) {
106
+ return Number(Math.abs(value).toFixed(decimals));
107
+ }
108
+ /**
109
+ * Formats a signed number with `toFixed` rounding and the locale's
110
+ * separators. A value that rounds to zero is zero for the sign.
111
+ *
112
+ * @param formatters - Locale-bound formatters.
113
+ * @param value - The signed value.
114
+ * @param options - Formatting options.
115
+ * @param options.minimumFractionDigits - Fraction digits always shown.
116
+ * @param options.maximumFractionDigits - Fraction digits at most shown.
117
+ * @param options.useGrouping - Whether to group thousands as the locale does.
118
+ * @param options.sign - The sign display mode.
119
+ * @returns The sign prefix and formatted magnitude.
120
+ */
121
+ function _formatSignedDecimal(formatters, value, options) {
122
+ const rounded = _roundedMagnitude(value, options.maximumFractionDigits);
123
+ return `${_signPrefix(value, rounded === 0, options.sign)}${_formatDecimal(formatters, rounded, options.minimumFractionDigits, options.maximumFractionDigits, options.useGrouping)}`;
124
+ }
125
+ /**
126
+ * Whether a currency amount shows as zero at `decimals`, with the half away
127
+ * from zero rounding `Intl` applies.
128
+ *
129
+ * @param amount - Non-negative amount.
130
+ * @param decimals - Fraction digits shown.
131
+ * @returns True when the displayed amount is zero.
132
+ */
133
+ function _currencyShowsZero(amount, decimals) {
134
+ return Math.round(amount * 10 ** decimals) === 0;
135
+ }
136
+ /**
137
+ * Whether `amount` rounded to `maximumFractionDigits` has an all-zero
138
+ * fraction, decided without an `Intl` call.
139
+ *
140
+ * `Intl.NumberFormat` rounds the shortest decimal form of a number
141
+ * (`String(amount)`) half away from zero, so this reads that form's digits as
142
+ * text: exact for any magnitude, including exponent forms such as `1.5e+21`
143
+ * and `5e-7`.
32
144
  *
33
- * @param amount - The numeric amount to format.
34
- * @param threshold - The threshold below which the "<" prefix is shown.
35
- * @param options - Intl formatting options.
145
+ * @param amount - Non-negative amount.
146
+ * @param maximumFractionDigits - Fraction digits the amount is rounded to.
147
+ * @returns True when the rounded amount is a whole number.
148
+ */
149
+ function _roundsToWhole(amount, maximumFractionDigits) {
150
+ const [mantissa, exponentText = '0'] = String(amount).split('e');
151
+ const [integerPart, fractionPart = ''] = mantissa.split('.');
152
+ // Fraction digits once the exponent is applied
153
+ const shift = Number(exponentText);
154
+ // An exponent form has one integer digit: "1.23e-7" → "000000123"
155
+ const fraction = shift >= 0
156
+ ? fractionPart.slice(shift)
157
+ : `${'0'.repeat(-shift - 1)}${integerPart}${fractionPart}`;
158
+ const kept = fraction.slice(0, maximumFractionDigits);
159
+ const roundsUp = (fraction[maximumFractionDigits] ?? '0') >= '5';
160
+ return roundsUp ? /^9*$/u.test(kept) : /^0*$/u.test(kept);
161
+ }
162
+ /**
163
+ * Formats a non-negative currency amount, stripping trailing fraction zeros.
164
+ *
165
+ * Stripping is done through the fraction-digit options, so the amount is
166
+ * formatted once. This works for any decimal separator or digit set and does
167
+ * not rely on `formatToParts`, which some Hermes builds return as one literal
168
+ * part.
169
+ *
170
+ * @param formatters - Locale-bound formatters.
171
+ * @param amount - Non-negative amount.
172
+ * @param options - Formatting options.
36
173
  * @param options.currency - ISO 4217 currency code.
37
174
  * @param options.minimumFractionDigits - Minimum decimal digits.
38
175
  * @param options.maximumFractionDigits - Maximum decimal digits.
176
+ * @param options.strip - `fiat` drops an all-zero two-digit fraction (`.00`),
177
+ * `all` drops every trailing fraction zero, `none` keeps them.
39
178
  * @returns Formatted currency string.
40
179
  */
41
- function _formatWithThreshold(amount, threshold, options) {
42
- const formatOpts = {
43
- minimumFractionDigits: options.minimumFractionDigits,
44
- maximumFractionDigits: options.maximumFractionDigits,
45
- currencyDisplay: 'narrowSymbol',
46
- };
47
- if (amount === 0) {
48
- return _formatCurrency(0, options.currency, formatOpts);
180
+ function _formatCurrency(formatters, amount, options) {
181
+ let { minimumFractionDigits, maximumFractionDigits } = options;
182
+ if (options.strip === 'all') {
183
+ // Intl drops trailing fraction zeros down to the minimum
184
+ minimumFractionDigits = 0;
185
+ }
186
+ else if (options.strip === 'fiat' && minimumFractionDigits === 2) {
187
+ if (_roundsToWhole(amount, maximumFractionDigits)) {
188
+ // Fiat-style: only an all-zero ".00" fraction is dropped
189
+ minimumFractionDigits = 0;
190
+ maximumFractionDigits = 0;
191
+ }
49
192
  }
50
- return Math.abs(amount) < threshold
51
- ? `<${_formatCurrency(threshold, options.currency, formatOpts)}`
52
- : _formatCurrency(amount, options.currency, formatOpts);
193
+ return formatters.formatCurrency(amount, options.currency, {
194
+ currencyDisplay: 'narrowSymbol',
195
+ minimumFractionDigits,
196
+ maximumFractionDigits,
197
+ });
53
198
  }
54
199
  /**
55
200
  * Price threshold constants for PRICE_RANGES_UNIVERSAL
@@ -269,232 +414,230 @@ export const PRICE_RANGES_UNIVERSAL = [
269
414
  },
270
415
  ];
271
416
  /**
272
- * Formats a balance value as USD currency with appropriate decimal places
417
+ * Formats a fiat value (balance, price, fee, position value) as currency with
418
+ * decimal places chosen by the matching range.
273
419
  *
274
- * @param balance - Raw numeric balance value (e.g., 1234.56, not token minimal denomination)
275
- * @param options - Optional formatting options
276
- * @param options.minimumDecimals - Global minimum decimal places (overrides range configs)
277
- * @param options.maximumDecimals - Global maximum decimal places (overrides range configs)
278
- * @param options.significantDigits - Global significant digits (overrides decimal settings when set)
279
- * @param options.ranges - Custom range configurations (defaults to PRICE_RANGES_MINIMAL_VIEW)
280
- * @param options.currency - Currency code (default: 'USD')
281
- * @param options.locale - Locale for formatting (default: 'en-US')
282
- * @param options.stripTrailingZeros - Strip trailing zeros from output (default: false via PRICE_RANGES_MINIMAL_VIEW). When true, overrides minimumDecimals constraint.
283
- * @returns Formatted currency string with variable decimals based on configured ranges
420
+ * @param balance - Raw numeric value (e.g., 1234.56, not token minimal denomination).
421
+ * @param options - Formatting options.
422
+ * @param options.formatters - Locale-bound formatters, e.g. `createFormatters({ locale: 'de' })` from `@metamask/client-utils` (default `en-US`).
423
+ * @param options.decimals - Fixed decimal places (e.g. `PERPS_DISPLAY_PRECISION.Fee`), overriding the range.
424
+ * @param options.sign - Sign display (default `auto`: `-` for negative values only).
425
+ * @param options.minimumDecimals - Global minimum decimal places (overrides `decimals` and range configs).
426
+ * @param options.maximumDecimals - Global maximum decimal places (overrides `decimals` and range configs).
427
+ * @param options.significantDigits - Global significant digits (overrides decimal settings when set).
428
+ * @param options.ranges - Custom range configurations (defaults to PRICE_RANGES_MINIMAL_VIEW).
429
+ * @param options.currency - Currency code (default: 'USD').
430
+ * @param options.stripTrailingZeros - Strip trailing zeros from output. `false` keeps them; otherwise the range decides (default: strip).
431
+ * @param options.locale - Locale passed to a range's `customFormat` only (default `en-US`).
432
+ * @returns Formatted currency string, or `PERPS_CONSTANTS.FallbackPriceDisplay`
433
+ * (`$---`) for a missing value.
284
434
  * @example
285
- * // Using defaults (preserves trailing zeros for fiat)
286
435
  * formatPerpsFiat(1234.56) => "$1,234.56"
287
- * formatPerpsFiat(1250.00) => "$1,250.00" // Trailing zeros preserved
288
- * formatPerpsFiat(50000) => "$50,000.00" // Trailing zeros preserved
289
- *
290
- * // Stripping trailing zeros when needed (e.g., for crypto)
291
- * formatPerpsFiat(1250, { stripTrailingZeros: true }) => "$1,250"
292
- *
293
- * // With custom ranges
294
- * formatPerpsFiat(0.00001, {
295
- * ranges: [
296
- * { condition: (v) => v < 0.001, minimumDecimals: 6, maximumDecimals: 8 },
297
- * { condition: () => true, minimumDecimals: 2, maximumDecimals: 2 }
298
- * ]
299
- * }) => "$0.00001" // Trailing zero stripped
300
- *
301
- * // With significant digits
302
- * formatPerpsFiat(1234.56789, { significantDigits: 5 }) => "$1,234.6"
303
- * formatPerpsFiat(0.0001234, { significantDigits: 3 }) => "$0.000123"
436
+ * formatPerpsFiat(1250) => "$1,250" // fiat-style stripping of .00
437
+ * formatPerpsFiat(-0.004) => "-<$0.01" // below the range threshold
438
+ * formatPerpsFiat(1234.5, { formatters: createFormatters({ locale: 'de' }) }) => "1.234,50 $"
439
+ * formatPerpsFiat(12345.67, { ranges: PRICE_RANGES_UNIVERSAL }) => "$12,346"
440
+ * formatPerpsFiat(undefined) => "$---"
304
441
  */
305
442
  export const formatPerpsFiat = (balance, options) => {
306
- const value = typeof balance === 'string' ? parseFloat(balance) : balance;
307
- const currency = options?.currency ?? 'USD';
308
- let formatted;
309
- if (isNaN(value)) {
310
- // Return placeholder for invalid values to avoid confusion with actual $0 values
443
+ const value = _parseDisplayNumber(balance);
444
+ if (value === undefined) {
445
+ // Placeholder for missing values to avoid confusion with actual $0 values
311
446
  return PERPS_CONSTANTS.FallbackPriceDisplay;
312
447
  }
313
- // Use custom ranges or defaults
448
+ const currency = options?.currency ?? 'USD';
314
449
  const ranges = options?.ranges ?? PRICE_RANGES_MINIMAL_VIEW;
315
450
  // Find the first matching range configuration
316
451
  const rangeConfig = ranges.find((range) => range.condition(value));
317
- if (rangeConfig) {
318
- // Check for significant digits (global or range-specific)
319
- const sigDigits = options?.significantDigits ?? rangeConfig.significantDigits;
320
- // If significant digits are specified, use them
321
- if (sigDigits) {
322
- // Get min/max decimals (global overrides range, range overrides default)
323
- const minDecimals = options?.minimumDecimals ?? rangeConfig.minimumDecimals;
324
- const maxDecimals = options?.maximumDecimals ?? rangeConfig.maximumDecimals;
325
- // Calculate appropriate formatting based on significant digits
326
- const { value: formattedValue, decimals } = formatWithSignificantDigits(value, sigDigits, minDecimals, maxDecimals);
327
- // Format with the calculated decimal places
328
- formatted = _formatWithThreshold(formattedValue, rangeConfig.threshold ?? 0.01, {
329
- currency,
330
- minimumFractionDigits: decimals,
331
- maximumFractionDigits: decimals,
332
- });
333
- }
334
- else {
335
- // Standard decimal-based formatting (existing logic)
336
- const minDecimals = options?.minimumDecimals ?? rangeConfig.minimumDecimals;
337
- const maxDecimals = options?.maximumDecimals ?? rangeConfig.maximumDecimals;
338
- // Use custom formatting if provided
339
- if (rangeConfig.customFormat) {
340
- formatted = rangeConfig.customFormat(value, options?.locale ?? 'en-US', currency);
341
- }
342
- else {
343
- // Use standard formatting with threshold
344
- formatted = _formatWithThreshold(value, rangeConfig.threshold ?? 0.01, {
345
- currency,
346
- minimumFractionDigits: minDecimals,
347
- maximumFractionDigits: maxDecimals,
348
- });
349
- }
350
- }
452
+ const sigDigits = options?.significantDigits ?? rangeConfig?.significantDigits;
453
+ if (rangeConfig?.customFormat && !sigDigits) {
454
+ return rangeConfig.customFormat(value, options?.locale ?? 'en-US', currency);
351
455
  }
352
- else {
353
- // Fallback if no range matches (shouldn't happen with proper default config)
354
- const fallbackMin = options?.minimumDecimals ?? 2;
355
- const fallbackMax = options?.maximumDecimals ?? 2;
356
- formatted = _formatWithThreshold(value, 0.01, {
357
- currency,
358
- minimumFractionDigits: fallbackMin,
359
- maximumFractionDigits: fallbackMax,
360
- });
456
+ // Strip trailing zeros unless explicitly disabled. Priority: explicit
457
+ // `stripTrailingZeros: false` > range config > option > true.
458
+ let strip = 'none';
459
+ if (options?.stripTrailingZeros !== false &&
460
+ (rangeConfig?.stripTrailingZeros ?? options?.stripTrailingZeros ?? true)) {
461
+ // Fiat-style only strips .00: "$1,250.00" → "$1,250", "$13.40" stays
462
+ strip = rangeConfig?.fiatStyleStripping ? 'fiat' : 'all';
361
463
  }
362
- // Post-process: strip trailing zeros unless explicitly disabled
363
- // Priority: explicit options.stripTrailingZeros false > rangeConfig > options default > true
364
- // If options.stripTrailingZeros is explicitly false, skip stripping entirely
365
- if (options?.stripTrailingZeros === false) {
366
- return formatted;
464
+ let minDecimals = options?.minimumDecimals ??
465
+ options?.decimals ??
466
+ rangeConfig?.minimumDecimals ??
467
+ 2;
468
+ let maxDecimals = options?.maximumDecimals ??
469
+ options?.decimals ??
470
+ rangeConfig?.maximumDecimals ??
471
+ 2;
472
+ let amount = Math.abs(value);
473
+ if (rangeConfig && sigDigits) {
474
+ // Calculate appropriate formatting based on significant digits
475
+ const significant = formatWithSignificantDigits(value, sigDigits, minDecimals, maxDecimals);
476
+ amount = Math.abs(significant.value);
477
+ minDecimals = significant.decimals;
478
+ maxDecimals = significant.decimals;
367
479
  }
368
- // Otherwise check range config or default to true
369
- const shouldStrip = rangeConfig?.stripTrailingZeros ?? options?.stripTrailingZeros ?? true;
370
- if (shouldStrip) {
371
- // Check if fiat-style stripping is enabled (only strips .00)
372
- const useFiatStyle = rangeConfig?.fiatStyleStripping ?? false;
373
- if (useFiatStyle) {
374
- // Fiat-style: Only strip .00 (no meaningful decimals), preserve 2-decimal format
375
- // Examples: $1,250.00 → $1,250 | $1,000.10 → $1,000.10 | $13.40 → $13.40
376
- return formatted.replace(/\.00$/u, '');
377
- }
378
- // Standard: Strip all trailing zeros after decimal point
379
- // Examples: $1,250.00 → $1,250 | $100.0 → $100 | $10.5 → $10.5 | $1.234 → $1.234
380
- return formatted.replace(/(\.\d*?)0+$/u, '$1').replace(/\.$/u, '');
381
- }
382
- return formatted;
480
+ // A non-zero amount below the threshold shows "<$threshold"
481
+ const threshold = rangeConfig?.threshold ?? PRICE_THRESHOLD.LOW;
482
+ const isBelowThreshold = amount !== 0 && amount < threshold;
483
+ const body = _formatCurrency(options?.formatters ?? _fallbackFormatters, isBelowThreshold ? threshold : amount, {
484
+ currency,
485
+ minimumFractionDigits: minDecimals,
486
+ maximumFractionDigits: maxDecimals,
487
+ strip,
488
+ });
489
+ const isZero = !isBelowThreshold && _currencyShowsZero(amount, maxDecimals);
490
+ return `${_signPrefix(value, isZero, options?.sign ?? 'auto')}${isBelowThreshold ? '<' : ''}${body}`;
383
491
  };
384
492
  /**
385
493
  * Formats position size with variable decimal precision based on magnitude or asset-specific decimals
386
- * Removes trailing zeros to match task requirements
494
+ * Removes trailing zeros and never groups thousands.
387
495
  *
388
496
  * @param size - Raw position size value
389
- * @param szDecimals - Optional asset-specific decimal precision from Hyperliquid metadata (e.g., BTC=5, ETH=4, DOGE=1)
497
+ * @param szDecimalsOrOptions - Asset-specific decimal precision from Hyperliquid metadata
498
+ * (e.g., BTC=5, ETH=4, DOGE=1), or options:
499
+ * `decimals` (the same precision), `formatters` (default `en-US`) and `sign` (default `auto`).
390
500
  * @returns Format varies by size or uses asset-specific decimals, with trailing zeros removed:
391
- * If szDecimals provided: Uses exact decimals (e.g., 0.00009 BTC with szDecimals=5 => "0.00009")
501
+ * If decimals are provided: Uses at most those decimals (e.g., 0.00009 BTC with szDecimals=5 => "0.00009")
392
502
  * Otherwise falls back to magnitude-based logic:
393
503
  * - Size < 0.01: Up to 6 decimals (e.g., "0.00009" not "0.000090")
394
504
  * - Size < 1: Up to 4 decimals (e.g., "0.0024" not "0.002400")
395
505
  * - Size >= 1: Up to 2 decimals (e.g., "44" not "44.00")
506
+ * A missing value returns `PERPS_CONSTANTS.FallbackDataDisplay` (`--`).
396
507
  * @example formatPositionSize(0.00009, 5) => "0.00009" (uses szDecimals)
397
508
  * @example formatPositionSize(44.00, 1) => "44" (uses szDecimals, trailing zeros removed)
398
509
  * @example formatPositionSize(0.0024) => "0.0024" (no szDecimals, uses magnitude logic)
399
- * @example formatPositionSize(44.00) => "44" (no szDecimals, uses magnitude logic)
510
+ * @example formatPositionSize(-1234.5, { decimals: 2, formatters: createFormatters({ locale: 'es' }) }) => "-1234,5"
511
+ * @example formatPositionSize(undefined) => "--"
400
512
  */
401
- export const formatPositionSize = (size, szDecimals) => {
402
- const value = typeof size === 'string' ? parseFloat(size) : size;
403
- if (isNaN(value) || value === 0) {
404
- return '0';
513
+ export const formatPositionSize = (size, szDecimalsOrOptions) => {
514
+ const { formatters = _fallbackFormatters, decimals, sign = 'auto', } = typeof szDecimalsOrOptions === 'number'
515
+ ? { decimals: szDecimalsOrOptions }
516
+ : (szDecimalsOrOptions ?? {});
517
+ const value = _parseDisplayNumber(size);
518
+ if (value === undefined) {
519
+ return PERPS_CONSTANTS.FallbackDataDisplay;
405
520
  }
406
- // Use asset-specific decimals if provided (Hyperliquid metadata)
407
- if (szDecimals !== undefined) {
408
- const fixed = value.toFixed(szDecimals);
409
- // Only strip trailing zeros when a decimal point is present; toFixed(0)
410
- // returns an integer string and the regex would otherwise eat valid zeros
411
- // on whole-unit assets (szDecimals=0), e.g. "100" -> "1".
412
- return fixed.includes('.') ? fixed.replace(/\.?0+$/u, '') : fixed;
413
- }
414
- // Fallback: magnitude-based decimal logic for backwards compatibility
415
521
  const abs = Math.abs(value);
416
- let formatted;
417
- if (abs < 0.01) {
418
- // For very small numbers, use more decimal places
419
- formatted = value.toFixed(6);
420
- }
421
- else if (abs < 1) {
422
- // For small numbers, use 4 decimal places
423
- formatted = value.toFixed(4);
424
- }
425
- else {
426
- // For normal numbers, use 2 decimal places
427
- formatted = value.toFixed(2);
522
+ let maxDecimals = decimals;
523
+ // Fallback: magnitude-based decimal logic for backwards compatibility
524
+ if (maxDecimals === undefined) {
525
+ if (abs < 0.01) {
526
+ maxDecimals = 6;
527
+ }
528
+ else if (abs < 1) {
529
+ maxDecimals = 4;
530
+ }
531
+ else {
532
+ maxDecimals = 2;
533
+ }
428
534
  }
429
- // Remove trailing zeros and unnecessary decimal point
430
- return formatted.replace(/\.?0+$/u, '');
535
+ return _formatSignedDecimal(formatters, value, {
536
+ minimumFractionDigits: 0,
537
+ maximumFractionDigits: maxDecimals,
538
+ useGrouping: false,
539
+ sign,
540
+ });
431
541
  };
432
542
  /**
433
- * Formats a PnL (Profit and Loss) value with sign prefix
543
+ * Formats a PnL (Profit and Loss) value as USD with a sign prefix
434
544
  *
435
545
  * @param pnl - Raw numeric PnL value (positive for profit, negative for loss)
436
- * @returns Format: "+$X,XXX.XX" or "-$X,XXX.XX" (always shows sign, 2 decimals)
546
+ * @param options - `formatters` (default `en-US`), `decimals` (default
547
+ * `PERPS_DISPLAY_PRECISION.Pnl`, 2) and `sign` (default `always`).
548
+ * @returns Format: "+$X,XXX.XX" or "-$X,XXX.XX", or
549
+ * `PERPS_CONSTANTS.FallbackPriceDisplay` (`$---`) for a missing value.
437
550
  * @example formatPnl(1234.56) => "+$1,234.56"
438
551
  * @example formatPnl(-500) => "-$500.00"
439
552
  * @example formatPnl(0) => "+$0.00"
553
+ * @example formatPnl(0, { sign: 'exceptZero' }) => "$0.00"
554
+ * @example formatPnl(1234.5, { formatters: createFormatters({ locale: 'es' }) }) => "+1234,50 $"
555
+ * @example formatPnl(undefined) => "$---"
440
556
  */
441
- export const formatPnl = (pnl) => {
442
- const value = typeof pnl === 'string' ? parseFloat(pnl) : pnl;
443
- if (isNaN(value)) {
444
- return PERPS_CONSTANTS.ZeroAmountDetailedDisplay;
557
+ export const formatPnl = (pnl, options = {}) => {
558
+ const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.Pnl, sign = 'always', } = options;
559
+ const value = _parseDisplayNumber(pnl);
560
+ if (value === undefined) {
561
+ return PERPS_CONSTANTS.FallbackPriceDisplay;
445
562
  }
446
- const formatted = _formatCurrency(Math.abs(value), 'USD', {
447
- minimumFractionDigits: 2,
448
- maximumFractionDigits: 2,
563
+ const amount = Math.abs(value);
564
+ const formatted = _formatCurrency(formatters, amount, {
565
+ currency: 'USD',
566
+ minimumFractionDigits: decimals,
567
+ maximumFractionDigits: decimals,
568
+ strip: 'none',
449
569
  });
450
- return value >= 0 ? `+${formatted}` : `-${formatted}`;
570
+ return `${_signPrefix(value, _currencyShowsZero(amount, decimals), sign)}${formatted}`;
451
571
  };
452
572
  /**
453
- * Formats a percentage value with sign prefix
573
+ * Formats a percentage value (change, RoE, fee rate, slippage) with a sign
574
+ * prefix and locale separators. Pick the precision from
575
+ * `PERPS_DISPLAY_PRECISION`.
454
576
  *
455
577
  * @param value - Raw percentage value (e.g., 5.25 for 5.25%, not 0.0525)
456
- * @param decimals - Number of decimal places to show (default: 2)
457
- * @returns Format: "+X.XX%" or "-X.XX%" (always shows sign, 2 decimals)
578
+ * @param decimalsOrOptions - Decimal places (default:
579
+ * `PERPS_DISPLAY_PRECISION.Percentage`, 2), or options: `decimals`,
580
+ * `formatters` (default `en-US`) and `sign` (default `always`).
581
+ * @returns Format: "+X.XX%" or "-X.XX%", or
582
+ * `PERPS_CONSTANTS.FallbackPercentageDisplay` (`--%`) for a missing value.
458
583
  * @example formatPercentage(5.25) => "+5.25%"
459
584
  * @example formatPercentage(-2.75) => "-2.75%"
460
585
  * @example formatPercentage(0) => "+0.00%"
586
+ * @example formatPercentage(10.25, { decimals: PERPS_DISPLAY_PRECISION.RoePercent }) => "+10.3%"
587
+ * @example formatPercentage(0.0021, { decimals: PERPS_DISPLAY_PRECISION.SlippageEstimatePercent, sign: 'never' }) => "0.0021%"
588
+ * @example formatPercentage(-12345.67, { decimals: 1, formatters: createFormatters({ locale: 'es' }) }) => "-12.345,7%"
589
+ * @example formatPercentage(undefined) => "--%"
461
590
  */
462
- export const formatPercentage = (value, decimals = 2) => {
463
- const parsed = typeof value === 'string' ? parseFloat(value) : value;
464
- if (isNaN(parsed)) {
465
- return '0.00%';
591
+ export const formatPercentage = (value, decimalsOrOptions) => {
592
+ const { formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.Percentage, sign = 'always', } = typeof decimalsOrOptions === 'number'
593
+ ? { decimals: decimalsOrOptions }
594
+ : (decimalsOrOptions ?? {});
595
+ const parsed = _parseDisplayNumber(value);
596
+ if (parsed === undefined) {
597
+ return PERPS_CONSTANTS.FallbackPercentageDisplay;
466
598
  }
467
- return `${parsed >= 0 ? '+' : ''}${parsed.toFixed(decimals)}%`;
599
+ return `${_formatSignedDecimal(formatters, parsed, {
600
+ minimumFractionDigits: decimals,
601
+ maximumFractionDigits: decimals,
602
+ useGrouping: true,
603
+ sign,
604
+ })}%`;
468
605
  };
469
606
  /**
470
607
  * Formats funding rate for display
471
608
  *
472
609
  * @param value - Raw funding rate value (decimal, not percentage)
473
610
  * @param options - Optional formatting options
474
- * @param options.showZero - Whether to return zero display value for zero/undefined (default: true)
475
- * @returns Formatted funding rate as percentage string
611
+ * @param options.showZero - `false` returns an empty string instead of the placeholder for a missing rate (default: true)
612
+ * @param options.formatters - Locale-bound formatters, e.g. `createFormatters({ locale })` from `@metamask/client-utils` (default `en-US`)
613
+ * @param options.decimals - Decimal places (default `PERPS_DISPLAY_PRECISION.FundingRatePercent`, 4)
614
+ * @param options.sign - Sign display (default `auto`: `-` for negative rates only)
615
+ * @returns Formatted funding rate as percentage string, or
616
+ * `PERPS_CONSTANTS.FallbackPercentageDisplay` (`--%`) for a missing rate.
476
617
  * @example formatFundingRate(0.0005) => "0.0500%"
477
618
  * @example formatFundingRate(-0.0001) => "-0.0100%"
478
619
  * @example formatFundingRate(0.000000059) => "<0.0001%"
479
620
  * @example formatFundingRate(-0.000000059) => "-<0.0001%"
480
- * @example formatFundingRate(undefined) => "0.0000%"
621
+ * @example formatFundingRate(0.0005, { sign: 'always', formatters: createFormatters({ locale: 'es' }) }) => "+0,0500%"
622
+ * @example formatFundingRate(undefined) => "--%"
481
623
  */
482
- export const formatFundingRate = (value, options) => {
483
- const showZero = options?.showZero ?? true;
484
- if (value === undefined || value === null) {
485
- return showZero ? FUNDING_RATE_CONFIG.ZeroDisplay : '';
486
- }
487
- const percentage = value * FUNDING_RATE_CONFIG.PercentageMultiplier;
488
- const formatted = percentage.toFixed(FUNDING_RATE_CONFIG.Decimals);
489
- const minimumDisplayPercentage = 10 ** -FUNDING_RATE_CONFIG.Decimals;
490
- if (value !== 0 && parseFloat(formatted) === 0) {
491
- const threshold = minimumDisplayPercentage.toFixed(FUNDING_RATE_CONFIG.Decimals);
492
- return value > 0 ? `<${threshold}%` : `-<${threshold}%`;
624
+ export const formatFundingRate = (value, options = {}) => {
625
+ const { showZero = true, formatters = _fallbackFormatters, decimals = PERPS_DISPLAY_PRECISION.FundingRatePercent, sign = 'auto', } = options;
626
+ const rate = _parseDisplayNumber(value);
627
+ if (rate === undefined) {
628
+ return showZero ? PERPS_CONSTANTS.FallbackPercentageDisplay : '';
493
629
  }
494
- // Check if the result is effectively zero
495
- if (showZero && parseFloat(formatted) === 0) {
496
- return FUNDING_RATE_CONFIG.ZeroDisplay;
630
+ const percentage = rate * FUNDING_RATE_CONFIG.PercentageMultiplier;
631
+ // A non-zero rate below the display precision shows "<0.0001%"
632
+ if (rate !== 0 && _roundedMagnitude(percentage, decimals) === 0) {
633
+ const minimum = _formatDecimal(formatters, 10 ** -decimals, decimals, decimals, true);
634
+ return `${_signPrefix(rate, false, sign)}<${minimum}%`;
497
635
  }
498
- return `${formatted}%`;
636
+ return `${_formatSignedDecimal(formatters, percentage, {
637
+ minimumFractionDigits: decimals,
638
+ maximumFractionDigits: decimals,
639
+ useGrouping: true,
640
+ sign,
641
+ })}%`;
499
642
  };
500
643
  //# sourceMappingURL=perpsFormatters.js.map