-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathusePerpsOrderForm.ts
More file actions
374 lines (335 loc) · 13.1 KB
/
usePerpsOrderForm.ts
File metadata and controls
374 lines (335 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import DevLogger from '../../../../core/SDKConnect/utils/DevLogger';
import {
TRADING_DEFAULTS,
OrderType,
getMaxAllowedAmount,
selectTradeConfiguration,
selectPendingTradeConfiguration,
type OrderFormState,
} from '@metamask/perps-controller';
import {
usePerpsLiveAccount,
usePerpsLivePositions,
usePerpsLivePrices,
} from './stream';
import { usePerpsMarketData } from './usePerpsMarketData';
import { usePerpsNetwork } from './usePerpsNetwork';
import { usePerpsSelector } from './usePerpsSelector';
interface UsePerpsOrderFormParams {
initialAsset?: string;
initialDirection?: 'long' | 'short';
initialAmount?: string;
initialLeverage?: number;
initialType?: OrderType;
/** When paying with a custom token, the selected token amount in USD; used to cap maxPossibleAmount and handlers */
effectiveAvailableBalance?: number;
}
export interface UsePerpsOrderFormReturn {
orderForm: OrderFormState;
updateOrderForm: (updates: Partial<OrderFormState>) => void;
setAmount: (amount: string) => void;
setLeverage: (leverage: number) => void;
setDirection: (direction: 'long' | 'short') => void;
setAsset: (asset: string) => void;
setTakeProfitPrice: (price?: string) => void;
setStopLossPrice: (price?: string) => void;
setLimitPrice: (price?: string) => void;
setOrderType: (type: OrderType) => void;
handlePercentageAmount: (percentage: number) => void;
handleMaxAmount: () => void;
handleMinAmount: () => void;
maxPossibleAmount: number;
/** Balance to use for validation and UI (Perps balance or selected token amount in USD when paying with custom token) */
balanceForValidation: number;
}
/**
* Hook to manage the perpetual order form state and calculations
* This hook is protocol-agnostic and handles form state management
*/
export function usePerpsOrderForm(
params: UsePerpsOrderFormParams = {},
): UsePerpsOrderFormReturn {
const {
initialAsset = 'BTC',
initialDirection = 'long',
initialAmount,
initialLeverage,
initialType = 'market',
effectiveAvailableBalance: effectiveAvailableBalanceParam,
} = params;
const currentNetwork = usePerpsNetwork();
const { account } = usePerpsLiveAccount();
const { positions } = usePerpsLivePositions();
const prices = usePerpsLivePrices({
symbols: [initialAsset],
throttleMs: 1000,
});
const currentPrice = prices[initialAsset];
const { marketData } = usePerpsMarketData(initialAsset);
// Get existing position leverage for this asset (protocol constraint)
// Positions load asynchronously via WebSocket, so this may be undefined initially
const existingPositionLeverage = useMemo(
() => positions.find((p) => p.symbol === initialAsset)?.leverage?.value,
[positions, initialAsset],
);
// Get saved trade configuration for this asset (user preference for new positions)
const savedConfig = usePerpsSelector((state) =>
selectTradeConfiguration(state, initialAsset),
);
// Get pending trade configuration for this asset (temporary, expires after 5 minutes)
const pendingConfig = usePerpsSelector((state) =>
selectPendingTradeConfiguration(state, initialAsset),
);
const availableBalance = Number.parseFloat(
effectiveAvailableBalanceParam != null
? effectiveAvailableBalanceParam.toString()
: (account?.availableToTradeBalance?.toString() ??
account?.availableBalance?.toString() ??
'0'),
);
// When paying with a custom token, use selected token amount in USD (including 0); otherwise use Perps balance
const balanceForMax = effectiveAvailableBalanceParam ?? availableBalance;
// Determine default amount based on network
const defaultAmount =
currentNetwork === 'mainnet'
? TRADING_DEFAULTS.amount.mainnet
: TRADING_DEFAULTS.amount.testnet;
// Priority for leverage: navigation param > existing position leverage > pending config > saved config > default (3x)
const defaultLeverage =
initialLeverage ||
existingPositionLeverage ||
pendingConfig?.leverage ||
savedConfig?.leverage ||
TRADING_DEFAULTS.leverage;
// Priority for amount: navigation param > pending config > calculated default
// Use memoized calculation for initial amount to ensure it updates when dependencies change
const initialAmountValue = useMemo(() => {
// If we have a pending config with amount, use it (unless overridden by navigation param)
if (initialAmount) {
return initialAmount;
}
if (pendingConfig?.amount) {
return pendingConfig.amount;
}
// Don't calculate if price is not available yet to avoid temporary 0 values
if (!currentPrice?.price) {
return defaultAmount.toString();
}
const tempMaxAmount = getMaxAllowedAmount({
availableBalance: balanceForMax,
assetPrice: Number.parseFloat(currentPrice.price),
assetSzDecimals: marketData?.szDecimals ?? 6,
leverage: defaultLeverage, // Use default leverage for initial calculation
});
// Return the target amount directly (USD as source of truth, no optimization)
// Use conservative default ($10) unless explicitly provided via navigation param
const targetAmount =
tempMaxAmount < defaultAmount
? tempMaxAmount.toString()
: defaultAmount.toString();
return targetAmount;
}, [
initialAmount,
pendingConfig?.amount,
balanceForMax,
defaultAmount,
currentPrice?.price,
marketData?.szDecimals,
defaultLeverage,
]);
// Priority for order type: pending config > navigation param > default (market)
const defaultOrderType = pendingConfig?.orderType || initialType || 'market';
// Calculate initial balance percentage
const initialMarginRequired =
Number.parseFloat(initialAmountValue) / defaultLeverage;
const initialBalancePercent =
availableBalance > 0
? Math.min((initialMarginRequired / availableBalance) * 100, 100)
: TRADING_DEFAULTS.marginPercent;
// Initialize form state with pending config if available
const [orderForm, setOrderForm] = useState<OrderFormState>({
asset: initialAsset,
direction: initialDirection,
amount: initialAmountValue, // Will be updated by useEffect when initialAmountValue is calculated
leverage: defaultLeverage,
balancePercent: Math.round(initialBalancePercent * 100) / 100,
takeProfitPrice: pendingConfig?.takeProfitPrice,
stopLossPrice: pendingConfig?.stopLossPrice,
limitPrice: pendingConfig?.limitPrice,
type: defaultOrderType,
});
// Calculate the maximum possible amount; when paying with custom token, capped by selected token amount in USD
const maxPossibleAmount = useMemo(
() =>
getMaxAllowedAmount({
availableBalance: balanceForMax,
assetPrice: Number.parseFloat(currentPrice?.price) || 0,
assetSzDecimals: marketData?.szDecimals ?? 6,
leverage: orderForm.leverage, // Use current leverage instead of default
}),
[
balanceForMax,
currentPrice?.price,
marketData?.szDecimals,
orderForm.leverage, // Include current leverage in dependencies
],
);
// Update amount only once when the hook first calculates the initial value
// We use a ref to track if we've already set the initial amount to avoid overwriting user input
const hasSetInitialAmount = useRef(false);
useEffect(() => {
if (!hasSetInitialAmount.current && initialAmountValue !== '0') {
setOrderForm((prev) => ({ ...prev, amount: initialAmountValue }));
hasSetInitialAmount.current = true;
}
}, [initialAmountValue]);
useEffect(() => {
if (!pendingConfig) return;
setOrderForm((prev) => ({
...prev,
...(pendingConfig.amount && { amount: pendingConfig.amount }),
...(pendingConfig.leverage && { leverage: pendingConfig.leverage }),
...(pendingConfig.takeProfitPrice !== undefined && {
takeProfitPrice: pendingConfig.takeProfitPrice,
}),
...(pendingConfig.stopLossPrice !== undefined && {
stopLossPrice: pendingConfig.stopLossPrice,
}),
...(pendingConfig.limitPrice !== undefined && {
limitPrice: pendingConfig.limitPrice,
}),
...(pendingConfig.orderType && { type: pendingConfig.orderType }),
}));
// We don't need to depend on pendingConfig because we only want to restore it once when the component mounts
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Sync leverage from existing position when it loads asynchronously
// This handles the case where positions haven't loaded yet when form initializes
const hasSyncedLeverage = useRef(false);
useEffect(() => {
// Only update if:
// 1. Haven't synced yet (avoid fighting with user input)
// 2. No explicit initialLeverage was provided (respect navigation params)
// 3. existingPositionLeverage loaded (was undefined, now has value)
// 4. Current leverage would cause protocol violation (< existing)
if (
!hasSyncedLeverage.current &&
!initialLeverage &&
existingPositionLeverage &&
orderForm.leverage < existingPositionLeverage
) {
setOrderForm((prev) => ({ ...prev, leverage: existingPositionLeverage }));
hasSyncedLeverage.current = true;
}
}, [existingPositionLeverage, initialLeverage, orderForm.leverage]);
// When user changes payment token (or effective balance drops), reset amount to MAX if current amount exceeds new max
useEffect(() => {
const currentAmount = Number.parseFloat(orderForm.amount);
if (
currentAmount === 0 ||
maxPossibleAmount === 0 ||
currentAmount < maxPossibleAmount
)
return;
const newValue = String(Math.floor(maxPossibleAmount));
setOrderForm((prev) => ({
...prev,
amount: newValue,
}));
}, [balanceForMax, maxPossibleAmount, orderForm.amount]);
// Update entire form
const updateOrderForm = (updates: Partial<OrderFormState>) => {
setOrderForm((prev) => ({ ...prev, ...updates }));
};
// Individual setters for common operations
const setAmount = (amount: string) => {
setOrderForm((prev) => ({ ...prev, amount: amount || '0' }));
};
const setLeverage = (leverage: number) => {
setOrderForm((prev) => ({ ...prev, leverage }));
};
const setDirection = (direction: 'long' | 'short') => {
setOrderForm((prev) => ({ ...prev, direction }));
};
const setAsset = (asset: string) => {
setOrderForm((prev) => ({ ...prev, asset }));
};
const setTakeProfitPrice = (price?: string) => {
// Convert empty string to undefined for proper clearing
const cleanedPrice = price === '' || price === null ? undefined : price;
setOrderForm((prev) => ({ ...prev, takeProfitPrice: cleanedPrice }));
};
const setStopLossPrice = (price?: string) => {
// Convert empty string to undefined for proper clearing
const cleanedPrice = price === '' || price === null ? undefined : price;
setOrderForm((prev) => {
const newState = { ...prev, stopLossPrice: cleanedPrice };
DevLogger.log('[Order Debug] setStopLossPrice state update:', {
previousStopLoss: prev.stopLossPrice,
newStopLoss: newState.stopLossPrice,
actualNewValue: cleanedPrice,
wasCleared: cleanedPrice === undefined,
});
return newState;
});
};
const setLimitPrice = (price?: string) => {
setOrderForm((prev) => {
const newState = { ...prev, limitPrice: price };
return newState;
});
};
const setOrderType = (type: OrderType) => {
setOrderForm((prev) => ({ ...prev, type }));
};
// Handle percentage-based amount selection (respects custom token amount when set).
// Clamp to maxPossibleAmount so near-100% values never exceed the buffered max.
const handlePercentageAmount = useCallback(
(percentage: number) => {
if (balanceForMax === 0) return;
const raw = balanceForMax * orderForm.leverage * percentage;
const clamped = Math.min(raw, maxPossibleAmount);
const newAmount = Math.floor(clamped).toString();
setOrderForm((prev) => ({ ...prev, amount: newAmount }));
},
[balanceForMax, orderForm.leverage, maxPossibleAmount],
);
// Handle max amount selection (respects custom token amount when set).
// Uses maxPossibleAmount (includes margin buffer) to avoid "Insufficient margin" rejections.
const handleMaxAmount = useCallback(() => {
if (balanceForMax === 0) return;
setOrderForm((prev) => ({
...prev,
amount: Math.floor(maxPossibleAmount).toString(),
}));
}, [balanceForMax, maxPossibleAmount]);
// Handle min amount selection
const handleMinAmount = useCallback(() => {
const minAmount =
currentNetwork === 'mainnet'
? TRADING_DEFAULTS.amount.mainnet
: TRADING_DEFAULTS.amount.testnet;
setOrderForm((prev) => ({
...prev,
amount: minAmount.toString(),
}));
}, [currentNetwork]);
return {
orderForm,
updateOrderForm,
setAmount,
setLeverage,
setDirection,
setAsset,
setTakeProfitPrice,
setStopLossPrice,
setLimitPrice,
setOrderType,
handlePercentageAmount,
handleMaxAmount,
handleMinAmount,
maxPossibleAmount,
balanceForValidation: balanceForMax,
};
}