done
This commit is contained in:
+220
-100
@@ -1,124 +1,244 @@
|
||||
'use client'
|
||||
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { useState } from 'react'
|
||||
import { useAccount } from 'wagmi'
|
||||
import { useConnectModal } from '@rainbow-me/rainbowkit'
|
||||
import { useAccount, useSignMessage } from 'wagmi'
|
||||
import type { BotPerformance } from '@/types'
|
||||
import { useDashboardStore } from '@/store/dashboard'
|
||||
import { formatPct, formatHold } from '@/lib/utils'
|
||||
import { setHlApiKey, subscribe } from '@/lib/api'
|
||||
import { signRequest } from '@/lib/signedRequest'
|
||||
|
||||
const MOCK_PERFORMANCE: BotPerformance = {
|
||||
period_days: 30,
|
||||
total_trades: 89,
|
||||
win_rate: 0.73,
|
||||
net_pnl_usd: 12840,
|
||||
avg_hold_seconds: 14 * 60,
|
||||
max_drawdown_pct: 8.2,
|
||||
// Action names must match backend/app/api/{user,subscribe}.py
|
||||
const ACTION_SET_API_KEY = 'set_hl_api_key'
|
||||
const ACTION_SUBSCRIBE = 'subscribe'
|
||||
|
||||
interface Props {
|
||||
performance?: BotPerformance | null
|
||||
}
|
||||
|
||||
interface BotPanelProps {
|
||||
performance?: BotPerformance
|
||||
type SaveState = 'idle' | 'signing' | 'saving' | 'success' | 'error'
|
||||
|
||||
function fmtHold(s: number) {
|
||||
if (s < 60) return s + 's'
|
||||
const m = Math.floor(s / 60)
|
||||
if (m < 60) return m + 'm'
|
||||
return Math.floor(m / 60) + 'h ' + (m % 60) + 'm'
|
||||
}
|
||||
|
||||
export default function BotPanel({ performance = MOCK_PERFORMANCE }: BotPanelProps) {
|
||||
const t = useTranslations('bot')
|
||||
const { isSubscribed, setSubscribed } = useDashboardStore()
|
||||
export default function BotPanel({ performance }: Props) {
|
||||
const { isSubscribed, hlApiKeySet, hlApiKeyMasked, setHlApiKeySet, setSubscribed } = useDashboardStore()
|
||||
const { address, isConnected } = useAccount()
|
||||
const { openConnectModal } = useConnectModal()
|
||||
const [apiKey, setApiKey] = useState('')
|
||||
const { signMessageAsync } = useSignMessage()
|
||||
|
||||
const stats = [
|
||||
{ label: t('winRate'), value: formatPct(performance.win_rate * 100 - 100 + performance.win_rate * 100), display: `${Math.round(performance.win_rate * 100)}%` },
|
||||
{ label: t('netPnl'), value: `+$${performance.net_pnl_usd.toLocaleString()}`, positive: true },
|
||||
{ label: t('totalTrades'), value: String(performance.total_trades) },
|
||||
{ label: t('avgHold'), value: formatHold(performance.avg_hold_seconds) },
|
||||
]
|
||||
const [apiKey, setApiKey] = useState('')
|
||||
const [saveState, setSaveState] = useState<SaveState>('idle')
|
||||
const [errorMsg, setErrorMsg] = useState('')
|
||||
const [subState, setSubState] = useState<'idle' | 'signing' | 'saving' | 'error'>('idle')
|
||||
const [subError, setSubError] = useState('')
|
||||
|
||||
async function handleSubscribe() {
|
||||
if (!address) return
|
||||
setSubError('')
|
||||
try {
|
||||
setSubState('signing')
|
||||
const env = await signRequest({
|
||||
action: ACTION_SUBSCRIBE,
|
||||
wallet: address,
|
||||
body: null,
|
||||
signMessageAsync,
|
||||
})
|
||||
setSubState('saving')
|
||||
await subscribe(env)
|
||||
setSubscribed(true)
|
||||
setSubState('idle')
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Unknown error'
|
||||
setSubError(msg.includes('User rejected') || msg.includes('denied') ? 'Signature cancelled' : msg.slice(0, 120))
|
||||
setSubState('error')
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveKey() {
|
||||
if (!address || !apiKey.trim()) return
|
||||
if (!apiKey.trim().startsWith('0x') || apiKey.trim().length !== 66) {
|
||||
setErrorMsg('Key must start with 0x and be 66 characters')
|
||||
setSaveState('error')
|
||||
return
|
||||
}
|
||||
setErrorMsg('')
|
||||
try {
|
||||
setSaveState('signing')
|
||||
const trimmed = apiKey.trim()
|
||||
const env = await signRequest({
|
||||
action: ACTION_SET_API_KEY,
|
||||
wallet: address,
|
||||
body: { api_key: trimmed },
|
||||
signMessageAsync,
|
||||
})
|
||||
setSaveState('saving')
|
||||
const res = await setHlApiKey(env, trimmed)
|
||||
setHlApiKeySet(true, res.masked_key)
|
||||
setApiKey('')
|
||||
setSaveState('success')
|
||||
} catch (err: unknown) {
|
||||
const msg = err instanceof Error ? err.message : 'Unknown error'
|
||||
if (msg.includes('User rejected') || msg.includes('denied')) {
|
||||
setErrorMsg('Signature cancelled')
|
||||
} else {
|
||||
setErrorMsg(msg.slice(0, 120))
|
||||
}
|
||||
setSaveState('error')
|
||||
}
|
||||
}
|
||||
|
||||
const saveLabel =
|
||||
saveState === 'signing' ? 'Waiting for signature…'
|
||||
: saveState === 'saving' ? 'Saving…'
|
||||
: saveState === 'success' ? '✓ Saved'
|
||||
: 'Save key'
|
||||
|
||||
return (
|
||||
<div className="w-[300px] shrink-0 flex flex-col gap-3">
|
||||
{/* Performance card */}
|
||||
<div className="bg-[#0a0a0a] border border-[#141414] rounded-[10px] p-5">
|
||||
<p className="text-[11px] uppercase tracking-wider text-[#555555] mb-4">
|
||||
{t('title')} · {t('period')}
|
||||
</p>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
{stats.map((stat) => (
|
||||
<div key={stat.label}>
|
||||
<p className="text-[10px] text-[#555555] mb-0.5">{stat.label}</p>
|
||||
<p className={`text-[16px] font-medium ${stat.positive ? 'text-[#4ade80]' : 'text-white'}`}>
|
||||
{stat.display ?? stat.value}
|
||||
</p>
|
||||
<>
|
||||
{/* Bot status card — dark design */}
|
||||
<div className="bot-status">
|
||||
<div className="bot-head">
|
||||
<h3>
|
||||
<span style={{ width: 8, height: 8, borderRadius: 999, background: isSubscribed ? 'var(--amber)' : 'oklch(70% 0.01 85)', display: 'inline-block' }} />
|
||||
Auto-trader
|
||||
</h3>
|
||||
<span style={{ fontSize: 11, opacity: 0.7, textTransform: 'uppercase', letterSpacing: '0.08em' }}>30 days</span>
|
||||
</div>
|
||||
|
||||
<div className="bot-stats">
|
||||
<div className="bot-stat">
|
||||
<div className="k">Net P&L</div>
|
||||
<div className="v amber">
|
||||
{performance ? (performance.net_pnl_usd >= 0 ? '+$' : '-$') + Math.abs(performance.net_pnl_usd).toLocaleString(undefined, { maximumFractionDigits: 0 }) : '—'}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="bot-stat">
|
||||
<div className="k">Win rate</div>
|
||||
<div className="v up">
|
||||
{performance ? (performance.win_rate * 100).toFixed(1) + '%' : '—'}
|
||||
</div>
|
||||
</div>
|
||||
<div className="bot-stat">
|
||||
<div className="k">Trades</div>
|
||||
<div className="v">{performance?.total_trades ?? '—'}</div>
|
||||
</div>
|
||||
<div className="bot-stat">
|
||||
<div className="k">Avg hold</div>
|
||||
<div className="v">{performance ? fmtHold(performance.avg_hold_seconds) : '—'}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bot-cta">
|
||||
{!isConnected && (
|
||||
<button className="btn amber" style={{ width: '100%' }}
|
||||
onClick={() => document.querySelector<HTMLButtonElement>('.connect-btn')?.click()}>
|
||||
Connect wallet
|
||||
</button>
|
||||
)}
|
||||
{isConnected && !isSubscribed && (
|
||||
<div style={{ width: '100%' }}>
|
||||
<button
|
||||
className="btn amber"
|
||||
style={{ width: '100%' }}
|
||||
onClick={handleSubscribe}
|
||||
disabled={subState === 'signing' || subState === 'saving'}
|
||||
>
|
||||
{subState === 'signing' ? 'Waiting for signature…' : subState === 'saving' ? 'Activating…' : 'Start trading'}
|
||||
</button>
|
||||
{subState === 'error' && subError && (
|
||||
<p style={{ fontSize: 11, color: 'var(--down)', marginTop: 6, textAlign: 'center' }}>{subError}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{isConnected && isSubscribed && !hlApiKeySet && (
|
||||
<div style={{ width: '100%', textAlign: 'center', fontSize: 12, color: 'oklch(75% 0.01 85)', padding: '6px 0' }}>
|
||||
↓ Paste your Hyperliquid API key below to activate
|
||||
</div>
|
||||
)}
|
||||
{isConnected && isSubscribed && hlApiKeySet && (
|
||||
<div style={{ width: '100%', textAlign: 'center', fontSize: 12, color: 'var(--amber)', padding: '6px 0', fontWeight: 500 }}>
|
||||
✓ Bot active · waiting for next signal
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="h-px bg-[#141414]" />
|
||||
|
||||
{/* Conditional bottom section */}
|
||||
{!isConnected && (
|
||||
<div className="bg-[#0a0a0a] border border-[#141414] rounded-[10px] p-5 flex flex-col gap-3">
|
||||
<p className="text-[14px] font-medium text-white">{t('connectCta')}</p>
|
||||
<p className="text-[12px] text-[#555555] leading-relaxed">{t('connectDesc')}</p>
|
||||
<button
|
||||
onClick={openConnectModal}
|
||||
className="w-full bg-[#f97316] text-black font-medium text-[13px] rounded-lg py-2.5 hover:bg-[#fb923c] transition-colors"
|
||||
>
|
||||
{t('connectWalletFree')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isConnected && !isSubscribed && (
|
||||
<div className="bg-[#0a0a0a] border border-[#141414] rounded-[10px] p-5 flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-[13px] font-medium text-[#333333]">{t('settingsTitle')}</p>
|
||||
<span className="text-[10px] text-[#333333] border border-[#1e1e1e] rounded-full px-2 py-0.5">
|
||||
Locked
|
||||
</span>
|
||||
</div>
|
||||
{/* Disabled API key input */}
|
||||
<div className="opacity-40">
|
||||
<label className="text-[11px] text-[#555555] block mb-1">{t('apiKeyLabel')}</label>
|
||||
<input
|
||||
disabled
|
||||
placeholder={t('apiKeyPlaceholder')}
|
||||
className="w-full bg-[#060606] border border-[#141414] rounded-lg px-3 py-2 text-[12px] text-[#333333] placeholder-[#222222] cursor-not-allowed"
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
onClick={() => setSubscribed(true)}
|
||||
className="w-full bg-[#f97316] text-black font-medium text-[13px] rounded-lg py-2.5 hover:bg-[#fb923c] transition-colors"
|
||||
>
|
||||
{t('subscribeBtn')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* HL API Key card — only when subscribed */}
|
||||
{isConnected && isSubscribed && (
|
||||
<div className="bg-[#0a0a0a] border border-[#141414] rounded-[10px] p-5 flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-[13px] font-medium text-white">{t('settingsTitle')}</p>
|
||||
<span className="text-[10px] text-[#4ade80] border border-[#1a4a2a] bg-[#0d2e1a] rounded-full px-2 py-0.5">
|
||||
{t('activeStatus')}
|
||||
</span>
|
||||
<div className="card" style={{ padding: 20 }}>
|
||||
<div className="section-title">
|
||||
<h2 style={{ fontSize: 14 }}>Hyperliquid API key</h2>
|
||||
{hlApiKeySet && <span style={{ fontSize: 11, color: 'var(--up)', fontWeight: 500 }}>✓ Connected</span>}
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-[11px] text-[#555555] block mb-1">{t('apiKeyLabel')}</label>
|
||||
<input
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder={t('apiKeyPlaceholder')}
|
||||
className="w-full bg-[#060606] border border-[#141414] rounded-lg px-3 py-2 text-[12px] text-white placeholder-[#333333] focus:outline-none focus:border-[#222222]"
|
||||
/>
|
||||
</div>
|
||||
<button className="w-full bg-[#141414] text-white border border-[#1a1a1a] text-[13px] rounded-lg py-2 hover:bg-[#0d0d0d] transition-colors">
|
||||
{t('saveKey')}
|
||||
</button>
|
||||
|
||||
{hlApiKeySet && !apiKey && (
|
||||
<div className="row between" style={{ padding: '10px 12px', background: 'var(--bg-sunk)', borderRadius: 'var(--r-sm)', border: '1px solid var(--line)', marginBottom: 12 }}>
|
||||
<span style={{ fontSize: 12, color: 'var(--up)', fontFamily: 'var(--mono)' }}>
|
||||
{hlApiKeyMasked ?? '···'}
|
||||
</span>
|
||||
<button
|
||||
style={{ fontSize: 11, color: 'var(--ink-3)' }}
|
||||
onClick={() => { setSaveState('idle'); setApiKey(' ') }}
|
||||
>
|
||||
Update
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(!hlApiKeySet || apiKey) && (
|
||||
<>
|
||||
<div className="field" style={{ marginBottom: 12 }}>
|
||||
<label>API wallet private key</label>
|
||||
<input
|
||||
value={apiKey.trim() === '' && hlApiKeySet ? '' : apiKey}
|
||||
onChange={(e) => {
|
||||
setApiKey(e.target.value)
|
||||
if (saveState === 'error' || saveState === 'success') setSaveState('idle')
|
||||
}}
|
||||
placeholder="0x…"
|
||||
/>
|
||||
<div className="hint">
|
||||
From{' '}
|
||||
<a href="https://app.hyperliquid.xyz/API" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--amber-ink)' }}>
|
||||
app.hyperliquid.xyz/API
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{saveState === 'error' && errorMsg && (
|
||||
<p style={{ fontSize: 11, color: 'var(--down)', marginBottom: 8 }}>{errorMsg}</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
className={`btn ${saveState === 'success' ? 'ghost' : 'amber'}`}
|
||||
style={{ width: '100%' }}
|
||||
onClick={handleSaveKey}
|
||||
disabled={saveState === 'signing' || saveState === 'saving' || !apiKey.trim()}
|
||||
>
|
||||
{saveLabel}
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
|
||||
{!hlApiKeySet && (
|
||||
<details style={{ marginTop: 12 }}>
|
||||
<summary style={{ fontSize: 11, color: 'var(--ink-3)', cursor: 'pointer' }}>
|
||||
How to get your API key
|
||||
</summary>
|
||||
<ol style={{ marginTop: 8, fontSize: 11, color: 'var(--ink-3)', paddingLeft: 16, lineHeight: 1.7 }}>
|
||||
<li>Deposit USDC at app.hyperliquid.xyz</li>
|
||||
<li>Go to app.hyperliquid.xyz/API</li>
|
||||
<li>Click <strong>Generate API Wallet</strong></li>
|
||||
<li>Sign with MetaMask (no gas)</li>
|
||||
<li>Copy the private key → paste above</li>
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user