Skip to content

Conversation

originalix
Copy link
Collaborator

@originalix originalix commented Sep 26, 2025

Summary by CodeRabbit

  • New Features

    • Interactive size slider on mobile and desktop with max, step, controlled value and real-time updates.
  • Enhancements

    • Real-time calculations for total value and margin requirements.
    • Smarter market vs. limit price handling with a unified price input (disabled for market).
    • Clear “available to trade” display formatting across the UI.
    • More accurate max size and leverage handling based on current prices and balances.
    • Consistent reference price used across inputs and displays.
  • Bug Fixes

    • Prevents stale price updates during token switches and ensures reliable first-load initialization.

Copy link
Contributor

coderabbitai bot commented Sep 26, 2025

Walkthrough

Adds token-switch guarding, reference-price derivation, slider-driven size mechanics, and derived trade calculations to PerpTradingForm. Refactors price input behavior for market vs limit, updates available-to-trade display handling, and renders size sliders for mobile and desktop with proper initialization and synchronization after token changes.

Changes

Cohort / File(s) Summary of changes
Perp trading form logic and UI
packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx
- Import Slider and wire slider UI for mobile & desktop
- Add token-switch effect to prevent stale-price use and initialize token ref on first load
- Compute referencePrice (limit or market) and referencePriceString
- Replace raw availableToTrade with { display, value } pair and update UI text
- Add derived values: totalValue, marginRequired
- Build sliderConfig (effective price, safe leverage, maxSize, current/controlled value, validity)
- Implement sliderStep and handleSizeSliderChange to clamp/format size by decimals
- Disable price input when market, refactor price input handling

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Form as PerpTradingForm
  participant Token as TokenState
  participant Price as MarketData/Price

  Note over Form,Token: Initial load
  Form->>Token: Read selected token
  Form->>Form: Initialize tokenRef (first load)
  Form->>Price: Read mark/limit price
  Form->>Form: Compute referencePrice, totals, sliderConfig

  Note over User,Form: Token switch
  User->>Form: Change token
  Form->>Form: Set switching=true (guard updates)
  Form->>Token: Update selected token
  Token-->>Form: Sync completes
  Form->>Price: Fetch new price
  Form->>Form: Update referencePrice, derived values
  Form->>Form: Set switching=false
Loading
sequenceDiagram
  autonumber
  actor User
  participant UI as Slider/Inputs
  participant Form as PerpTradingForm

  Note over User,UI: Adjust amount via slider
  User->>UI: Drag size slider
  UI->>Form: handleSizeSliderChange(value)
  Form->>Form: Clamp by sliderStep & decimals, update size
  Form->>Form: Recompute totalValue, marginRequired, sliderConfig
  Form-->>UI: Update slider controlledValue and displayed amounts
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes Check ⚠️ Warning The pull request adds multiple features beyond the slider, including reference price logic, margin calculations, and token switch effects, which are not specified in the linked issue OK-43698. Consider splitting the price handling and related enhancements into a separate pull request or link additional issues to cover these changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title highlights the new slider for size adjustment and improved price handling in PerpTradingForm, matching the main changes in this pull request.
Linked Issues Check ✅ Passed The changes fully implement the requested Perp amount input slider by adding the Slider component, configuring its behavior and constraints, and integrating it into both mobile and desktop views as specified in issue OK-43698.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch OK-43698

Comment @coderabbitai help to get the list of available commands and usage tips.

@revan-zhang
Copy link
Contributor

revan-zhang commented Sep 26, 2025

🎉 Snyk checks have passed. No issues have been found so far.

security/snyk check is complete. No issues have been found. (View Details)

license/snyk check is complete. No issues have been found. (View Details)

limichange
limichange previously approved these changes Sep 26, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (3)

85-117: Simplify token-switch effect; remove redundant state

The three‑step/ref bookkeeping is more complex than needed. You can key off the token identity and update price once markPx is ready, without tokenSwitchingRef or the “synced” check.

Suggested simplification within this effect:

-useEffect(() => {
-  const prevToken = prevTokenRef.current;
-  const hasTokenChanged =
-    currentTokenName && prevToken && prevToken !== currentTokenName;
-  const isDataSynced = prevToken === currentTokenName;
-  const shouldUpdatePrice =
-    tokenSwitchingRef.current === currentTokenName &&
-    formData.type === 'limit' &&
-    currentTokenName &&
-    tokenInfo?.markPx &&
-    isDataSynced;
-  if (hasTokenChanged) {
-    tokenSwitchingRef.current = currentTokenName;
-    prevTokenRef.current = currentTokenName;
-    return;
-  }
-  if (shouldUpdatePrice && tokenInfo.markPx) {
-    updateForm({ price: formatPriceToSignificantDigits(tokenInfo.markPx) });
-    tokenSwitchingRef.current = false;
-  }
-  if (!prevToken && currentTokenName) {
-    prevTokenRef.current = currentTokenName;
-  }
-}, [currentTokenName, tokenInfo?.markPx, formData.type, updateForm]);
+useEffect(() => {
+  if (formData.type !== 'limit') return;
+  const tokenKey = currentTokenName || '';
+  if (!tokenKey || !tokenInfo?.markPx) return;
+  if (prevTokenRef.current !== tokenKey) {
+    prevTokenRef.current = tokenKey;
+    updateForm({ price: formatPriceToSignificantDigits(tokenInfo.markPx) });
+  }
+}, [currentTokenName, tokenInfo?.markPx, formData.type, updateForm]);

Optional: remove tokenSwitchingRef entirely since it becomes unused.


367-382: Unify TP/SL price formatting with desktop

Mobile passes referencePrice.toFixed() (implicit precision). Desktop passes a pre‑formatted string. Use the same referencePriceString to avoid mismatched precision.

Apply:

-            <TpslInput
-              price={referencePrice.toFixed()}
+            <TpslInput
+              price={referencePriceString}
               side={formData.side}
               szDecimals={tokenInfo?.szDecimals ?? 2}
               leverage={leverage}

420-428: Use NumberSizeableText for currency formatting (mobile)

Align with desktop and other rows; avoid manual “$” + toFixed.

Apply:

-            <SizableText fontSize={10}>
-              ${marginRequired.toFixed(2)}
-            </SizableText>
+            <NumberSizeableText
+              fontSize={10}
+              formatter="value"
+              formatterOptions={{ currency: '$' }}
+            >
+              {marginRequired.toNumber()}
+            </NumberSizeableText>
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 41ecb2d and 73ecc77.

📒 Files selected for processing (1)
  • packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (11 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Socket Security: Pull Request Alerts
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (9)
packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (9)

11-11: LGTM: Slider import

Good addition.


232-236: LGTM: Step resolution

Reasonable cap on precision and numerically stable step.


237-248: LGTM: Slider change handler

Properly floors to szDecimals and guards invalid input.


338-348: LGTM: Mobile slider wiring

Config, step and disabled conditions look correct (after clamping fix above).


513-514: Decimals for PriceInput may be pxDecimals, not szDecimals

Flagging here too for visibility; see earlier comment on lines 122‑136.


524-535: LGTM: Desktop slider wiring

Matches mobile; will be correct after clamping fix.


556-567: LGTM: Desktop TP/SL uses pre‑formatted price

Good to reuse the formatted reference string.


122-136: No pxDecimals field found; szDecimals is correct


310-329: Verify PriceInput disabled parsing and decimal prop

  • Disabled inputs still render any string; confirm the market-price label won’t trigger validation or onChange
  • Component only accepts szDecimals; ensure you’re passing price decimals (pxDecimals) instead of size decimals (szDecimals)

# Conflicts:
#	packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx
@originalix
Copy link
Collaborator Author

@coderabbitai resolve

@originalix originalix enabled auto-merge (squash) September 27, 2025 14:25
Copy link
Contributor

coderabbitai bot commented Sep 27, 2025

✅ Actions performed

Comments resolved.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (1)

423-423: Use referencePriceString; avoid BigNumber.toFixed() default.

toFixed() defaults can produce overly long strings. Use the already formatted string.

-              price={referencePrice.toFixed()}
+              price={referencePriceString}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: ASSERTIVE

Plan: Pro

Cache: Disabled due to data retention organization setting

Knowledge base: Disabled due to data retention organization setting

Disabled knowledge base sources:

  • Jira integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 73ecc77 and e451a3e.

📒 Files selected for processing (1)
  • packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: unittest (20.x)
  • GitHub Check: lint (20.x)
🔇 Additional comments (7)
packages/kit/src/views/Perp/components/TradingPanel/panels/PerpTradingForm.tsx (7)

148-164: Reference price derivation looks good.


269-273: Step calculation looks solid.

Clamped decimals and a positive step. Good.


102-140: Token switch effect: verify no stale price on fast switches.

You set prevTokenRef immediately, so isDataSynced is effectively always true on the next run. Please sanity-check rapid symbol switches in limit mode to ensure we never momentarily set a stale price from the previous token.


252-259: Clamp slider value to [0, maxSize].

Negative sizes can slip through and break the Slider. Clamp both ends.

     return {
       price: effectivePrice,
       leverage: safeLeverage,
       maxSize,
       currentValue: currentValueNum,
-      controlledValue: maxSize > 0 ? Math.min(currentValueNum, maxSize) : 0,
+      controlledValue:
+        maxSize > 0 ? Math.max(0, Math.min(currentValueNum, maxSize)) : 0,
       isValid: !!effectivePrice && effectivePrice.gt(0) && maxSize > 0,
     };

171-179: Stop pre-formatting “Available”; return numeric only.

Drop the fixed 2 decimals. Let UI format it consistently.

-  const { availableToTradeDisplay, availableToTradeValue } = useMemo(() => {
+  const { availableToTradeValue } = useMemo(() => {
     const _availableToTrade = activeAssetData?.availableToTrade || [0, 0];
     const value = _availableToTrade[formData.side === 'long' ? 0 : 1] || 0;
     const valueBN = new BigNumber(value);
     return {
-      availableToTradeDisplay: valueBN.toFixed(2, BigNumber.ROUND_DOWN),
       availableToTradeValue: valueBN.toNumber(),
     };
   }, [formData.side, activeAssetData?.availableToTrade]);

326-327: Use NumberSizeableText for “Available” (mobile).

Avoid pre-formatted strings; format at render.

-            <SizableText size="$bodySmMedium" color="$text">
-              ${availableToTradeDisplay}
-            </SizableText>
+            <NumberSizeableText
+              size="$bodySmMedium"
+              color="$text"
+              formatter="value"
+              formatterOptions={{ currency: '$' }}
+            >
+              {availableToTradeValue}
+            </NumberSizeableText>

517-518: Use NumberSizeableText for “Available” (desktop).

Match mobile and keep formatting consistent.

-              <SizableText size="$bodySmMedium" color="$text">
-                ${availableToTradeDisplay}
-              </SizableText>
+              <NumberSizeableText
+                size="$bodySmMedium"
+                color="$text"
+                formatter="value"
+                formatterOptions={{ currency: '$' }}
+              >
+                {availableToTradeValue}
+              </NumberSizeableText>

@limichange limichange self-requested a review September 28, 2025 01:55
@originalix originalix merged commit 2d2a150 into x Sep 28, 2025
11 checks passed
@originalix originalix deleted the OK-43698 branch September 28, 2025 02:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants