banked {fmtMoney(p.realized_usd, { sign: true })} from partial close
)}
{/* Emergency close — bypasses TP/SL/schedule. Always available. */}
)
}
export default function OpenPositions() {
const locale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const { address, isConnected } = useAccount()
const { signMessageAsync } = useSignMessage()
const [mounted, setMounted] = useState(false)
const [positions, setPositions] = useState(null)
const [today, setToday] = useState(null)
const [err, setErr] = useState(null)
const [needsUnlock, setNeedsUnlock] = useState(false)
const [unlocking, setUnlocking] = useState(false)
// Close-confirmation modal state
const [closing, setClosing] = useState(null)
const [closeState, setCloseState] = useState<'idle' | 'signing' | 'closing' | 'err'>('idle')
useEffect(() => {
setMounted(true)
}, [])
const [closeErr, setCloseErr] = useState('')
const [growId, setGrowId] = useState(null)
// Separate error slot for the Grow toggle so a transient toggle failure
// doesn't squat in the panel-header `err` banner (which is otherwise
// owned by the 15s poll). Auto-clears after 4s.
const [growErr, setGrowErr] = useState('')
useEffect(() => {
if (!growErr) return
const t = setTimeout(() => setGrowErr(''), 4000)
return () => clearTimeout(t)
}, [growErr])
async function toggleGrow(p: OpenPosition) {
if (!address || growId !== null) return
const next = !p.grow_mode
setGrowId(p.trade_id)
setGrowErr('')
try {
const env = await signRequest({
action: 'set_trade_grow',
wallet: address,
body: { trade_id: p.trade_id, enabled: next },
signMessageAsync,
})
const r = await setTradeGrow(env, p.trade_id, next)
setPositions((prev) =>
(prev ?? []).map((x) => (x.trade_id === p.trade_id ? { ...x, grow_mode: r.grow_mode } : x)),
)
} catch (e) {
if (isUserRejection(e)) {
setGrowErr(isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled')
} else {
setGrowErr(
walletErrorLabel(e, isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled', 90) ||
(isZh ? 'Grow 切换失败' : 'grow toggle failed'),
)
}
} finally {
setGrowId(null)
}
}
useEffect(() => {
// B39: wipe stale data from the previous wallet immediately — don't wait
// for the async fetch to complete before the UI shows a clean slate.
setPositions(null)
setToday(null)
setNeedsUnlock(false)
setErr(null)
if (!isConnected || !address) return
let cancelled = false
// Only reuse a cached envelope here. Open positions should never trigger
// a fresh signature popup on their own while the user is browsing.
async function load() {
const env =
getCachedViewEnvelope('view_positions', address!) ??
getCachedViewEnvelope('view_user', address!)
if (!env) {
if (!cancelled) {
setNeedsUnlock(true)
setErr(null)
}
return
}
try {
const [p, t] = await Promise.all([
getOpenPositions(address!, env),
getTodayStats(address!, env),
])
if (!cancelled) {
setPositions(p.positions)
setToday(t)
setErr(null)
setNeedsUnlock(false)
}
} catch (e: unknown) {
if (!cancelled)
setErr(e instanceof Error ? e.message.slice(0, 80) : isZh ? '加载失败' : 'fetch error')
}
}
void load()
const id = setInterval(() => {
void load()
}, POLL_MS)
return () => {
cancelled = true
clearInterval(id)
}
// signMessageAsync and isZh are intentionally excluded: signMessageAsync is
// never called inside this effect (load() uses cached envelopes only), and
// isZh is a compile-time constant (always false). Including either would
// restart the 15-second poll timer on every wagmi reference change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [address, isConnected])
// In-page unlock: mint a view_user envelope (one signature) right here and
// load positions immediately — no detour to the Settings page. view_user is
// a superset accepted by /positions/open and /positions/today.
async function handleUnlock() {
if (!address || unlocking) return
setUnlocking(true)
setErr(null)
try {
const env = await getOrCreateViewEnvelope({
action: 'view_user',
wallet: address,
signMessageAsync,
})
const [p, t] = await Promise.all([
getOpenPositions(address, env),
getTodayStats(address, env),
])
setPositions(p.positions)
setToday(t)
setNeedsUnlock(false)
setErr(null)
} catch (e: unknown) {
// User-cancelled signature is benign — keep the unlock CTA visible.
if (!isUserRejection(e)) {
setErr(e instanceof Error ? e.message.slice(0, 80) : isZh ? '解锁失败' : 'unlock failed')
}
} finally {
setUnlocking(false)
}
}
// Trigger close. Two-step: opens modal, user confirms, we sign + POST.
async function confirmCloseTrade() {
if (!address || !closing) return
setCloseErr('')
setCloseState('signing')
try {
const env = await signRequest({
action: 'close_trade',
wallet: address,
body: { trade_id: closing.trade_id },
signMessageAsync,
})
setCloseState('closing')
await manualCloseTrade(env, closing.trade_id)
// Optimistically drop the row from the list; the next poll will confirm.
setPositions((prev) => (prev ?? []).filter((x) => x.trade_id !== closing.trade_id))
setClosing(null)
setCloseState('idle')
} catch (e: unknown) {
// Distinguish a user-cancelled signature (benign, close the modal) from
// a real failure (keep modal open in 'err' state so user can retry or
// read the error).
if (isUserRejection(e)) {
setClosing(null)
setCloseState('idle')
setCloseErr('')
} else {
setCloseErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 120))
setCloseState('err')
}
}
}
// Return null both before mount (SSR) and when not connected — same output,
// no hydration mismatch.
if (!mounted || !isConnected) return null
if (needsUnlock && positions === null && today === null) {
return (
Open positions
Sign in to see open positions
Sign once on this device to unlock your positions (valid for a few minutes, no
transaction, no gas).
or go to Settings →
{err &&
⚠️ {err}
}
)
}
// When the first load fails, positions and today are still null but err is set.
// Without this guard the component returns null (blank), swallowing the error.
if (positions === null && today === null) {
if (err) {
return (
{closing.is_paper
? isZh
? '这是模拟交易,平仓只做本地记录,不会动用真实资金。'
: 'Paper trade — simulated close, no real funds involved.'
: isZh
? '立即按市价在 Hyperliquid 上平仓。盈亏将立即结算,无法撤销。'
: 'Closes at market price on Hyperliquid right now. The profit or loss becomes final and cannot be undone.'}