Files
trumpsignal-frontend/components/dashboard/BotPanel.tsx
T
k d01adc4790 style(dashboard): unify Macro composite into one card + dark-mode fix
for Performance accent

User flagged the macro index box on the overview page as feeling
disjointed. Reshaped it from three stacked elements (band → track →
scale) into a single bordered card so it reads as ONE component.

  - JSX: wrap the three pieces in <div className="overview-macro-card">
  - CSS: new .overview-macro-card with tone-coloured rim (bull/bear/neutral)
  - Solid neutral-gray filled needle (was a hollow ring — looked like a
    placeholder); tone-coloured background + white inner ring + double
    shadow so it stands out on any gradient position
  - Removed the .overview-score-fill overlay — the gradient already
    encodes the spectrum; layering an opaque fill obscured it near 0
  - Thinner track (14px vs 22px), tighter scale labels, smaller pill
  - Added "TODAY · 8 INDICATORS" stamp next to the title — gives users
    a quick anchor of what they're looking at + freshness

Plus: dark-mode override for .overview-stat-card.accent (the Performance
card). It was using a cream gradient that floated as a glaring
out-of-theme block on dark mode. Mirrored the existing .kpi.accent dark
treatment so it stays visually grouped with the rest of the dashboard.

Also includes the in-flight overview rewrite from the other AI tool
(legacy /btc redirect to /macro, middleware.ts replacing proxy.ts for
Next.js routing, refactored several dashboard panels). TypeScript clean,
production build passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-27 11:25:59 +08:00

297 lines
11 KiB
TypeScript

'use client'
import { useEffect, useState } from 'react'
import { useAccount, useConnect, useSignMessage } from 'wagmi'
import type { BotPerformance } from '@/types'
import { useDashboardStore } from '@/store/dashboard'
import { getUserPublic, setHlApiKey, subscribe } from '@/lib/api'
import { signRequest } from '@/lib/signedRequest'
import { isUserRejection, walletErrorLabel } from '@/lib/walletError'
import { getFirstReadyConnector, walletConnectErrorLabel } from '@/lib/walletConnect'
// 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
}
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 }: Props) {
const { isSubscribed, hlApiKeySet, hlApiKeyMasked, botReadiness, setBotReadiness, setHlApiKeySet, setSubscribed } = useDashboardStore()
const { address, isConnected } = useAccount()
const { connectAsync, connectors } = useConnect()
const { signMessageAsync } = useSignMessage()
const [mounted, setMounted] = useState(false)
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('')
const [connectError, setConnectError] = useState('')
useEffect(() => { setMounted(true) }, [])
useEffect(() => {
if (!isConnected || !address) {
setSubscribed(false)
setHlApiKeySet(false)
setBotReadiness('unknown')
return
}
setSubscribed(false)
setHlApiKeySet(false)
setBotReadiness('unknown')
getUserPublic(address.toLowerCase())
.then((user) => {
setSubscribed(user.active)
setHlApiKeySet(user.hl_api_key_set)
setBotReadiness(user.hl_api_key_set ? 'saved' : 'unknown')
})
.catch(() => {})
}, [address, isConnected, setHlApiKeySet, setSubscribed, setBotReadiness])
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
}
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)
await refreshUserState(address)
setSubState('idle')
} catch (err: unknown) {
setSubError(walletErrorLabel(err, 'Signature cancelled', 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)
const pub = await refreshUserState(address)
setHlApiKeySet(pub.hl_api_key_set, res.masked_key)
setApiKey('')
setSaveState('success')
} catch (err: unknown) {
if (isUserRejection(err)) {
setErrorMsg('Signature cancelled')
} else {
setErrorMsg(walletErrorLabel(err, 'Signature cancelled', 120))
}
setSaveState('error')
}
}
const saveLabel =
saveState === 'signing' ? 'Waiting for signature…'
: saveState === 'saving' ? 'Saving…'
: saveState === 'success' ? '✓ Saved'
: 'Save key'
async function handleConnectWallet() {
setConnectError('')
try {
const connector = await getFirstReadyConnector(connectors)
if (!connector) {
setConnectError('No wallet connector is available right now.')
return
}
await connectAsync({ connector })
} catch (err: unknown) {
setConnectError(walletConnectErrorLabel(err))
}
}
return (
<>
{/* Bot status card — dark design */}
<div className="bot-status">
<div className="bot-head">
<h3>
<span style={{ width: 8, height: 8, borderRadius: 999, background: botReadiness === 'ready' ? 'var(--amber)' : hlApiKeySet ? 'var(--up)' : isSubscribed ? 'var(--up)' : '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&amp;L</div>
<div className="v amber">
{performance ? (performance.net_pnl_usd >= 0 ? '+$' : '-$') + Math.abs(performance.net_pnl_usd).toLocaleString('en-US', { 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">
{(!mounted || !isConnected) && (
<>
<button className="btn amber" style={{ width: '100%' }}
onClick={() => { void handleConnectWallet() }}>
Connect wallet
</button>
{connectError && (
<p style={{ fontSize: 11, color: 'var(--down)', marginTop: 6, textAlign: 'center' }}>{connectError}</p>
)}
</>
)}
{mounted && 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>
)}
{mounted && 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 finish setup
</div>
)}
{mounted && isConnected && isSubscribed && hlApiKeySet && (
<div style={{ width: '100%', textAlign: 'center', fontSize: 12, color: 'var(--amber)', padding: '6px 0', fontWeight: 500 }}>
Setup saved · verification still depends on backend
</div>
)}
</div>
</div>
{/* HL API Key card — only when subscribed */}
{mounted && isConnected && isSubscribed && (
<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>
{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>
)}
</>
)
}