'use client' import { useState, useEffect, useCallback } from 'react' import { useLocale } from 'next-intl' import { useAccount, useConnect, useSignMessage } from 'wagmi' import { getUserPublic, getUser, setUserSettings, setHlApiKey, setManualWindow, subscribe, type UserSettings, } from '@/lib/api' import { useDashboardStore } from '@/store/dashboard' import { signRequest, getOrCreateViewEnvelope, getCachedViewEnvelope, } from '@/lib/signedRequest' import { walletErrorLabel } from '@/lib/walletError' import { confirmSign } from '@/components/wallet/SignConfirmSheet' // Defaults shown to a brand-new, un-configured wallet. take_profit_pct, // stop_loss_pct and daily_budget_usd are all REQUIRED before the bot will // trade — we still initialise them so the inputs have sensible placeholders. const DEFAULT_SETTINGS: UserSettings = { leverage: 3, position_size_usd: 20, take_profit_pct: 2, stop_loss_pct: 1.5, min_confidence: 70, daily_budget_usd: 15, sys2_leverage: 2, sys2_mode: 'standard', active_from: null, active_until: null, } // ── datetime-local helpers (browser local tz ↔ ISO UTC) ────────────────────── function isoToLocalInput(iso: string | null): string { if (!iso) return '' const d = new Date(iso) if (isNaN(d.getTime())) return '' const pad = (n: number) => String(n).padStart(2, '0') return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}` } function localInputToIso(v: string): string | null { if (!v) return null const d = new Date(v) // interpreted as local time if (isNaN(d.getTime())) return null return d.toISOString() } // ─── Bot config panel ───────────────────────────────────────────────────────── export default function BotConfigPanel() { 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 { connect, connectors } = useConnect() const { signMessageAsync } = useSignMessage() const { isSubscribed, hlApiKeySet, hlApiKeyMasked, botReadiness, setSubscribed, setBotReadiness, setHlApiKeySet, } = useDashboardStore() const [settings, setSettings] = useState(DEFAULT_SETTINGS) // Tracks whether the SERVER already has values for these required fields. const [tpConfigured, setTpConfigured] = useState(false) const [slConfigured, setSlConfigured] = useState(false) const [budgetConfigured, setBudgetConfigured] = useState(false) const [useSchedule, setUseSchedule] = useState(false) const [fromLocal, setFromLocal] = useState('') const [untilLocal, setUntilLocal] = useState('') const [dirty, setDirty] = useState(false) const [saveState, setSaveState] = useState<'idle'|'signing'|'saving'|'ok'|'err'>('idle') const [saveErr, setSaveErr] = useState('') // HL key state const [apiKey, setApiKey] = useState('') const [keyState, setKeyState] = useState<'idle'|'signing'|'saving'|'ok'|'err'>('idle') const [keyErr, setKeyErr] = useState('') // Subscribe state. `subPaperChoice` is the user's selection on the // pre-subscribe form ("paper" or "live"); written to Subscription.paper_mode // when the signed subscribe goes through. const [subState, setSubState] = useState<'idle'|'signing'|'saving'|'err'>('idle') const [subErr, setSubErr] = useState('') const [subPaperChoice, setSubPaperChoice] = useState<'paper' | 'live'>('paper') // Manual window (convex-strategy "enable for N hours" override). // null = no override active; ISO string = bot armed until that UTC time. const [manualUntil, setManualUntil] = useState(null) const [mwState, setMwState] = useState<'idle'|'signing'|'saving'|'err'>('idle') const [mwErr, setMwErr] = useState('') const [mwTick, setMwTick] = useState(0) // forces countdown re-render // Mounted flag: avoid SSR/CSR mismatch since wagmi state differs between the two. const [mounted, setMounted] = useState(false) useEffect(() => { setMounted(true) }, []) // Settings-load state. We do NOT auto-pop MetaMask — only fetch with a // cached signature; otherwise wait for the user to click "Load settings". const [loadState, setLoadState] = useState<'idle'|'loading'|'loaded'|'err'>('idle') const [loadErr, setLoadErr] = useState('') // Apply a fetched user payload into local form state. function applyUserPayload(u: { active: boolean hl_api_key_set: boolean hl_api_key_masked: string | null settings: UserSettings manual_window_until?: string | null }) { setSubscribed(u.active) setHlApiKeySet(u.hl_api_key_set, u.hl_api_key_masked ?? undefined) setManualUntil(u.manual_window_until ?? null) if (u.settings) { const s = u.settings setTpConfigured(s.take_profit_pct != null) setSlConfigured(s.stop_loss_pct != null) setBudgetConfigured(s.daily_budget_usd != null) setBotReadiness(u.hl_api_key_set ? 'saved' : 'unknown') setSettings({ ...s, take_profit_pct: s.take_profit_pct ?? 2, stop_loss_pct: s.stop_loss_pct ?? 1.5, daily_budget_usd: s.daily_budget_usd ?? 15, }) const hasSched = s.active_from != null && s.active_until != null setUseSchedule(hasSched) setFromLocal(isoToLocalInput(s.active_from)) setUntilLocal(isoToLocalInput(s.active_until)) } } // On connect: fetch public state only (no signature). If a fresh view // envelope is already cached in sessionStorage, silently hydrate full data. useEffect(() => { if (!mounted || !isConnected || !address) return let cancelled = false ;(async () => { const pub = await getUserPublic(address.toLowerCase()).catch(() => null) if (!pub || cancelled) return setSubscribed(pub.active) setHlApiKeySet(pub.hl_api_key_set) setBotReadiness(pub.hl_api_key_set ? 'saved' : 'unknown') if (!pub.active) return const cached = getCachedViewEnvelope('view_user', address) if (!cached) return const u = await getUser(address, cached).catch(() => null) if (!u || cancelled) return applyUserPayload(u) setLoadState('loaded') })() return () => { cancelled = true } }, [address, isConnected, mounted]) // eslint-disable-line react-hooks/exhaustive-deps async function handleLoadSettings() { if (!address) return setLoadErr(''); setLoadState('loading') try { const ok = await confirmSign({ label: isZh ? '查看账户设置' : 'View account settings', description: isZh ? '读取你在 Trump Alpha 的订阅状态、风控参数和 API Key 状态。签名仅用于身份验证,不做任何链上操作。' : 'Read your Trump Alpha subscription state, risk settings, and API key status. The signature is only for identity verification. No on-chain action is performed.', }) if (!ok) { setLoadState('idle'); return } const env = await getOrCreateViewEnvelope({ action: 'view_user', wallet: address, signMessageAsync }) const u = await getUser(address, env) applyUserPayload(u) setLoadState('loaded') } catch (e: unknown) { setLoadErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 120)) setLoadState('err') } } async function refreshUserState(wallet: string) { const pub = await getUserPublic(wallet.toLowerCase()) setSubscribed(pub.active) setHlApiKeySet(pub.hl_api_key_set) setBotReadiness(pub.hl_api_key_set ? 'saved' : 'unknown') return pub } function updateSettings(patch: Partial) { setSettings(s => ({ ...s, ...patch })) setDirty(true) } async function handleSubscribe() { if (!address) return const paperMode = subPaperChoice === 'paper' const ok = await confirmSign({ label: paperMode ? (isZh ? '订阅 Trump Alpha(模拟模式)' : 'Subscribe to Trump Alpha (paper mode)') : (isZh ? '订阅 Trump Alpha(真实资金)' : 'Subscribe to Trump Alpha (live capital)'), description: paperMode ? (isZh ? '注册为 Paper 模式订阅者。机器人开仓不涉及真实资金,仅供测试。' : 'Register as a paper-mode subscriber. Trades are simulated and do not touch real funds.') : (isZh ? '注册为正式订阅者。完成后需配置 Hyperliquid API Key 才能实际开仓。' : 'Register as a live subscriber. You still need to configure a Hyperliquid API key before any real trade can open.'), danger: !paperMode, }) if (!ok) return setSubErr(''); setSubState('signing') try { const signedBody = paperMode ? { paper_mode: true } : null const env = await signRequest({ action: 'subscribe', wallet: address, body: signedBody, signMessageAsync }) setSubState('saving') await subscribe(env, { paper_mode: paperMode }) setSubscribed(true) void refreshUserState(address) setSubState('idle') setTpConfigured(false) setSlConfigured(false) setBudgetConfigured(false) setLoadState('loaded') } catch (e: unknown) { setSubErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 100)) setSubState('err') } } async function handleSaveSettings() { if (!address) return const ok = await confirmSign({ label: isZh ? '保存交易风控参数' : 'Save trading risk settings', description: isZh ? '保存杠杆、仓位大小、止盈止损比例和每日预算设置。签名后立即生效。' : 'Save leverage, position size, take-profit, stop-loss, and daily budget settings. Changes apply immediately after signing.', }) if (!ok) return setSaveErr(''); setSaveState('signing') try { let schedFrom: string | null = null let schedUntil: string | null = null if (useSchedule) { schedFrom = localInputToIso(fromLocal) schedUntil = localInputToIso(untilLocal) if (!schedFrom || !schedUntil) { setSaveErr(isZh ? '请选择开始和结束时间' : 'Pick both a start and end time'); setSaveState('err'); return } if (new Date(schedUntil).getTime() <= new Date(schedFrom).getTime()) { setSaveErr(isZh ? '结束时间必须晚于开始时间' : 'End must be after start'); setSaveState('err'); return } } const tp = settings.take_profit_pct, sl = settings.stop_loss_pct, bd = settings.daily_budget_usd if (tp == null || tp < 0.1 || tp > 50) { setSaveErr(isZh ? '止盈必须在 0.1% 到 50% 之间' : 'Take profit must be 0.1 – 50%'); setSaveState('err'); return } if (sl == null || sl < 0.1 || sl > 50) { setSaveErr(isZh ? '止损必须在 0.1% 到 50% 之间' : 'Stop loss must be 0.1 – 50%'); setSaveState('err'); return } if (bd == null || bd <= 0 || bd > 100000){ setSaveErr(isZh ? '每日预算必须大于 0 美元' : 'Daily budget must be > $0'); setSaveState('err'); return } const payload: UserSettings = { ...settings, take_profit_pct: tp, stop_loss_pct: sl, daily_budget_usd: bd, active_from: schedFrom, active_until: schedUntil, } const env = await signRequest({ action: 'set_settings', wallet: address, body: payload, signMessageAsync }) setSaveState('saving') await setUserSettings(env, payload) setSettings(payload) setTpConfigured(true); setSlConfigured(true); setBudgetConfigured(true) setBotReadiness('saved') setDirty(false) setSaveState('ok') setTimeout(() => setSaveState('idle'), 2000) } catch (e: unknown) { setSaveErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 100)) setSaveState('err') } } async function handleSaveKey() { if (!address || !apiKey.trim()) return const trimmed = apiKey.trim() if (!trimmed.startsWith('0x') || trimmed.length !== 66) { setKeyErr(isZh ? '必须是 0x 开头加 64 位十六进制字符' : 'Must be 0x + 64 hex chars'); setKeyState('err'); return } const ok = await confirmSign({ label: isZh ? '绑定 Hyperliquid API Key' : 'Link Hyperliquid API key', description: isZh ? 'API Key 将加密存储在服务端,用于机器人在 Hyperliquid 上代替你下单。签名用于验证是你本人操作。' : 'The API key is stored encrypted on the server and used by the bot to place trades on Hyperliquid for you. The signature confirms this action came from you.', danger: true, }) if (!ok) return setKeyErr(''); setKeyState('signing') try { const env = await signRequest({ action: 'set_hl_api_key', wallet: address, body: { api_key: trimmed }, signMessageAsync }) setKeyState('saving') const res = await setHlApiKey(env, trimmed) setHlApiKeySet(true, res.masked_key) setBotReadiness('saved') void refreshUserState(address) setApiKey('') setKeyState('ok') } catch (e: unknown) { setKeyErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 100)) setKeyState('err') } } const handleConnectWallet = useCallback(() => { const connector = connectors[0] if (connector) connect({ connector }) }, [connect, connectors]) // ── Manual-window: arm for N hours, or clear (hours = 0) ────────────────── async function handleManualWindow(hours: number) { if (!address) return setMwErr(''); setMwState('signing') try { const env = await signRequest({ action: 'set_manual_window', wallet: address, body: { hours }, signMessageAsync, }) setMwState('saving') const r = await setManualWindow(env, hours) setManualUntil(r.manual_window_until) setMwState('idle') } catch (e: unknown) { setMwErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 100)) setMwState('err') } } // Countdown re-render every 15s while a manual window is armed. useEffect(() => { if (!manualUntil) return const id = setInterval(() => setMwTick(t => t + 1), 15000) return () => clearInterval(id) }, [manualUntil]) if (!mounted || !isConnected) { return (

{isZh ? '连接钱包后即可配置机器人并查看你的交易。' : 'Connect your wallet to configure the bot and view your trades.'}

) } // ── small local helpers ─────────────────────────────────────────────────── const Switch = ({ on, onChange, tone = 'amber' }: { on: boolean; onChange: (v: boolean) => void; tone?: 'amber' | 'up' | 'down' }) => ( ) const saveBtnLabel = saveState === 'signing' ? (isZh ? '钱包签名中…' : 'Sign in wallet…') : saveState === 'saving' ? (isZh ? '保存中…' : 'Saving…') : saveState === 'ok' ? (isZh ? '✓ 已保存' : '✓ Saved') : (isZh ? '保存更改' : 'Save changes') const keyHint = hlApiKeySet && !apiKey ? (isZh ? '已保存在你的机器人配置里。如果你在 Hyperliquid 轮换了 API 钱包,重新交易前请先在这里更新。' : 'Saved in your bot profile. If you rotate the API wallet in Hyperliquid, update it here before trading again.') : (isZh ? '请使用 app.hyperliquid.xyz/API 生成的 Hyperliquid API 钱包私钥。不要在这里粘贴 MetaMask 助记词或私钥。' : 'Use the Hyperliquid API wallet private key from app.hyperliquid.xyz/API. Never paste your MetaMask secret phrase or private key here.') const keyStatusHint = keyState === 'ok' ? (isZh ? 'API 钱包已保存。建议下一步先用极小仓位跑一次你自己的 BTC 测试,再把这套配置当成生产可用。' : 'API wallet saved. Recommended next step: keep size tiny and run your own first BTC test before treating the setup as production-ready.') : null // ── Hyperliquid key strip ───────────────────────────────────────────────── const hlKeyStrip = (
{hlApiKeySet ? '✓' : '◇'}
Hyperliquid API wallet
{!isSubscribed ? 'Subscribe first to link your HL account' : hlApiKeySet && !apiKey ? <>Linked · {hlApiKeyMasked ?? '···'} · trade-only scope : 'Paste your API wallet private key — trade-only, never withdraw'}
{isSubscribed && hlApiKeySet && !apiKey && ( )} {isSubscribed && (!hlApiKeySet || apiKey) && ( <> { setApiKey(e.target.value); if (keyState !== 'idle') setKeyState('idle') }} placeholder="0x…" style={{ width: 220, fontFamily: 'var(--mono)', fontSize: 12, padding: '8px 10px' }} /> )}
{keyHint}
{keyStatusHint && (
{keyStatusHint}
)} {keyState === 'err' && (
{keyErr}
)}
) // ── Setup readiness ─────────────────────────────────────────────────────── const missingSetup: string[] = [] if (!isSubscribed) missingSetup.push('subscribe to the bot') if (!hlApiKeySet) missingSetup.push('link a Hyperliquid API wallet') if (!tpConfigured) missingSetup.push('take-profit') if (!slConfigured) missingSetup.push('stop-loss') if (!budgetConfigured) missingSetup.push('daily budget') const botReady = missingSetup.length === 0 const setupSteps = [ { label: '1. Subscribe', done: isSubscribed }, { label: '2. Add HL API wallet', done: hlApiKeySet }, { label: '3. Save risk limits', done: tpConfigured && slConfigured && budgetConfigured }, ] const setupGuideMessage = !isSubscribed ? 'Start by subscribing with the connected wallet. That unlocks the bot profile for this address.' : botReadiness === 'ready' ? 'Your setup is verified. Before relying on automation, run one tiny BTC trade with your own wallet and Hyperliquid API wallet to confirm the live path end to end.' : !hlApiKeySet ? 'Next, paste the Hyperliquid API wallet private key you generated inside Hyperliquid. Do not paste your MetaMask private key or seed phrase here.' : 'Your exchange key is saved. Finish take-profit, stop-loss, and daily budget, then save changes. The backend still needs to verify this setup before we mark it ready.' return (
{/* ── Setup progress banner ── */}
{setupSteps.map((step) => ( {step.done ? '✓ ' : '○ '}{step.label} ))}
{setupGuideMessage}
{hlKeyStrip} {/* ── Manual window (convex-strategy override) ── */} {isSubscribed && (() => { const untilMs = manualUntil ? new Date(manualUntil).getTime() : 0 // Touch the tick counter so countdown re-renders even if `manualUntil` is unchanged. void mwTick const remainingMin = untilMs ? Math.max(0, Math.round((untilMs - Date.now()) / 60000)) : 0 const armed = remainingMin > 0 const remainingLabel = remainingMin >= 60 ? `${Math.floor(remainingMin / 60)}h ${remainingMin % 60}m` : `${remainingMin}m` const busy = mwState === 'signing' || mwState === 'saving' return (
{armed ? '● Manually armed' : '○ Manual window'}
{armed ? <>Bot is live for {remainingLabel} more — overrides any schedule. : 'Arm the bot for a specific window. Best for catalysts (CPI, FOMC, news drops).'}
{!armed && ( <> {[1, 4, 24].map(h => ( ))} )} {armed && ( )}
{mwState === 'err' && (
{mwErr}
)}
) })()} {/* ── Main settings card ── */}
{/* Header bar */}
Trading bot
Executes on Hyperliquid when a Trump post clears your filters.
{dirty && isSubscribed && ● Unsaved} {saveState === 'err' && {saveErr}} {!isSubscribed ? ( // Subscribe button moved into the body to live alongside the // paper-vs-live choice. Header keeps only status chips. ○ Not subscribed ) : ( <> {botReady ? '● Bot ready' : '● Bot paused'} )}
{/* Setup-incomplete warning */} {isSubscribed && loadState === 'loaded' && !botReady && (
Setup incomplete — the bot will not open any trades.
Finish configuring: {missingSetup.join(' · ')}. Fill every required field below and save. The bot stays paused until every box is ticked.
)} {/* Setup-complete banner */} {isSubscribed && loadState === 'loaded' && botReady && (
Setup complete on this page.
Wallet subscription, API wallet storage, and risk fields are all saved. Before you rely on automation, use your own account to run one tiny BTC test and confirm the live trade path behaves the way you expect.
)} {/* Body */} {!isSubscribed ? (
Subscribe to activate automated trading. The bot signs positions on Hyperliquid using an API wallet scoped to trade-only — it can never withdraw. You pick the size, leverage, risk limits, and signal threshold below.
{/* ── Paper-vs-Live choice (P0.2) ──────────────────────────── New users land on PAPER by default. Forces a conscious opt-in to live trading rather than auto-routing real money. */}
{([ { key: 'paper', title: '📝 Start in paper mode', tag: 'Recommended', body: 'Trades are simulated end-to-end. No funds at risk, no HL key needed. Promote to live anytime.', }, { key: 'live', title: '💰 Start live', tag: 'Real money', body: 'Bot trades real positions on Hyperliquid. Requires an HL API key. Risk = your full position size.', }, ] as const).map(opt => { const active = subPaperChoice === opt.key return ( ) })}
{/* The subscribe button moves down here so paper choice is resolved before the wallet popup. */}
{subState === 'err' && {subErr}}
) : loadState !== 'loaded' ? (
Sign a one-time message with your wallet to load your bot settings and trade history. The signature is cached for 4 minutes so repeat visits won't prompt again.
{loadState === 'err' && {loadErr}}
) : (
{/* ── EXECUTION ── */}
Execution
Per-trade size Notional in USD. margin ≈ ${(settings.position_size_usd / settings.leverage).toFixed(2)} at {settings.leverage}×
$ updateSettings({ position_size_usd: Math.max(5, +e.target.value || 0) })} />
$5 – $10,000
Leverage (Trump / System 1) Event-driven scalp positions
updateSettings({ leverage: +e.target.value })} />
25×50×
{settings.leverage}×
{(() => { const aggressive = settings.sys2_mode === 'aggressive' return (
BTC strategy mode (System 2) A separately-funded sleeve. Aggressive = high leverage + earlier/heavier pyramiding + wider trailing → explosive in a clean bull, but a normal 25–35% correction will scale you out hard. Both modes stay inside the liquidation line.
{aggressive && (
⚠️ High-risk sleeve: default 8×, pyramids up to +1.5× base, gives back up to 42% off the peak. Fund this separately — expect frequent full scale-outs on corrections in exchange for explosive clean runs.
)}
) })()} {(() => { const aggressive = settings.sys2_mode === 'aggressive' const defLev = aggressive ? 8 : 2 const lev = Math.max(1, Math.min(10, settings.sys2_leverage ?? defLev)) const prot = Math.min(35, 0.85 * 100 / lev) const liq = 100 / lev const risky = lev > 2 const e1 = aggressive ? '¼' : '⅓' const e2 = aggressive ? '¼' : '⅓' return (
BTC bottom leverage (System 2) Independent of Trump. Wrong → scales OUT in 3 stages inside the liquidation line (never exchange-liquidated). Right → pyramids IN on a confirmed trend, stop floored at breakeven.
updateSettings({ sys2_leverage: +e.target.value })} />
10×
{lev}×
At {lev}× it sheds {e1} near −{(prot * 0.6).toFixed(0)}%, {' '}{e2} near −{(prot * 0.8).toFixed(0)}%, fully out by −{prot.toFixed(0)}% (exchange would liquidate ≈ −{liq.toFixed(0)}%).{' '} {risky ? (aggressive ? '🔥 Aggressive: a normal 25–35% bull correction will scale you out — you’re betting on clean explosive runs.' : '⚠️ Above 2× a normal 25–35% bull correction can scale you out before the top. To ride a super-bull, keep ≤2× — amplify via pyramiding, not leverage.') : 'Wide enough to ride normal bull corrections; amplification comes from pyramiding.'}
) })()}
Min AI confidence Skip any signal below this score (0–100)
updateSettings({ min_confidence: +e.target.value })} />
050100
{settings.min_confidence}%
{/* ── LIMITS ── */}
Limits & risk
Daily budget * Stop opening new trades once the day's total notional reaches this (UTC). Required.
$ updateSettings({ daily_budget_usd: e.target.value === '' ? null : Math.max(0, +e.target.value) })} /> /day
{!budgetConfigured && Not configured}
Take profit * Auto-close when unrealised gain hits target. Required.
updateSettings({ take_profit_pct: e.target.value === '' ? null : +e.target.value })} /> % gain
{!tpConfigured && Not configured}
Stop loss * Auto-close when drawdown hits limit. Required.
updateSettings({ stop_loss_pct: e.target.value === '' ? null : +e.target.value })} /> % loss
{!slConfigured && Not configured}
{/* ── SCHEDULE ── */}
Active schedule
Only run in a window Bot ignores signals outside this range. Shown in your browser's local time.
{ setUseSchedule(v); setDirty(true) }} /> {useSchedule && (
From { setFromLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
Until { setUntilLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
)}
{useSchedule && fromLocal && untilLocal && (() => { const fromMs = new Date(fromLocal).getTime() const untilMs = new Date(untilLocal).getTime() const nowMs = Date.now() if (isNaN(fromMs) || isNaN(untilMs) || untilMs <= fromMs) return null const inWindow = nowMs >= fromMs && nowMs < untilMs const durH = (untilMs - fromMs) / 3600000 const durLabel = durH < 1 ? `${Math.round(durH * 60)} min` : durH < 48 ? `${durH.toFixed(1)} h` : `${(durH / 24).toFixed(1)} d` return (
{inWindow ? '● In window now' : '○ Outside window'} Duration: {durLabel}
) })()}
)}
) }