diff --git a/src/components/common/KeySimulationTool.tsx b/src/components/common/KeySimulationTool.tsx index 626998bc..72958912 100644 --- a/src/components/common/KeySimulationTool.tsx +++ b/src/components/common/KeySimulationTool.tsx @@ -181,155 +181,6 @@ const KeySimulationTool: React.FC = ({ -import React, { useEffect, useRef, useState } from 'react'; -import { courseService } from '@/services/course.service'; -import { - calculatePriceImpact, - formatPriceImpact, -} from '@/utils/priceImpact.utils'; - -export interface KeySimulationToolProps { - /** Key identifier used for GET /keys/:keyId/simulate?quantity=N */ - keyId: string; - /** Current spot price in the same unit as simulated_price (e.g. XLM or stroops) */ - spotPrice: number; - /** Optional initial quantity */ - initialQuantity?: number; -} - -interface SimulateResult { - simulated_price?: number; - simulatedPrice?: number; - spot_price?: number; - spotPrice?: number; -} - -/** - * Key price simulation tool (#887). - * - * Lets the user enter a custom quantity, debounces the input by 300ms, - * fetches GET /keys/:keyId/simulate?quantity=N, computes price impact as - * (simulated_price - spot_price) / spot_price * 100 and displays it. - * - * Loading shows a skeleton, fetch errors show 'Unable to simulate price' - * and hide the impact value. - */ -const KeySimulationTool: React.FC = ({ - keyId, - spotPrice, - initialQuantity = 1, -}) => { - const [quantityInput, setQuantityInput] = useState( - String(initialQuantity) - ); - const [simulatedPrice, setSimulatedPrice] = useState(null); - const [resolvedSpotPrice, setResolvedSpotPrice] = useState(spotPrice); - const [loading, setLoading] = useState(false); - const [error, setError] = useState(null); - const debounceRef = useRef | null>(null); - - // Keep spot price in sync when prop changes - useEffect(() => { - setResolvedSpotPrice(spotPrice); - }, [spotPrice]); - - useEffect(() => { - const quantity = Number(quantityInput); - // Empty or invalid quantity: clear simulation - if (quantityInput.trim() === '' || isNaN(quantity) || quantity <= 0) { - setSimulatedPrice(null); - setError(null); - setLoading(false); - return; - } - - if (debounceRef.current) clearTimeout(debounceRef.current); - - setLoading(true); - setError(null); - - debounceRef.current = setTimeout(async () => { - try { - const result: SimulateResult = - await courseService.simulateBuy(keyId, quantity); - // Support both snake_case and camelCase shapes - const sim = - result.simulated_price ?? result.simulatedPrice ?? null; - const spot = - result.spot_price ?? result.spotPrice ?? spotPrice; - if (sim != null) { - setSimulatedPrice(sim); - if (spot != null) setResolvedSpotPrice(spot); - setError(null); - } else { - setSimulatedPrice(null); - } - } catch { - setError('Unable to simulate price'); - setSimulatedPrice(null); - } finally { - setLoading(false); - } - }, 300); - - return () => { - if (debounceRef.current) clearTimeout(debounceRef.current); - }; - }, [quantityInput, keyId, spotPrice]); - - const impact = - simulatedPrice != null - ? calculatePriceImpact(simulatedPrice, resolvedSpotPrice) - : null; - - return ( -
-
- - setQuantityInput(e.target.value)} - className="w-full rounded-md border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-white placeholder:text-white/30 outline-none" - placeholder="Enter quantity" - /> -
- - {loading && ( -
- )} - - {!loading && error && ( -

- {error} -

- )} - - {!loading && !error && impact != null && ( -

- {formatPriceImpact(impact)} -

)}
); diff --git a/src/components/common/SlippageToleranceSelector.tsx b/src/components/common/SlippageToleranceSelector.tsx index f249bbf1..60b1f9c9 100644 --- a/src/components/common/SlippageToleranceSelector.tsx +++ b/src/components/common/SlippageToleranceSelector.tsx @@ -11,29 +11,6 @@ export interface SlippageToleranceSelectorProps { value: number; onChange: (percent: number) => void; disabled?: boolean; - computeSlippagePriceBounds, - validateSlippageTolerance, - SLIPPAGE_TOLERANCE_PRESETS, - type TradeSide, -} from '@/utils/slippageTolerance.utils'; - -export interface SlippageToleranceSelectorProps { - /** The quoted/preview price the tolerance is applied against. */ - previewPrice: number; - /** Whether this trade is a buy (computes max_price) or sell (min_price). */ - side: TradeSide; - /** Called whenever the selected tolerance changes with a valid value. */ - onToleranceChange?: (tolerancePercent: number) => void; - /** - * Called with the confirm-eligibility state whenever it changes, so a - * parent trade dialog can disable its own confirm button in lockstep. - */ - onValidityChange?: (canConfirm: boolean) => void; - /** Called when the confirm button is clicked while the tolerance is valid. */ - onConfirm?: (bounds: { - maxPrice: number | null; - minPrice: number | null; - }) => void; className?: string; } @@ -79,63 +56,6 @@ const SlippageToleranceSelector: React.FC = ({ const parsed = Number(normalized); if (validateSlippageTolerancePercent(parsed) === null) { onChange(parsed); - * Slippage tolerance selector — issue #877 / #784 trade flow. - * - * Lets the user pick a preset tolerance (0.5% / 1% / 5%) or enter a custom - * percentage, and displays the resulting max_price (buy) / min_price (sell) - * bound. A custom tolerance above 50% is rejected with a validation error - * and disables the confirm action. - */ -const SlippageToleranceSelector: React.FC = ({ - previewPrice, - side, - onToleranceChange, - onValidityChange, - onConfirm, - className, -}) => { - const [selectedPreset, setSelectedPreset] = useState( - SLIPPAGE_TOLERANCE_PRESETS[0] - ); - const [customValue, setCustomValue] = useState(''); - const [isCustom, setIsCustom] = useState(false); - - const activeToleranceText = isCustom - ? customValue - : String(selectedPreset ?? ''); - const parsedTolerance = activeToleranceText.trim() - ? Number(activeToleranceText) - : NaN; - - const validation = useMemo( - () => validateSlippageTolerance(parsedTolerance), - [parsedTolerance] - ); - - const bounds = useMemo(() => { - if (!validation.valid) return { maxPrice: null, minPrice: null }; - return computeSlippagePriceBounds(previewPrice, parsedTolerance, side); - }, [validation.valid, previewPrice, parsedTolerance, side]); - - const canConfirm = validation.valid; - - const selectPreset = (preset: number) => { - setIsCustom(false); - setSelectedPreset(preset); - onToleranceChange?.(preset); - onValidityChange?.(true); - }; - - const handleCustomChange = (rawValue: string) => { - setIsCustom(true); - setSelectedPreset(null); - setCustomValue(rawValue); - - const parsed = rawValue.trim() ? Number(rawValue) : NaN; - const result = validateSlippageTolerance(parsed); - onValidityChange?.(result.valid); - if (result.valid) { - onToleranceChange?.(parsed); } }; @@ -209,70 +129,6 @@ const SlippageToleranceSelector: React.FC = ({ {SLIPPAGE_TOLERANCE_BOUNDS.MAX_PERCENT}%. The trade will revert if the price moves beyond your tolerance before it executes.

-
-
Slippage tolerance
-
- {SLIPPAGE_TOLERANCE_PRESETS.map(preset => ( - - ))} - handleCustomChange(event.target.value)} - onFocus={() => setIsCustom(true)} - aria-label="Custom slippage tolerance" - data-testid="slippage-custom-input" - className={cn( - 'w-24 rounded-md border bg-white/[0.04] px-2 py-1 text-xs text-white outline-none transition-colors', - 'border-white/10 focus:border-amber-500/50', - isCustom && !validation.valid ? 'border-red-500/60' : '' - )} - /> -
- - {isCustom && !validation.valid && ( -

- {validation.error} -

- )} - - {validation.valid && ( -

- {side === 'buy' - ? `Max price: ${bounds.maxPrice} XLM` - : `Min price: ${bounds.minPrice} XLM`} -

- )} - -
); }; diff --git a/src/components/common/__tests__/SlippageToleranceSelector.test.tsx b/src/components/common/__tests__/SlippageToleranceSelector.test.tsx index 2e0cd20b..e4a5d953 100644 --- a/src/components/common/__tests__/SlippageToleranceSelector.test.tsx +++ b/src/components/common/__tests__/SlippageToleranceSelector.test.tsx @@ -88,112 +88,5 @@ describe('SlippageToleranceSelector', () => { fireEvent.change(input, { target: { value: '3' } }); fireEvent.click(screen.getByTestId('slippage-preset-0.5')); expect(input).toHaveValue(''); -import { render, screen } from '@testing-library/react'; -import userEvent from '@testing-library/user-event'; -import React from 'react'; - -import SlippageToleranceSelector from '@/components/common/SlippageToleranceSelector'; - -describe('SlippageToleranceSelector (#877)', () => { - it('shows max_price of 100.5 XLM for the 0.5% preset on a 100 XLM buy preview', () => { - render(); - - // 0.5% is the default-selected preset. - expect(screen.getByTestId('slippage-price-bound')).toHaveTextContent( - 'Max price: 100.5 XLM' - ); - }); - - it('shows max_price of 105 XLM after selecting the 5% preset', async () => { - const user = userEvent.setup(); - render(); - - await user.click(screen.getByTestId('slippage-preset-5')); - - expect(screen.getByTestId('slippage-price-bound')).toHaveTextContent( - 'Max price: 105 XLM' - ); - }); - - it('shows min_price of 99 XLM after selecting the 1% preset on a sell', async () => { - const user = userEvent.setup(); - render(); - - await user.click(screen.getByTestId('slippage-preset-1')); - - expect(screen.getByTestId('slippage-price-bound')).toHaveTextContent( - 'Min price: 99 XLM' - ); - }); - - it('sets max_price equal to the preview price for a custom 0% tolerance', async () => { - const user = userEvent.setup(); - render(); - - await user.type(screen.getByTestId('slippage-custom-input'), '0'); - - expect(screen.getByTestId('slippage-price-bound')).toHaveTextContent( - 'Max price: 100 XLM' - ); - expect( - screen.queryByTestId('slippage-validation-error') - ).not.toBeInTheDocument(); - expect(screen.getByTestId('slippage-confirm-button')).toBeEnabled(); - }); - - it('shows a validation error and disables the confirm button for a custom tolerance above 50%', async () => { - const user = userEvent.setup(); - const onValidityChange = vi.fn(); - render( - - ); - - await user.type(screen.getByTestId('slippage-custom-input'), '51'); - - expect(screen.getByTestId('slippage-validation-error')).toHaveTextContent( - /50%/ - ); - expect(screen.getByTestId('slippage-confirm-button')).toBeDisabled(); - expect(onValidityChange).toHaveBeenLastCalledWith(false); - // No stale price-bound should be shown once the input is invalid. - expect( - screen.queryByTestId('slippage-price-bound') - ).not.toBeInTheDocument(); - }); - - it('re-enables the confirm button once a custom tolerance is corrected back into range', async () => { - const user = userEvent.setup(); - render(); - - const input = screen.getByTestId('slippage-custom-input'); - await user.type(input, '75'); - expect(screen.getByTestId('slippage-confirm-button')).toBeDisabled(); - - await user.clear(input); - await user.type(input, '10'); - expect(screen.getByTestId('slippage-confirm-button')).toBeEnabled(); - }); - - it('calls onConfirm with the computed bounds when the confirm button is clicked', async () => { - const user = userEvent.setup(); - const onConfirm = vi.fn(); - render( - - ); - - await user.click(screen.getByTestId('slippage-confirm-button')); - - expect(onConfirm).toHaveBeenCalledWith({ - maxPrice: 100.5, - minPrice: null, - }); }); }); diff --git a/src/utils/__tests__/slippageTolerance.utils.test.ts b/src/utils/__tests__/slippageTolerance.utils.test.ts index 6ae36f0c..d5eb2e17 100644 --- a/src/utils/__tests__/slippageTolerance.utils.test.ts +++ b/src/utils/__tests__/slippageTolerance.utils.test.ts @@ -123,92 +123,5 @@ describe('slippageTolerance.utils', () => { expect(computeSlippageBounds('buy', null, 1).maxPriceStroops).toBeNull(); expect(computeSlippageBounds('sell', undefined, 1).minPriceStroops).toBeNull(); }); -import { describe, expect, it } from 'vitest'; -import { - computeSlippagePriceBounds, - validateSlippageTolerance, - MAX_SLIPPAGE_TOLERANCE_PERCENT, -} from '@/utils/slippageTolerance.utils'; - -describe('computeSlippagePriceBounds (#877)', () => { - it('computes max_price of 100.5 for a 0.5% buy tolerance on a 100 XLM preview', () => { - const { maxPrice, minPrice } = computeSlippagePriceBounds( - 100, - 0.5, - 'buy' - ); - expect(maxPrice).toBe(100.5); - expect(minPrice).toBeNull(); - }); - - it('computes max_price of 105 for a 5% buy tolerance on a 100 XLM preview', () => { - const { maxPrice } = computeSlippagePriceBounds(100, 5, 'buy'); - expect(maxPrice).toBe(105); - }); - - it('computes min_price of 99 for a 1% sell tolerance on a 100 XLM preview', () => { - const { minPrice, maxPrice } = computeSlippagePriceBounds( - 100, - 1, - 'sell' - ); - expect(minPrice).toBe(99); - expect(maxPrice).toBeNull(); - }); - - it('sets max_price equal to the preview price for a custom 0% tolerance', () => { - const { maxPrice } = computeSlippagePriceBounds(100, 0, 'buy'); - expect(maxPrice).toBe(100); - }); - - it('sets min_price equal to the preview price for a custom 0% sell tolerance', () => { - const { minPrice } = computeSlippagePriceBounds(100, 0, 'sell'); - expect(minPrice).toBe(100); - }); - - it('does not accumulate binary floating-point drift for common percentages', () => { - // 100 * 1.005 === 100.49999999999999 in raw IEEE-754 arithmetic; - // the util must round this back to the exact expected value. - expect(computeSlippagePriceBounds(100, 0.5, 'buy').maxPrice).toBe( - 100.5 - ); - expect(computeSlippagePriceBounds(37.5, 1.5, 'buy').maxPrice).toBeCloseTo( - 38.0625, - 7 - ); - }); -}); - -describe('validateSlippageTolerance (#877)', () => { - it('accepts a custom tolerance of 0%', () => { - expect(validateSlippageTolerance(0)).toEqual({ - valid: true, - error: null, - }); - }); - - it('accepts tolerances within the valid range', () => { - expect(validateSlippageTolerance(0.5).valid).toBe(true); - expect(validateSlippageTolerance(25).valid).toBe(true); - expect(validateSlippageTolerance(MAX_SLIPPAGE_TOLERANCE_PERCENT).valid).toBe( - true - ); - }); - - it('rejects a custom tolerance above 50% with a validation error', () => { - const result = validateSlippageTolerance(51); - expect(result.valid).toBe(false); - expect(result.error).toMatch(/50%/); - }); - - it('rejects negative tolerances', () => { - const result = validateSlippageTolerance(-1); - expect(result.valid).toBe(false); - expect(result.error).toBeTruthy(); - }); - - it('rejects non-finite input', () => { - expect(validateSlippageTolerance(NaN).valid).toBe(false); - expect(validateSlippageTolerance(Infinity).valid).toBe(false); }); }); diff --git a/src/utils/slippageTolerance.utils.ts b/src/utils/slippageTolerance.utils.ts index 6b29ec3e..ea354b19 100644 --- a/src/utils/slippageTolerance.utils.ts +++ b/src/utils/slippageTolerance.utils.ts @@ -114,113 +114,4 @@ export function computeSlippageBounds( ? computeMinPriceStroops(previewPriceStroops, toleranceZPercent) : null, }; - * Slippage tolerance selector logic — issue #877. - * - * A trade preview's `max_price` (for buys) or `min_price` (for sells) is - * the preview price adjusted by the user's selected slippage tolerance: - * buys accept paying up to `tolerance%` more than the preview price, sells - * accept receiving up to `tolerance%` less. - */ - -/** Preset tolerance options shown in the slippage selector, in percent. */ -export const SLIPPAGE_TOLERANCE_PRESETS = [0.5, 1, 5] as const; - -/** Tolerances above this percentage are rejected as invalid. */ -export const MAX_SLIPPAGE_TOLERANCE_PERCENT = 50; - -/** Tolerances below this percentage are rejected as invalid. */ -export const MIN_SLIPPAGE_TOLERANCE_PERCENT = 0; - -export type TradeSide = 'buy' | 'sell'; - -export interface SlippagePriceBounds { - /** - * Highest price the trade will accept paying, for a buy. `null` for - * sell-side computations. - */ - maxPrice: number | null; - /** - * Lowest price the trade will accept receiving, for a sell. `null` for - * buy-side computations. - */ - minPrice: number | null; -} - -/** - * Decimal places prices are rounded to. Guards against binary - * floating-point drift (e.g. `100 * 1.005` landing on 100.49999999999999 - * instead of 100.5) — XLM prices in this app are never displayed or - * compared at finer than micro-XLM precision. - */ -const PRICE_DECIMAL_PLACES = 7; - -function roundPrice(value: number): number { - const factor = 10 ** PRICE_DECIMAL_PLACES; - return Math.round(value * factor) / factor; -} - -/** - * Computes the max_price (buy) or min_price (sell) bound for a trade given - * the preview price and a slippage tolerance percentage. - * - * @param previewPrice The quoted/preview price before slippage is applied. - * @param tolerancePercent Slippage tolerance as a percent (e.g. 0.5 for 0.5%). - * @param side Whether this is a 'buy' (computes max_price) or 'sell' - * (computes min_price). - */ -export function computeSlippagePriceBounds( - previewPrice: number, - tolerancePercent: number, - side: TradeSide -): SlippagePriceBounds { - const multiplier = tolerancePercent / 100; - - if (side === 'buy') { - return { - maxPrice: roundPrice(previewPrice * (1 + multiplier)), - minPrice: null, - }; - } - - return { - maxPrice: null, - minPrice: roundPrice(previewPrice * (1 - multiplier)), - }; -} - -export interface SlippageToleranceValidation { - valid: boolean; - /** Human-readable validation error, or `null` when the tolerance is valid. */ - error: string | null; -} - -/** - * Validates a (typically custom) slippage tolerance percentage. - * - * Valid range is [0, 50]. Anything above 50% is rejected as an unreasonably - * high tolerance that would let a trade execute far away from the preview - * price; negative values and non-finite input are also rejected. - */ -export function validateSlippageTolerance( - tolerancePercent: number -): SlippageToleranceValidation { - if (!Number.isFinite(tolerancePercent)) { - return { valid: false, error: 'Enter a valid slippage tolerance.' }; - } - - if (tolerancePercent < MIN_SLIPPAGE_TOLERANCE_PERCENT) { - return { - valid: false, - error: 'Slippage tolerance cannot be negative.', - }; - } - - if (tolerancePercent > MAX_SLIPPAGE_TOLERANCE_PERCENT) { - return { - valid: false, - error: `Slippage tolerance cannot exceed ${MAX_SLIPPAGE_TOLERANCE_PERCENT}%.`, - }; - } - - return { valid: true, error: null }; }