refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router

This commit is contained in:
2026-11-03 20:42:30 +08:00
parent de1a903462
commit 1791dbb557
188 changed files with 52461 additions and 2 deletions
+67
View File
@@ -0,0 +1,67 @@
import Head from 'next/head'
import type { Metadata } from 'next'
import { siteMetadata } from '@/lib/siteMetadata'
function titleText(value: Metadata['title'], fallback: string): string {
if (typeof value === 'string') return value
if (value && typeof value === 'object') {
if ('absolute' in value && value.absolute) return value.absolute
if ('default' in value && value.default) return value.default
}
return fallback
}
export function PageHead({ seo = {} }: { seo?: Metadata }) {
const title = titleText(seo.title, titleText(siteMetadata.title, 'Trump Alpha'))
const description = seo.description ?? siteMetadata.description ?? ''
const canonical =
seo.alternates?.canonical?.toString() ?? siteMetadata.alternates?.canonical?.toString()
const robots = seo.robots ?? siteMetadata.robots
const robotsText =
typeof robots === 'string'
? robots
: [
robots?.index === false ? 'noindex' : 'index',
robots?.follow === false ? 'nofollow' : 'follow',
].join(',')
const keywords = seo.keywords ?? siteMetadata.keywords
const languages = seo.alternates?.languages ?? siteMetadata.alternates?.languages
return (
<Head>
<title>{title}</title>
<meta name="description" content={description} />
<meta name="application-name" content="Trump Alpha" />
{keywords && (
<meta name="keywords" content={Array.isArray(keywords) ? keywords.join(', ') : keywords} />
)}
<meta name="author" content="Endorphin" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0f0d0a" />
<meta name="robots" content={robotsText} />
{canonical && <link rel="canonical" href={canonical} />}
{languages &&
Object.entries(languages).map(([language, value]) => (
<link
key={language}
rel="alternate"
hrefLang={language}
href={String(Array.isArray(value) ? value[0]?.url : value)}
/>
))}
<meta property="og:title" content={title} />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Trump Alpha" />
<meta property="og:locale" content="en_US" />
<meta
property="og:image"
content={`${process.env.NEXT_PUBLIC_SITE_URL || 'https://trumpsignal.com'}/opengraph-image`}
/>
<meta property="og:description" content={description} />
{canonical && <meta property="og:url" content={canonical} />}
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<link rel="manifest" href="/manifest.webmanifest" />
<link rel="icon" href="/icon" />
<link rel="apple-touch-icon" href="/apple-icon" />
</Head>
)
}
+34
View File
@@ -0,0 +1,34 @@
'use client'
import { WagmiProvider } from 'wagmi'
import { RainbowKitProvider, darkTheme } from '@rainbow-me/rainbowkit'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState } from 'react'
import { config } from '@/lib/wagmi'
import { WsProvider } from '@/lib/wsContext'
interface ProvidersProps {
children: React.ReactNode
}
export default function Providers({ children }: ProvidersProps) {
const [queryClient] = useState(() => new QueryClient())
return (
<WagmiProvider config={config} reconnectOnMount={false}>
<QueryClientProvider client={queryClient}>
<RainbowKitProvider
theme={darkTheme({
accentColor: '#f97316',
accentColorForeground: '#000000',
borderRadius: 'medium',
overlayBlur: 'small',
})}
>
{/* Single shared WebSocket — all components subscribe via useWsSubscribe */}
<WsProvider>{children}</WsProvider>
</RainbowKitProvider>
</QueryClientProvider>
</WagmiProvider>
)
}
+740
View File
@@ -0,0 +1,740 @@
'use client'
import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'
import { getMacroSnapshot, type MacroSnapshot } from '@/lib/api'
import { swrFetch } from '@/lib/cache'
import InfoTip from '@/components/ui/InfoTip'
function fmtUsd(n: number | null | undefined, { compact = false } = {}): string {
if (n == null || isNaN(n)) return '—'
const abs = Math.abs(n)
if (compact) {
if (abs >= 1e9) return `${(n / 1e9).toFixed(2)}B`
if (abs >= 1e6) return `${(n / 1e6).toFixed(1)}M`
if (abs >= 1e3) return `${(n / 1e3).toFixed(0)}K`
return n.toFixed(0)
}
return n.toLocaleString('en-US', { maximumFractionDigits: 2 })
}
function fmtSignedUsd(n: number | null | undefined): string {
if (n == null || isNaN(n)) return '—'
const compact = fmtUsd(Math.abs(n), { compact: true })
return (n >= 0 ? '+$' : '-$') + compact
}
function fmtPct(n: number | null | undefined, digits = 2): string {
if (n == null || isNaN(n)) return '—'
return n.toFixed(digits) + '%'
}
type Tone = 'up' | 'down' | 'neutral'
function toneAhr(v: number | null): Tone {
if (v == null) return 'neutral'
if (v < 0.45) return 'up'
if (v > 1.2) return 'down'
return 'neutral'
}
function toneAltseason(v: number | null): Tone {
if (v == null) return 'neutral'
if (v >= 75) return 'up'
if (v <= 25) return 'down'
return 'neutral'
}
function toneFearGreed(v: number | null): Tone {
if (v == null) return 'neutral'
if (v <= 25) return 'up'
if (v >= 75) return 'down'
return 'neutral'
}
function toneEtfFlow(v: number | null): Tone {
if (v == null) return 'neutral'
if (v > 50_000_000) return 'up'
if (v < -50_000_000) return 'down'
return 'neutral'
}
function toneBtcDominance(v: number | null): Tone {
if (v == null) return 'neutral'
if (v >= 60 || v <= 40) return 'down'
return 'neutral'
}
function toneEthBtc(v: number | null): Tone {
if (v == null) return 'neutral'
if (v >= 0.04) return 'up'
if (v <= 0.025) return 'down'
return 'neutral'
}
const REGIME_COLOR: Record<string, string> = {
BULL: 'var(--up)',
BULLISH: 'var(--up)',
NEUTRAL: 'var(--ink-3)',
BEARISH: 'var(--down)',
BEAR: 'var(--down)',
}
/**
* Single "Open chart" button per card. Was two (Data source + Chart) — users
* couldn't tell which to click and the dual-link group split attention.
* Defaults to a CoinGlass page; when CoinGlass doesn't host the indicator
* (Pi Cycle Bottom, Stablecoin Supply), we fall back to the canonical site.
*/
function SourceButton({ href, children }: { href: string; children: ReactNode }) {
return (
<a href={href} target="_blank" rel="noreferrer" className="macro-action-btn chart">
<span className="macro-action-copy">
<span className="macro-action-kicker">Open chart</span>
<span className="macro-action-label">{children}</span>
</span>
<span className="macro-action-arrow" aria-hidden="true">
↗
</span>
</a>
)
}
function ThresholdChip({
tone = 'neutral',
active = false,
children,
}: {
tone?: Tone
active?: boolean
children: ReactNode
}) {
const cls = `macro-threshold-chip ${tone}${active ? ' active' : ''}`
return <span className={cls}>{children}</span>
}
function MetricCard({
rank,
label,
value,
tone = 'neutral',
hint,
summary,
thresholds,
activeIndex,
chartHref,
chartLabel = 'CoinGlass',
hero = false,
}: {
rank: number
label: string
value: string
tone?: Tone
/** What the indicator IS, one sentence. Do NOT enumerate threshold bands
* here — the chips below each card already list them. */
hint: string
summary: string
thresholds: Array<{ label: string; tone?: Tone }>
/** Index into `thresholds` of the band the current value falls into.
* Renders that chip with the .active class — full opacity + highlight. */
activeIndex?: number
/** URL of the canonical chart page (usually CoinGlass). One button only —
* the dual "Data source + Chart" pattern confused users about which to click. */
chartHref: string
chartLabel?: string
/** Horizontal headline layout for a single full-width card (Valuation).
* The stacked layout stretched across the panel left a dead middle. */
hero?: boolean
}) {
const head = (
<div className="macro-metric-head">
<div className="macro-metric-title">
<span className="macro-rank">{String(rank).padStart(2, '0')}</span>
<span>{label}</span>
<InfoTip text={hint} placement="top" width={280} />
</div>
<div className="macro-metric-value">{value}</div>
</div>
)
const chips = (
<div className="macro-thresholds">
{thresholds.map((item, i) => (
<ThresholdChip key={item.label} tone={item.tone} active={i === activeIndex}>
{item.label}
</ThresholdChip>
))}
</div>
)
const action = (
<div className="macro-actions">
<SourceButton href={chartHref}>{chartLabel}</SourceButton>
</div>
)
if (hero) {
return (
<article className={`macro-metric-card tone-${tone} hero`}>
{head}
<div className="macro-hero-body">
<div className="macro-summary">{summary}</div>
{chips}
</div>
{action}
</article>
)
}
return (
<article className={`macro-metric-card tone-${tone}`}>
{head}
<div className="macro-summary">{summary}</div>
{chips}
{action}
</article>
)
}
function GuideCard({
title,
summary,
thresholds,
chartHref,
chartLabel = 'CoinGlass',
}: {
title: string
summary: string
thresholds: Array<{ label: string; tone?: Tone }>
chartHref: string
chartLabel?: string
}) {
return (
<article className="macro-guide-card">
<div className="macro-guide-title">{title}</div>
<div className="macro-summary">{summary}</div>
<div className="macro-thresholds">
{thresholds.map((item) => (
<ThresholdChip key={item.label} tone={item.tone}>
{item.label}
</ThresholdChip>
))}
</div>
<div className="macro-actions">
<SourceButton href={chartHref}>{chartLabel}</SourceButton>
</div>
</article>
)
}
function Section({
title,
children,
variant,
}: {
title: string
children: ReactNode
/** "reference" tones the section down + adds a 📐 icon so users see at a
* glance that the cards inside are explainers, not live data. */
variant?: 'reference'
}) {
return (
<section className={`macro-section${variant ? ' ' + variant : ''}`}>
<div className="macro-section-title">{title}</div>
{children}
</section>
)
}
export default function MacroPanel() {
const [snap, setSnap] = useState<MacroSnapshot | null>(null)
const [err, setErr] = useState('')
useEffect(() => {
let alive = true
function load() {
swrFetch(
'macro-snapshot',
10 * 60_000,
() => getMacroSnapshot(),
(fresh) => {
if (alive) setSnap(fresh)
},
)
.then((s) => {
if (alive) {
setSnap(s)
setErr('')
}
})
.catch((e) => {
if (alive) setErr(e instanceof Error ? e.message : 'load failed')
})
}
load()
const id = setInterval(load, 10 * 60_000)
return () => {
alive = false
clearInterval(id)
}
}, [])
if (err) {
return (
<div className="card" style={{ padding: 14, fontSize: 12, color: 'var(--down)' }}>
Couldn&apos;t load macro indicators — {err}
</div>
)
}
if (!snap) {
return (
<div className="skeleton-card">
<div className="skeleton sk-line sk-w-3q" />
<div className="skeleton sk-line sk-w-half" />
<div className="skeleton sk-line sk-w-full" />
</div>
)
}
if (!snap.ok || !snap.indicators) {
return (
<div className="card" style={{ padding: 14, fontSize: 12, color: 'var(--ink-3)' }}>
Macro snapshot not available yet — {snap.error ?? 'cron has not run'}.
</div>
)
}
const ind = snap.indicators
const ahrSay =
ind.ahr999 == null
? 'No data yet.'
: ind.ahr999 < 0.45
? 'Deep-value zone. Historically this is where macro accumulation starts to make sense.'
: ind.ahr999 > 1.2
? 'Expensive regime. This is no longer a bottom setup.'
: ind.ahr999 < 0.75
? 'Reasonable value. Closer to cheap than to overheated.'
: 'Neutral-to-rich. No strong valuation edge from this metric alone.'
const altSay =
ind.altcoin_season_index == null
? 'No data yet.'
: ind.altcoin_season_index >= 75
? 'Altseason conditions. Broad risk appetite is favoring alts over BTC.'
: ind.altcoin_season_index >= 60
? 'Alt strength is building, but it is not a full altseason yet.'
: ind.altcoin_season_index >= 40
? 'Mixed tape. Neither BTC nor alts have a decisive lead.'
: ind.altcoin_season_index >= 25
? 'BTC is leading. This is a more defensive market posture.'
: 'Bitcoin season. Alts are broadly lagging BTC.'
const fgSay =
ind.fear_greed == null
? 'No data yet.'
: ind.fear_greed <= 20
? 'Extreme fear. Contrarian bottom-hunting conditions.'
: ind.fear_greed <= 40
? 'Fear is present, but not yet a full washout.'
: ind.fear_greed <= 60
? 'Neutral sentiment. Little edge from crowd psychology here.'
: ind.fear_greed <= 80
? 'Greed is building. Be selective about adding exposure.'
: 'Extreme greed. Historically a poor place to chase upside.'
const domSay =
ind.btc_dominance_pct == null
? 'No data yet.'
: ind.btc_dominance_pct >= 65
? 'Capital is crowding back into BTC. That usually reads as caution.'
: ind.btc_dominance_pct >= 55
? 'BTC still leads the market. Risk appetite is present, but selective.'
: ind.btc_dominance_pct >= 45
? 'Balanced regime. No strong breadth message from dominance.'
: ind.btc_dominance_pct >= 35
? 'Alt participation is improving. Risk appetite is broadening.'
: 'Dominance is very low. That often shows late-cycle froth.'
const ebrSay =
ind.eth_btc_ratio == null
? 'No data yet.'
: ind.eth_btc_ratio >= 0.05
? 'ETH leadership is strong. This usually maps to a cleaner risk-on regime.'
: ind.eth_btc_ratio >= 0.04
? 'ETH is waking up versus BTC. Useful confirmation for broader crypto risk appetite.'
: ind.eth_btc_ratio >= 0.03
? 'Range-bound. ETH/BTC is not giving a decisive leadership signal.'
: ind.eth_btc_ratio >= 0.025
? 'ETH is lagging, which usually means BTC remains the safer bid.'
: 'ETH is weak versus BTC. This is a defensive backdrop.'
const stabSay =
ind.stablecoin_supply_usd == null
? 'No data yet.'
: 'This is a liquidity gauge, not a hard trigger. Watch the direction of supply over time.'
const etfSay =
ind.etf_flow_net_usd_1d == null
? 'No data yet.'
: (() => {
const v = ind.etf_flow_net_usd_1d ?? 0
if (v >= 500_000_000) return 'Huge ETF inflow day. Institutions are pressing the bid.'
if (v >= 200_000_000)
return 'Strong inflow day. Institutional demand is clearly supportive.'
if (v >= 50_000_000) return 'Positive day, but not a major outlier.'
if (v > -50_000_000) return 'Roughly flat. No strong institutional message.'
if (v > -200_000_000) return 'Moderate outflow day. Some distribution, but not panic.'
if (v > -500_000_000) return 'Heavy outflows. Institutions are leaning defensive.'
return 'Very large outflows. This is a meaningful risk-off signal.'
})()
const oiSay =
ind.btc_open_interest_usd == null
? 'No data yet.'
: 'Use this with price, not by itself. Rising OI confirms commitment; falling OI shows deleveraging.'
// ── Active threshold band per indicator ─────────────────────────────────
// Each function returns the index into the indicator's `thresholds` array
// that the CURRENT value falls into. Renders that chip with the .active
// CSS class so it stands out from the muted siblings.
// Indexes MUST stay in lock-step with the threshold array order below.
const ahrActive =
ind.ahr999 == null
? -1
: ind.ahr999 < 0.45
? 0
: ind.ahr999 < 0.75
? 1
: ind.ahr999 <= 1.2
? 2
: 3
const altActive =
ind.altcoin_season_index == null
? -1
: ind.altcoin_season_index < 25
? 0
: ind.altcoin_season_index < 60
? 1
: ind.altcoin_season_index < 75
? 2
: 3
const fgActive =
ind.fear_greed == null
? -1
: ind.fear_greed < 25
? 0
: ind.fear_greed < 45
? 1
: ind.fear_greed < 60
? 2
: ind.fear_greed < 75
? 3
: 4
const domActive =
ind.btc_dominance_pct == null
? -1
: ind.btc_dominance_pct < 45
? 0
: ind.btc_dominance_pct < 55
? 1
: ind.btc_dominance_pct < 65
? 2
: 3
const ebrActive =
ind.eth_btc_ratio == null
? -1
: ind.eth_btc_ratio < 0.025
? 0
: ind.eth_btc_ratio < 0.04
? 1
: 2
const etfActive =
ind.etf_flow_net_usd_1d == null
? -1
: ind.etf_flow_net_usd_1d > 200_000_000
? 0
: ind.etf_flow_net_usd_1d < -200_000_000
? 2
: 1
const stabActive = ind.stablecoin_supply_usd == null ? -1 : 1 // we can't infer trend → land mid
const compositeColor =
snap.composite_score == null
? 'var(--ink-3)'
: snap.composite_score > 3
? 'var(--up)'
: snap.composite_score < -3
? 'var(--down)'
: 'var(--ink-3)'
const compositePct =
snap.composite_score == null ? 50 : Math.max(0, Math.min(100, (snap.composite_score + 100) / 2))
const trackGradient =
'linear-gradient(to right, ' +
'color-mix(in oklab, var(--down) 70%, transparent) 0%, ' +
'color-mix(in oklab, var(--down) 25%, transparent) 35%, ' +
'var(--bg-sunk) 50%, ' +
'color-mix(in oklab, var(--up) 25%, transparent) 65%, ' +
'color-mix(in oklab, var(--up) 70%, transparent) 100%)'
return (
<div className="card macro-panel">
<div className="macro-panel-head">
<div>
<div className="macro-panel-title">
<span className="macro-panel-dot" />
Macro indicators
</div>
<div className="macro-panel-subtitle">
Daily snapshot for BTC macro context. Designed for scanning first, details second.
</div>
</div>
<div className="macro-panel-meta">
<div>{snap.date}</div>
<div>free public sources</div>
</div>
</div>
<Section title="Valuation">
<div className="macro-grid one">
<MetricCard
hero
rank={1}
label="AHR999"
value={ind.ahr999?.toFixed(4) ?? '—'}
tone={toneAhr(ind.ahr999)}
hint="BTC valuation index: price vs 200-day geometric mean × price vs fitted long-run growth curve. Lower = cheaper."
summary={ahrSay}
activeIndex={ahrActive}
thresholds={[
{ label: '< 0.45 buy zone', tone: 'up' },
{ label: '0.45–0.75 fair value', tone: 'neutral' },
{ label: '0.75–1.2 no edge', tone: 'neutral' },
{ label: '> 1.2 expensive', tone: 'down' },
]}
chartHref="https://www.coinglass.com/en/pro/i/ahr999"
chartLabel="CoinGlass"
/>
</div>
</Section>
<Section title="Bottom trigger reference" variant="reference">
<div className="macro-grid two">
<GuideCard
title="200-week Moving Average"
summary="A structural support check. In this system, price near the 200WMA is one of the three bottom votes."
thresholds={[
{ label: '≤ 1.05× 200WMA = vote ON', tone: 'up' },
{ label: 'Below 200WMA = strongest value zone', tone: 'up' },
{ label: '1.05×–1.20× above = recovering', tone: 'neutral' },
{ label: 'Far above = no bottom vote', tone: 'down' },
]}
chartHref="https://www.coinglass.com/pro/i/200WMA"
chartLabel="CoinGlass"
/>
<GuideCard
title="Pi Cycle Bottom"
summary="A binary bottom condition. It is either confirmed or not confirmed; there is no graded middle reading in the live code."
thresholds={[
{ label: '150EMA ≤ 471SMA × 0.745 = vote ON', tone: 'up' },
{ label: '150EMA above line = not confirmed', tone: 'down' },
]}
// CoinGlass only hosts Pi Cycle TOP; for Pi Cycle BOTTOM the
// canonical chart lives on LookIntoBitcoin.
chartHref="https://www.lookintobitcoin.com/charts/pi-cycle-bottom-indicator/"
chartLabel="LookIntoBitcoin"
/>
</div>
</Section>
<Section title="Market structure">
<div className="macro-grid two">
<MetricCard
rank={2}
label="Altcoin Season"
value={
ind.altcoin_season_index == null
? '—'
: ind.altcoin_season_index.toFixed(0) + ' / 100'
}
tone={toneAltseason(ind.altcoin_season_index)}
hint="% of top-50 alts that beat BTC over the last 90 days (blockchaincenter.net formula). Higher = broader alt strength."
summary={altSay}
activeIndex={altActive}
thresholds={[
{ label: '< 25 Bitcoin season', tone: 'down' },
{ label: '25–60 mixed', tone: 'neutral' },
{ label: '60–75 alt strength', tone: 'up' },
{ label: '≥ 75 altseason', tone: 'up' },
]}
chartHref="https://www.blockchaincenter.net/altcoin-season-index/"
chartLabel="BlockchainCenter"
/>
<MetricCard
rank={3}
label="BTC Dominance"
value={fmtPct(ind.btc_dominance_pct)}
tone={toneBtcDominance(ind.btc_dominance_pct)}
hint="BTC's share of total crypto market cap. High dominance = defensive, capital hiding in BTC; low = alt rotation."
summary={domSay}
activeIndex={domActive}
thresholds={[
{ label: '< 45% alt rotation', tone: 'up' },
{ label: '45–55% balanced', tone: 'neutral' },
{ label: '55–65% BTC-led', tone: 'neutral' },
{ label: '> 65% safety trade', tone: 'down' },
]}
chartHref="https://www.coinglass.com/pro/i/bitcoin-dominance"
chartLabel="CoinGlass"
/>
<MetricCard
rank={4}
label="ETH / BTC"
value={ind.eth_btc_ratio == null ? '—' : ind.eth_btc_ratio.toFixed(5)}
tone={toneEthBtc(ind.eth_btc_ratio)}
hint="Relative strength of ETH vs BTC — a proxy for broader crypto risk appetite."
summary={ebrSay}
activeIndex={ebrActive}
thresholds={[
{ label: '< 0.025 defensive', tone: 'down' },
{ label: '0.025–0.04 range', tone: 'neutral' },
{ label: '> 0.04 ETH leadership', tone: 'up' },
]}
chartHref="https://www.coinglass.com/currencies/ETHBTC"
chartLabel="CoinGlass"
/>
</div>
</Section>
<Section title="Sentiment & flows">
<div className="macro-grid two">
<MetricCard
rank={5}
label="Fear & Greed"
value={ind.fear_greed == null ? '—' : String(ind.fear_greed)}
tone={toneFearGreed(ind.fear_greed)}
hint="Sentiment composite from alternative.me. CONTRARIAN read — extreme fear is bullish, extreme greed is bearish."
summary={fgSay}
activeIndex={fgActive}
thresholds={[
{ label: '< 25 → BUY (extreme fear)', tone: 'up' },
{ label: '25–45 fear', tone: 'neutral' },
{ label: '45–60 neutral', tone: 'neutral' },
{ label: '60–75 greed', tone: 'neutral' },
{ label: '> 75 → SELL (extreme greed)', tone: 'down' },
]}
chartHref="https://www.coinglass.com/pro/i/FearGreedIndex?s=09"
chartLabel="CoinGlass"
/>
<MetricCard
rank={6}
label="Stablecoin Supply"
value={
ind.stablecoin_supply_usd == null
? '—'
: '$' + fmtUsd(ind.stablecoin_supply_usd, { compact: true })
}
summary={stabSay}
hint="Sum of all USDT + USDC + DAI + others in circulation. Rising = dry powder accumulating; falling = capital exiting crypto."
activeIndex={stabActive}
thresholds={[
{ label: 'Rising = liquidity building', tone: 'up' },
{ label: 'Flat = neutral', tone: 'neutral' },
{ label: 'Falling = capital leaving', tone: 'down' },
]}
// CoinGlass doesn't expose an all-issuer stablecoin supply view
// cleanly; DeFiLlama is the canonical aggregator we pull from.
chartHref="https://defillama.com/stablecoins"
chartLabel="DeFiLlama"
/>
<MetricCard
rank={7}
label="ETF Net Flow (1d)"
value={fmtSignedUsd(ind.etf_flow_net_usd_1d)}
tone={toneEtfFlow(ind.etf_flow_net_usd_1d)}
hint="Yesterday's total net flow into/out of US spot BTC ETFs — a direct read on institutional demand."
summary={etfSay}
activeIndex={etfActive}
thresholds={[
{ label: '> +$200M strong bid', tone: 'up' },
{ label: '±$50M noise band', tone: 'neutral' },
{ label: '< −$200M heavy outflow', tone: 'down' },
]}
chartHref="https://www.coinglass.com/etf"
/>
<MetricCard
rank={8}
label="BTC Open Interest"
value={
ind.btc_open_interest_usd == null
? '—'
: '$' + fmtUsd(ind.btc_open_interest_usd, { compact: true })
}
summary={oiSay}
hint="Total notional in BTC futures. No universal absolute threshold: use OI with price. Rising OI + rising price = trend confirmation; rising OI + falling price = trapped longs."
thresholds={[
{ label: 'OI up + price up = confirmation', tone: 'up' },
{ label: 'OI up + price down = stress', tone: 'down' },
{ label: 'OI down after flush = reset', tone: 'neutral' },
]}
chartHref="https://www.tradingview.com/symbols/BTC_OI/"
chartLabel="TradingView"
/>
</div>
</Section>
<div className="macro-composite">
<div className="macro-composite-head">
<div>
<div className="macro-composite-label">Composite read</div>
<div className="macro-panel-subtitle">
Advisory blend of the metrics above. Useful for context, not for blind execution.
</div>
</div>
<div className="macro-composite-right">
<span className="macro-composite-value" style={{ color: compositeColor }}>
{snap.composite_score == null
? '—'
: (snap.composite_score > 0 ? '+' : '') + snap.composite_score.toFixed(1)}
</span>
{snap.regime_label ? (
<span
className="macro-regime-pill"
style={{
color: REGIME_COLOR[snap.regime_label] || 'var(--ink-3)',
borderColor: `color-mix(in oklab, ${REGIME_COLOR[snap.regime_label] || 'var(--ink-3)'} 32%, transparent)`,
background: `color-mix(in oklab, ${REGIME_COLOR[snap.regime_label] || 'var(--ink-3)'} 12%, transparent)`,
}}
>
{snap.regime_label}
</span>
) : null}
</div>
</div>
<div className="macro-composite-track" style={{ background: trackGradient }}>
{snap.composite_score != null ? (
<div
// Keying by score forces a remount → the @keyframes pulse on
// .macro-composite-needle re-fires every time the score moves.
key={snap.composite_score}
className="macro-composite-needle"
style={{
left: `calc(${compositePct}% - 10px)`,
borderColor: compositeColor,
color: compositeColor,
}}
/>
) : null}
</div>
<div className="macro-composite-scale">
{/* .word spans are hidden on screens ≤420px so the scale becomes
just "-100", "0", "+100" — fits comfortably on any phone. */}
<span>
−100 <span className="word">bear</span>
</span>
<span>
0 <span className="word">neutral</span>
</span>
<span>
+100 <span className="word">bull</span>
</span>
</div>
</div>
</div>
)
}
@@ -0,0 +1,522 @@
'use client'
import { useEffect, useRef, useState } from 'react'
import type { TrumpPost, Candle } from '@/types'
import { useDashboardStore } from '@/store/dashboard'
interface ChartPanelProps {
posts?: TrumpPost[]
candles?: Candle[]
externalSelectedId?: number | null
onSelectPost?: (id: number | null) => void
onSelectDayPosts?: (posts: TrumpPost[]) => void
}
export default function ChartPanel({
posts = [],
candles = [],
externalSelectedId,
onSelectPost,
onSelectDayPosts,
}: ChartPanelProps) {
const { timeframe, asset, livePrices } = useDashboardStore()
const containerRef = useRef<HTMLDivElement>(null)
const chartRef = useRef<unknown>(null)
const seriesRef = useRef<unknown>(null)
const macroPriceLineRef = useRef<unknown>(null)
const macroVerticalRef = useRef<HTMLDivElement | null>(null)
const macroLabelRef = useRef<HTMLDivElement | null>(null)
// Macro overlay state. The vertical line + label are absolutely-positioned
// DOM nodes (lightweight-charts has no first-class "vertical marker"
// primitive), so we have to manually re-project signal time → pixel X
// every time the visible range / chart width changes. Without this the
// line stays anchored to the SCREEN while the candles pan beneath it,
// which looks exactly like a draggable / floating line.
const macroBucketTimeRef = useRef<number | null>(null)
const macroLabelTextRef = useRef<string>('')
// Imperative reposition fn — set up by the chart-creation effect, called
// from BOTH the data effect (when the signal changes) AND from a
// subscribeVisibleTimeRangeChange callback (when the user pans / zooms).
const repositionMacroRef = useRef<(() => void) | null>(null)
const fittedRef = useRef(false)
// Chart creation is async (dynamic import). If the candles fetch wins the
// race (common — SWR serves them instantly from cache), the data effect
// runs while seriesRef is still null and bails; nothing re-triggers it
// afterwards, so the chart stays EMPTY and the 2s live-tick effect then
// paints a single lone candle via series.update(). This state flips when
// the chart actually exists so the data effect re-runs.
const [chartReady, setChartReady] = useState(false)
// The live-tick effect must never run before setData() — updating an empty
// series creates a one-candle chart.
const dataLoadedRef = useRef(false)
const postsRef = useRef(posts)
postsRef.current = posts
const selectedPostIdRef = useRef(externalSelectedId)
selectedPostIdRef.current = externalSelectedId
const timeframeRef = useRef(timeframe)
timeframeRef.current = timeframe
const onSelectRef = useRef(onSelectPost)
onSelectRef.current = onSelectPost
const onSelectDayPostsRef = useRef(onSelectDayPosts)
onSelectDayPostsRef.current = onSelectDayPosts
// Detect current theme for chart colors
function getChartColors() {
const isDark = document.documentElement.dataset.theme === 'dark'
return {
background: isDark ? '#121212' : '#ffffff',
textColor: isDark ? '#666666' : '#888888',
gridColor: isDark ? '#1e1e1e' : '#f0ede8',
borderColor: isDark ? '#2a2a2a' : '#e8e4de',
macroAccent: isDark ? '#f59e0b' : '#b45309',
macroAccentSoft: isDark ? 'rgba(245,158,11,0.24)' : 'rgba(180,83,9,0.18)',
}
}
// Create chart once on mount
useEffect(() => {
if (!containerRef.current || typeof window === 'undefined') return
let destroyed = false
let ro: ResizeObserver | null = null
let themeObserver: MutationObserver | null = null
import('lightweight-charts').then(({ createChart, CrosshairMode }) => {
if (destroyed || !containerRef.current) return
const colors = getChartColors()
const vertical = document.createElement('div')
vertical.style.position = 'absolute'
vertical.style.top = '0'
vertical.style.bottom = '0'
vertical.style.width = '0'
vertical.style.borderLeft = `2px dashed ${colors.macroAccent}`
vertical.style.opacity = '0'
vertical.style.pointerEvents = 'none'
vertical.style.zIndex = '2'
// NO transition on `left` — the reposition callback fires on every
// pan/zoom frame; a 160ms ease there makes the line lag visibly
// behind the candles and looks exactly like the original bug.
vertical.style.transition = 'opacity 120ms ease'
containerRef.current.appendChild(vertical)
macroVerticalRef.current = vertical
const label = document.createElement('div')
label.style.position = 'absolute'
label.style.top = '14px'
label.style.left = '0'
label.style.padding = '5px 8px'
label.style.borderRadius = '999px'
label.style.border = `1px solid ${colors.macroAccentSoft}`
label.style.background = colors.background
label.style.boxShadow = '0 6px 24px rgba(15, 23, 42, 0.08)'
label.style.color = colors.macroAccent
label.style.fontSize = '11px'
label.style.fontWeight = '700'
label.style.letterSpacing = '0.04em'
label.style.textTransform = 'uppercase'
label.style.whiteSpace = 'nowrap'
label.style.pointerEvents = 'none'
label.style.opacity = '0'
label.style.transform = 'translateX(-50%)'
label.style.zIndex = '3'
// Same reasoning as the vertical line: no transition on `left` —
// panning must keep the label glued to its timestamp without lag.
label.style.transition = 'opacity 120ms ease'
containerRef.current.appendChild(label)
macroLabelRef.current = label
const chart = createChart(containerRef.current, {
width: containerRef.current.clientWidth,
// Follow the container, don't hardcode: .chart-wrap is 360px on
// desktop but 300/240px behind !important media queries. A fixed
// 360 overflows those and overflow:hidden cuts off the bottom of
// the chart — lowest candles, markers, and the whole time axis.
height: containerRef.current.clientHeight || 360,
layout: {
background: { color: colors.background },
textColor: colors.textColor,
},
grid: {
vertLines: { color: colors.gridColor },
horzLines: { color: colors.gridColor },
},
crosshair: { mode: CrosshairMode.Normal },
rightPriceScale: { borderColor: colors.borderColor },
timeScale: {
borderColor: colors.borderColor,
timeVisible: true,
rightOffset: 5,
barSpacing: 10,
},
handleScroll: true,
handleScale: true,
})
chartRef.current = chart
const series = chart.addCandlestickSeries({
upColor: '#26a69a',
downColor: '#ef5350',
borderUpColor: '#26a69a',
borderDownColor: '#ef5350',
wickUpColor: '#26a69a',
wickDownColor: '#ef5350',
})
seriesRef.current = series
// Breathing room above/below the candles. Markers render ~10px outside
// the bar's high/low; with the default tight bottom margin a crash
// candle at the bottom of the autoscaled range gets its marker dots
// clipped by the pane edge.
series.priceScale().applyOptions({
scaleMargins: { top: 0.12, bottom: 0.16 },
})
setChartReady(true)
// Re-project macro signal time → pixel X on every visible-range
// change (pan / zoom / data update / resize). Without this the line
// is set ONCE in the data effect and then stays stuck at a fixed
// pixel column while the user scrolls the chart — the bug the user
// reported as "this line is draggable".
const reposition = () => {
const c = chartRef.current as any
const vert = macroVerticalRef.current
const lbl = macroLabelRef.current
const container = containerRef.current
if (!c || !vert || !container) return
const bucket = macroBucketTimeRef.current
if (bucket == null) {
vert.style.opacity = '0'
if (lbl) lbl.style.opacity = '0'
return
}
const x = c.timeScale?.().timeToCoordinate?.(bucket)
const w = container.clientWidth
// Hide (don't clamp) when the signal time is OUTSIDE the visible
// range. Clamping to the edge would put the "MACRO BOTTOM" label
// on candles that have nothing to do with the signal — actively
// misleading.
if (typeof x !== 'number' || !Number.isFinite(x) || x < 0 || x > w) {
vert.style.opacity = '0'
if (lbl) lbl.style.opacity = '0'
return
}
vert.style.left = `${x}px`
vert.style.opacity = '1'
if (lbl) {
lbl.textContent = macroLabelTextRef.current
const clamped = Math.max(76, Math.min(w - 76, x))
lbl.style.left = `${clamped}px`
lbl.style.opacity = '1'
}
}
repositionMacroRef.current = reposition
// lightweight-charts fires this on user pan, wheel zoom, programmatic
// setVisibleRange, and on each new candle. We piggy-back on it for
// every reposition trigger we care about.
chart.timeScale().subscribeVisibleTimeRangeChange(reposition)
chart.subscribeClick((param: any) => {
if (!param.time) return
const clickTime = typeof param.time === 'number' ? param.time : 0
if (!clickTime) return
const bucketByTf: Record<string, number> = {
'5m': 300,
'15m': 900,
'1h': 3600,
'4h': 14400,
'1d': 86400,
'1w': 604800,
}
const bucketSecs = bucketByTf[timeframeRef.current.toLowerCase()] ?? 3600
const clickBucket = Math.floor(clickTime / bucketSecs) * bucketSecs
const inBucket = postsRef.current.filter((p) => {
if (!p.published_at) return false
const pt = Math.floor(new Date(p.published_at).getTime() / 1000)
return Math.floor(pt / bucketSecs) * bucketSecs === clickBucket
})
if (inBucket.length === 0) {
onSelectRef.current?.(null)
return
}
// Multiple posts in this candle bucket → show all of them in the right rail
if (inBucket.length > 1 && onSelectDayPostsRef.current) {
const sorted = [...inBucket].sort(
(a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime(),
)
onSelectDayPostsRef.current(sorted)
return
}
// Single post → show detail directly
onSelectRef.current?.(inBucket[0].id)
})
ro = new ResizeObserver(() => {
if (containerRef.current && !destroyed) {
chart.applyOptions({
width: containerRef.current.clientWidth,
height: containerRef.current.clientHeight || 360,
})
// Width change → new pixel coordinates → re-project the macro
// marker too, otherwise it'd drift relative to the candles on
// window resize / sidebar toggle.
repositionMacroRef.current?.()
}
})
ro.observe(containerRef.current)
themeObserver = new MutationObserver(() => {
const colors = getChartColors()
chart.applyOptions({
layout: {
background: { color: colors.background },
textColor: colors.textColor,
},
grid: {
vertLines: { color: colors.gridColor },
horzLines: { color: colors.gridColor },
},
rightPriceScale: { borderColor: colors.borderColor },
timeScale: { borderColor: colors.borderColor },
})
if (macroVerticalRef.current) {
macroVerticalRef.current.style.borderLeft = `2px dashed ${colors.macroAccent}`
}
if (macroLabelRef.current) {
macroLabelRef.current.style.color = colors.macroAccent
macroLabelRef.current.style.borderColor = colors.macroAccentSoft
macroLabelRef.current.style.background = colors.background
}
})
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['data-theme'],
})
})
return () => {
destroyed = true
ro?.disconnect()
themeObserver?.disconnect()
fittedRef.current = false
dataLoadedRef.current = false
setChartReady(false)
if (chartRef.current) {
// @ts-expect-error lightweight-charts type
chartRef.current.remove()
chartRef.current = null
seriesRef.current = null
}
if (macroVerticalRef.current?.parentNode) {
macroVerticalRef.current.parentNode.removeChild(macroVerticalRef.current)
}
if (macroLabelRef.current?.parentNode) {
macroLabelRef.current.parentNode.removeChild(macroLabelRef.current)
}
macroVerticalRef.current = null
macroLabelRef.current = null
macroPriceLineRef.current = null
}
}, [])
// Update candles + markers
useEffect(() => {
const series = seriesRef.current
const chart = chartRef.current
if (!series || !chart || candles.length === 0) {
dataLoadedRef.current = false
return
}
const sorted = [...candles].sort((a, b) => a.time - b.time)
// @ts-expect-error lightweight-charts type
series.setData(
sorted.map((c) => ({
time: c.time as number,
open: c.open,
high: c.high,
low: c.low,
close: c.close,
})),
)
dataLoadedRef.current = true
const minTime = sorted[0].time
const maxTime = sorted[sorted.length - 1].time
const visible = posts.filter((p) => {
if (!p.published_at) return false
const t = Math.floor(new Date(p.published_at).getTime() / 1000)
return t >= minTime && t <= maxTime
})
// Markers show actionable signals only. Hold/filtered posts vastly
// outnumber signals and their gray dots pile into unreadable clusters;
// they stay browsable in the Recent-signals list instead.
const markerPosts = visible.filter(
(p) => p.signal === 'buy' || p.signal === 'short' || p.signal === 'sell',
)
const bucketByTf: Record<string, number> = {
'5m': 300,
'15m': 900,
'1h': 3600,
'4h': 14400,
'1d': 86400,
'1w': 604800,
}
const candleSpacing = sorted.length > 1 ? sorted[1].time - sorted[0].time : 300
const bucketSecs = bucketByTf[timeframeRef.current.toLowerCase()] ?? candleSpacing
const bucketMap = new Map<number, typeof visible>()
for (const p of markerPosts) {
const pt = Math.floor(new Date(p.published_at).getTime() / 1000)
const bucket = Math.floor(pt / bucketSecs) * bucketSecs
if (!bucketMap.has(bucket)) bucketMap.set(bucket, [])
bucketMap.get(bucket)!.push(p)
}
bucketMap.forEach((ps) => ps.sort((a, b) => (b.ai_confidence ?? 0) - (a.ai_confidence ?? 0)))
const markers = Array.from(bucketMap.entries())
.sort(([a], [b]) => a - b)
.map(([bucketTime, bPosts]) => {
const isSelected = bPosts.some((p) => p.id === externalSelectedId)
const best = bPosts[0]
const count = bPosts.length
const signalColor = isSelected
? '#f59e0b'
: best.signal === 'short' || best.signal === 'sell'
? '#ef5350'
: best.signal === 'buy'
? '#26a69a'
: '#aaaaaa'
return {
time: bucketTime as number,
position: 'aboveBar' as const,
color: signalColor,
shape: 'circle' as const,
text: count > 1 ? String(count) : '',
size: isSelected ? 2 : count > 1 ? 1.5 : 1,
}
})
// @ts-expect-error lightweight-charts type
series.setMarkers(markers)
// Highlight the most recent visible Macro Vibes reversal signal on BTC.
const visibleMacro =
asset === 'BTC'
? visible
.filter(
(p) =>
((p.source || '') === 'btc_bottom_reversal' ||
(p.source || '') === 'funding_reversal') &&
(p.signal === 'buy' || p.signal === 'short'),
)
.sort((a, b) => new Date(b.published_at).getTime() - new Date(a.published_at).getTime())
: []
const macroSignal = visibleMacro[0] ?? null
const colors = getChartColors()
const priceSeries = series as any
if (macroPriceLineRef.current && priceSeries?.removePriceLine) {
try {
priceSeries.removePriceLine(macroPriceLineRef.current as any)
} catch {}
macroPriceLineRef.current = null
}
if (macroSignal && chart && macroVerticalRef.current) {
const pt = Math.floor(new Date(macroSignal.published_at).getTime() / 1000)
const bucketTime = Math.floor(pt / bucketSecs) * bucketSecs
// Only draw the horizontal reference when we have a true signal-entry
// price from the backend. Falling back to a bucket close made the line
// drift across timeframe changes and looked like a bug because it was.
const priceAtSignal =
macroSignal.price_impact?.asset === 'BTC' && macroSignal.price_impact?.price_at_post
? macroSignal.price_impact.price_at_post
: null
if (priceAtSignal != null && priceSeries?.createPriceLine) {
macroPriceLineRef.current = priceSeries.createPriceLine({
price: priceAtSignal,
color: colors.macroAccent,
lineWidth: 2,
lineStyle: 2,
axisLabelVisible: false,
title:
(macroSignal.source || '') === 'btc_bottom_reversal'
? 'Macro bottom'
: 'Funding reversal',
})
}
// Hand off positioning to the shared reposition fn — it knows how
// to re-project on every pan/zoom too, not just on data update.
// (Before this fix, the line was positioned ONCE here and never
// moved with the chart; it looked like a draggable floating element
// because the candles slid out from under it.)
macroBucketTimeRef.current = bucketTime
macroLabelTextRef.current =
(macroSignal.source || '') === 'btc_bottom_reversal' ? 'Macro bottom' : 'Funding reversal'
repositionMacroRef.current?.()
} else {
macroBucketTimeRef.current = null
repositionMacroRef.current?.()
}
if (!fittedRef.current) {
// @ts-expect-error lightweight-charts type
chart.timeScale().fitContent()
fittedRef.current = true
}
}, [candles, posts, externalSelectedId, asset, chartReady])
useEffect(() => {
fittedRef.current = false
}, [timeframe, asset])
// Live-tick the rightmost candle so the chart feels alive between REST polls.
// lightweight-charts' `series.update()` either appends a new bar (newer time)
// or in-place mutates the bar at that timestamp. We always keep `time` ==
// the last candle's bucket so the bar grows in place; high/low expand if
// the live tick exceeds them.
useEffect(() => {
const series = seriesRef.current as any
// dataLoadedRef: update() on a series that hasn't had setData() yet
// creates a chart with a single lone candle.
if (!series || !dataLoadedRef.current) return
const live = livePrices[asset]
if (live == null || !candles.length) return
const last = candles[candles.length - 1]
series.update({
time: last.time as number,
open: last.open,
high: Math.max(last.high, live),
low: Math.min(last.low, live),
close: live,
})
}, [livePrices, asset, candles])
return (
<div
ref={containerRef}
style={{
width: '100%',
height: '100%',
borderRadius: 'var(--r-sm)',
overflow: 'hidden',
cursor: 'crosshair',
position: 'relative',
}}
/>
)
}
+418
View File
@@ -0,0 +1,418 @@
'use client'
import { memo, useEffect, useState } from 'react'
import type { TrumpPost } from '@/types'
/**
* Was this post actually AI-scored, or filtered as off-topic noise before any
* AI call? Single source of truth — used both by the card (to de-emphasise
* noise) and by list views (to offer a "collapse off-topic" toggle), so the
* two can never disagree about what counts as noise.
*/
export function isAiScored(post: Pick<TrumpPost, 'ai_confidence' | 'ai_reasoning'>): boolean {
return (post.ai_confidence ?? 0) > 0 || !!post.ai_reasoning
}
function fmtPct(n: number | null | undefined) {
if (n == null || isNaN(n)) return '—' // null = window not yet closed
const s = n.toFixed(2) + '%'
return n >= 0 ? '+' + s : s
}
function fmtImpactPct(v: number | null | undefined) {
if (v == null || isNaN(v)) return '—'
const s = Math.abs(v).toFixed(2) + '%'
return v >= 0 ? '+' + s : '-' + s
}
function timeAgo(iso: string) {
const diff = Date.now() - new Date(iso).getTime()
const m = Math.floor(diff / 60000)
if (m < 1) return 'just now'
if (m < 60) return m + 'm'
const h = Math.floor(m / 60)
if (h < 24) return h + 'h'
return Math.floor(h / 24) + 'd'
}
/**
* Hydration-safe wrapper for relative time. Returns an empty placeholder on
* SSR / first client render, then the real relative time after mount. Prevents
* the SSR/CSR "5m vs 6m" mismatch error.
*/
function TimeAgo({ iso, suffix = '' }: { iso: string; suffix?: string }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return (
<span>
{timeAgo(iso)}
{suffix}
</span>
)
}
/**
* Hydration-safe absolute date formatter. Uses fixed 'en-US' locale + options
* so the server/client outputs match once mounted; renders a placeholder before
* mount to avoid timezone mismatches.
*/
function LocalDateTime({ iso, opts }: { iso: string; opts?: Intl.DateTimeFormatOptions }) {
const [mounted, setMounted] = useState(false)
useEffect(() => {
setMounted(true)
}, [])
if (!mounted) return <span suppressHydrationWarning>…</span>
return <span>{new Date(iso).toLocaleString('en-US', opts)}</span>
}
// Visual identity per signal source. The post stream now mixes Trump posts
// with scanner-emitted technical signals — operators need to tell them
// apart at a glance without reading the text.
//
// When adding a new scanner source, register it here too — otherwise it
// falls through to the generic "first letter" fallback which has no title
// or accent colour.
export const SOURCE_DISPLAY: Record<
string,
{ glyph: string; cls: string; title: string; label: string }
> = {
truth: { glyph: 'T', cls: 'truth', title: 'Trump · Truth Social', label: '@realDonaldTrump' },
breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
vcp_breakout: {
glyph: '▲',
cls: 'breakout',
title: 'VCP / breakout scanner',
label: 'Breakout scanner',
},
reversal: { glyph: '⇋', cls: 'reversal', title: 'Reversal scanner', label: 'Reversal scanner' },
btc_bottom_reversal: {
glyph: '₿',
cls: 'reversal',
title: 'BTC Macro Bottom scanner',
label: 'BTC Macro Bottom',
},
funding_reversal: {
glyph: 'ƒ',
cls: 'reversal',
title: 'BTC Funding Rate Reversal scanner',
label: 'Funding Reversal',
},
kol_divergence: {
glyph: '⚖',
cls: 'whale',
title: 'KOL Talks-vs-Trades Divergence',
label: 'KOL Divergence',
},
sma_reclaim: { glyph: '〽', cls: 'breakout', title: 'SMA reclaim scanner', label: 'SMA Reclaim' },
rsi_reversal: {
glyph: '⇋',
cls: 'reversal',
title: 'RSI reversal scanner',
label: 'RSI Reversal',
},
whale: { glyph: '🐋', cls: 'whale', title: 'On-chain whale alert', label: 'Whale alert' },
manual: { glyph: '✋', cls: 'manual', title: 'Manual entry', label: 'Manual' },
}
function SourceIcon({ source }: { source: string }) {
const d = SOURCE_DISPLAY[source.toLowerCase()]
if (d) {
return (
<div className={`src-ico ${d.cls}`} title={d.title}>
{d.glyph}
</div>
)
}
// Unknown source — show first letter so user can still tell it apart.
return (
<div className="src-ico external" title={`Source: ${source}`}>
{source.charAt(0).toUpperCase()}
</div>
)
}
function SignalPill({ signal }: { signal: string | null }) {
if (!signal || signal === 'hold') return <span className="sig hold">HOLD</span>
if (signal === 'buy') return <span className="sig buy">BUY</span>
if (signal === 'short') return <span className="sig short">SHORT</span>
if (signal === 'sell') return <span className="sig sell">SELL</span>
return <span className={`sig ${signal}`}>{signal.toUpperCase()}</span>
}
interface PostRowProps {
post: TrumpPost
selected?: boolean
onClick?: () => void
}
const PostRow = memo(function PostRow({ post, selected, onClick }: PostRowProps) {
const [expanded, setExpanded] = useState(false)
const impact = post.price_impact
function handleClick() {
if (!onClick) setExpanded((e) => !e)
onClick?.()
}
// Off-topic Trump posts (most of them) are filtered before any AI call, so
// they carry confidence 0 + no reasoning. Treat those as un-scored noise and
// de-emphasise them. Shared helper so list-level "collapse off-topic" agrees.
const aiScored = isAiScored(post)
return (
<div
className={`post-row ${selected ? 'selected' : ''} ${aiScored ? '' : 'noise'} ${post.signal === 'buy' ? 'signal-buy' : post.signal === 'short' ? 'signal-short' : ''}`}
onClick={handleClick}
>
{/* ── main row ── */}
<div className="post-row-main">
<SourceIcon source={post.source} />
<div className="post-body">
<div className="meta">
{/* Author label depends on source — non-Trump signals come from
technical scanners or external modules, not @realDonaldTrump. */}
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{SOURCE_DISPLAY[post.source?.toLowerCase?.()]?.label ?? post.source ?? 'Signal'}
</span>
<span>·</span>
<TimeAgo iso={post.published_at} suffix=" ago" />
<span>·</span>
{aiScored ? (
<span
className={`chip ${post.sentiment === 'bullish' ? 'up' : post.sentiment === 'bearish' ? 'down' : 'neutral'}`}
style={{ padding: '2px 8px', fontSize: 11 }}
>
{post.sentiment}
</span>
) : (
<span
style={{
padding: '2px 8px',
fontSize: 11,
fontWeight: 600,
borderRadius: 4,
color: 'var(--ink-4)',
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
letterSpacing: '0.02em',
}}
>
off-topic · not crypto
</span>
)}
</div>
<p
className="text"
style={{
...(expanded
? { display: 'block', overflow: 'visible', WebkitLineClamp: 'unset' }
: {}),
// Noise posts are de-emphasised: dimmer text + shorter preview so
// the reader can skip them at a glance without opening.
...(aiScored ? {} : { color: 'var(--ink-4)' }),
}}
>
{expanded
? post.text
: post.text.slice(0, aiScored ? 180 : 90) +
(post.text.length > (aiScored ? 180 : 90) ? '…' : '')}
</p>
</div>
{/* Aside (signal pill / target / impact / AI%) only for scored posts.
Noise posts render as a compact two-column row (no aside) — the
'off-topic · not crypto' tag in the meta line is enough. */}
{aiScored && (
<div className="post-aside">
<SignalPill signal={post.signal} />
{/* Target asset chip for actionable signals */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<span
style={{
fontSize: 10,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '2px 6px',
borderRadius: 4,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
letterSpacing: '0.04em',
}}
>
{post.target_asset}
{post.expected_move_pct ? ` +${post.expected_move_pct}%` : ''}
</span>
)}
<div className="impact-mini">
{impact ? (
<>
<span className="tf">1h move</span>
<span
className={`delta ${impact.m1h == null ? '' : impact.m1h >= 0 ? 'up' : 'down'}`}
>
{impact.m1h == null ? '…' : fmtPct(impact.m1h)}
</span>
</>
) : (
<span className="tf">no data</span>
)}
</div>
<div className="row gap-s" style={{ fontSize: 11, color: 'var(--ink-3)' }}>
<span>AI</span>
<span className="mono" style={{ color: 'var(--ink-2)', fontWeight: 500 }}>
{post.ai_confidence}%
</span>
</div>
</div>
)}
</div>
{/* ── expanded detail ── */}
{expanded && (
<div className="post-row-detail" onClick={(e) => e.stopPropagation()}>
{/* AI confidence bar — only when the post was actually AI-scored.
Off-topic/noise posts (relevant=false, conf 0, no reasoning) show
a neutral note instead of a misleading empty 0% bar. */}
{aiScored ? (
<div>
<div className="ai-metric-head">
<span>AI confidence</span>
<strong>{post.ai_confidence}%</strong>
</div>
<div className="confidence-bar">
<div style={{ width: post.ai_confidence + '%' }} />
</div>
</div>
) : (
<div style={{ fontSize: 12, color: 'var(--ink-3)', padding: '4px 0' }}>
Not crypto-relevant — skipped AI scoring.
</div>
)}
{/* Trade routing — target asset + expected move */}
{post.target_asset && (post.signal === 'buy' || post.signal === 'short') && (
<div style={{ display: 'flex', gap: 8, alignItems: 'center', marginBottom: 4 }}>
<span className="tiny">Trade</span>
<span
style={{
fontSize: 12,
fontWeight: 700,
fontFamily: 'var(--mono)',
padding: '3px 8px',
borderRadius: 5,
background:
post.signal === 'buy' ? 'rgba(34,197,94,0.12)' : 'rgba(239,68,68,0.12)',
color: post.signal === 'buy' ? '#22c55e' : '#ef4444',
}}
>
{post.signal === 'buy'
? `↑ LONG ${post.target_asset}`
: `↓ SHORT ${post.target_asset}`}
</span>
{post.expected_move_pct != null && (
<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>
{`model projection ~${post.expected_move_pct}% · 1h`}
</span>
)}
{post.category && (
<span
style={{
fontSize: 10,
color: 'var(--ink-4)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
{post.category.replace(/_/g, ' ')}
</span>
)}
</div>
)}
{/* AI reasoning */}
{post.ai_reasoning && (
<div>
<div className="ai-reasoning-label">
{post.signal === 'buy' || post.signal === 'short'
? 'Why this signal fired'
: 'Why this was filtered out'}
</div>
<div className="ai-reasoning-card">{post.ai_reasoning}</div>
</div>
)}
{/* Price impact — peak move in signal direction per window */}
{impact && (
<div>
<div
className="tiny"
style={{ marginBottom: 8 }}
>{`Price moved · ${impact.asset} · after signal`}</div>
<div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8 }}>
{(['m5', 'm15', 'm1h'] as const).map((key) => {
const label = key === 'm5' ? '5m' : key === 'm15' ? '15m' : '1h'
const v = impact[key] // null = window still open
const correct =
impact[`correct_${key}` as 'correct_m5' | 'correct_m15' | 'correct_m1h']
const pending = v == null
return (
<div
key={key}
style={{
padding: 10,
background: 'var(--bg-sunk)',
borderRadius: 'var(--r-sm)',
border: `1px solid ${pending ? 'var(--amber)' : 'var(--line)'}`,
textAlign: 'center',
opacity: pending ? 0.75 : 1,
}}
>
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginBottom: 4 }}>
{label}
</div>
<div
className={pending ? '' : `delta ${v >= 0 ? 'up' : 'down'}`}
style={{
fontSize: 14,
fontWeight: 600,
color: pending ? 'var(--ink-3)' : undefined,
}}
>
{pending ? '…' : fmtImpactPct(v)}
</div>
{!pending && correct != null && (
<div
style={{
fontSize: 10,
marginTop: 4,
color: correct ? 'var(--up)' : 'var(--down)',
}}
>
{correct ? '✓' : '✗'}
</div>
)}
{pending && (
<div style={{ fontSize: 9, marginTop: 4, color: 'var(--amber)' }}>live</div>
)}
</div>
)
})}
</div>
</div>
)}
</div>
)}
</div>
)
})
export default PostRow
export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime }
@@ -0,0 +1,299 @@
'use client'
import { useState, useEffect } from 'react'
import { useWsSubscribe } from '@/lib/wsContext'
const API_BASE = '/api/proxy/api'
interface SignalAlert {
type: 'funding_signal'
symbol: string
time: string
close: number
tbr: number
vol_mult: number
bb_pct: number
bb_upper: number
btc_trend: string
enabled: boolean
}
function symbolLabel(s: string) {
return s.replace('USDT', '')
}
function timeAgo(iso: string) {
const diff = (Date.now() - new Date(iso).getTime()) / 1000
if (diff < 60) return `${Math.round(diff)}s ago`
if (diff < 3600) return `${Math.round(diff / 60)}m ago`
return `${Math.round(diff / 3600)}h ago`
}
// ── Main component ────────────────────────────────────────────────────────────
// Display-only: toggle is operator-only (requires X-Ingest-Key) so the
// on/off switch is intentionally absent from the user-facing UI.
export default function SignalMonitor() {
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const [enabled, setEnabledState] = useState(false)
const [signals, setSignals] = useState<SignalAlert[]>([])
const [btcTrend, setBtcTrend] = useState<string | null>(null)
const [lastScan, setLastScan] = useState<Date | null>(null)
// ── Load initial state ───────────────────────────────────────────────────
useEffect(() => {
fetch(`${API_BASE}/signal/status`)
.then((r) => {
if (!r.ok) throw new Error()
return r.json()
})
.then((d) => {
setEnabledState(d.enabled)
})
.catch(() => {})
fetch(`${API_BASE}/signal/history?limit=20`)
.then((r) => r.json())
.then((list: SignalAlert[]) => {
if (!Array.isArray(list)) return
setSignals(list)
if (list.length > 0) {
setBtcTrend(list[0].btc_trend)
setLastScan(new Date(list[0].time))
}
})
.catch(() => {})
}, [])
// ── WebSocket listener (shared singleton connection via WsProvider) ─────────
useWsSubscribe('funding_signal', (msg) => {
const alert = msg as SignalAlert
setBtcTrend(alert.btc_trend)
setLastScan(new Date(alert.time))
setSignals((prev) => [alert, ...prev].slice(0, 50))
})
// ── Render ───────────────────────────────────────────────────────────────
const btcUp = btcTrend?.includes('↑')
return (
<div className="card" style={{ padding: 20, marginTop: 12 }}>
{/* Header */}
<div
style={{
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'space-between',
marginBottom: 14,
}}
>
<div>
<div
style={{
fontSize: 12,
fontWeight: 700,
letterSpacing: '0.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
marginBottom: 3,
}}
>
{isZh ? '突破监控' : 'Breakout Monitor'}
</div>
<div style={{ fontSize: 11, color: 'var(--ink-3)' }}>
{isZh ? 'ETH · LINK · 5 分钟扫描' : 'ETH · LINK · 5m scan'}
</div>
</div>
{/* Enabled status dot — display-only; toggle is operator-only (X-Ingest-Key) */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
fontSize: 11,
color: enabled ? '#22c55e' : 'var(--ink-3)',
}}
>
<div
style={{
width: 7,
height: 7,
borderRadius: '50%',
background: enabled ? '#22c55e' : 'var(--ink-4)',
boxShadow: enabled ? '0 0 0 2px rgba(34,197,94,0.25)' : 'none',
}}
/>
{enabled ? (isZh ? '监控中' : 'Active') : isZh ? '已暂停' : 'Paused'}
</div>
</div>
{/* Status row: BTC trend + last scan */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
fontSize: 11,
color: 'var(--ink-3)',
padding: '6px 10px',
borderRadius: 8,
background: 'rgba(255,255,255,0.04)',
marginBottom: 14,
}}
>
<span>
BTC &nbsp;
{btcTrend ? (
<strong style={{ color: btcUp ? '#22c55e' : '#ef4444' }}>{btcTrend}</strong>
) : (
<span style={{ opacity: 0.5 }}>—</span>
)}
</span>
<span>
{lastScan
? isZh
? `最近信号 ${timeAgo(lastScan.toISOString())}`
: `Last signal ${timeAgo(lastScan.toISOString())}`
: enabled
? isZh
? '扫描中…'
: 'Scanning…'
: isZh
? '已暂停'
: 'Paused'}
</span>
</div>
{/* Signal list */}
{signals.length === 0 ? (
<div
style={{
fontSize: 13,
color: 'var(--ink-3)',
textAlign: 'center',
padding: '20px 0',
lineHeight: 1.5,
}}
>
{enabled
? isZh
? '· 正在等待信号…'
: '· Watching for signals…'
: isZh
? '· 暂无历史信号'
: '· No signals yet'}
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{signals.map((s) => (
<div
key={`${s.symbol}-${s.time}`}
style={{
padding: '11px 13px',
borderRadius: 10,
background: 'rgba(255,255,255,0.04)',
borderLeft: `3px solid ${s.enabled ? '#22c55e' : 'rgba(255,255,255,0.15)'}`,
}}
>
{/* Top row */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 8,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<span
style={{
fontWeight: 700,
fontSize: 14,
fontFamily: 'var(--mono)',
color: 'var(--ink)',
}}
>
{symbolLabel(s.symbol)}
</span>
{!s.enabled && (
<span
style={{
fontSize: 9,
padding: '2px 6px',
borderRadius: 4,
background: 'rgba(255,255,255,0.08)',
color: 'var(--ink-3)',
textTransform: 'uppercase',
letterSpacing: '0.05em',
}}
>
silent
</span>
)}
</div>
<span style={{ fontSize: 11, color: 'var(--ink-3)' }}>{timeAgo(s.time)}</span>
</div>
{/* Metrics grid */}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
{[
{
label: isZh ? '价格' : 'Price',
value: `$${s.close.toLocaleString(undefined, { maximumFractionDigits: 2 })}`,
color: 'var(--ink)',
},
{
label: isZh ? '主动买入' : 'Taker Buy',
value: `${(s.tbr * 100).toFixed(1)}%`,
color: '#22c55e',
},
{
label: isZh ? '成交量倍数' : 'Vol ×',
value: `${s.vol_mult}×`,
color: '#22c55e',
},
].map((m) => (
<div
key={m.label}
style={{
background: 'rgba(255,255,255,0.03)',
borderRadius: 6,
padding: '5px 8px',
}}
>
<div
style={{
fontSize: 9,
color: 'var(--ink-3)',
marginBottom: 2,
textTransform: 'uppercase',
letterSpacing: '0.04em',
}}
>
{m.label}
</div>
<div
style={{
fontSize: 13,
fontFamily: 'var(--mono)',
fontWeight: 600,
color: m.color,
}}
>
{m.value}
</div>
</div>
))}
</div>
{/* Footer */}
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 8 }}>
{isZh ? `BB squeeze 处于第 ${s.bb_pct} 分位` : `BB squeeze ${s.bb_pct}th pct`}{' '}
&nbsp;·&nbsp; {s.btc_trend}
</div>
</div>
))}
</div>
)}
</div>
)
}
@@ -0,0 +1,76 @@
'use client'
import { useMemo } from 'react'
import Link from 'next/link'
import { usePathname, useSearchParams } from '@/lib/navigation'
import { defaultLocale, locales, type Locale } from '@/i18n'
function replaceLocale(pathname: string, nextLocale: Locale) {
const segments = pathname.split('/').filter(Boolean)
const current = segments[0]
if (locales.includes(current as Locale)) {
segments[0] = nextLocale
} else {
segments.unshift(nextLocale)
}
return '/' + segments.join('/')
}
export default function LanguageSwitch() {
const pathname = usePathname()
const searchParams = useSearchParams()
const options: Array<{ locale: Locale; label: string }> = [{ locale: 'en', label: 'EN' }]
const activeLocale = useMemo<Locale>(() => {
const seg = pathname.split('/').filter(Boolean)[0]
return locales.includes(seg as Locale) ? (seg as Locale) : defaultLocale
}, [pathname])
return (
<div
aria-label="Language switch"
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 4,
padding: 4,
borderRadius: 999,
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
flexShrink: 0,
}}
>
{options.map(({ locale, label }) => {
const active = activeLocale === locale
const nextPath = replaceLocale(pathname || `/${defaultLocale}`, locale)
const qs = searchParams.toString()
const href = qs ? `${nextPath}?${qs}` : nextPath
return (
<Link
key={locale}
href={href}
aria-pressed={active}
style={{
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
minWidth: 40,
padding: '6px 10px',
borderRadius: 999,
border: 'none',
background: active ? 'var(--ink)' : 'transparent',
color: active ? 'var(--bg)' : 'var(--ink-3)',
fontSize: 12,
fontWeight: 700,
lineHeight: 1,
cursor: 'pointer',
textDecoration: 'none',
}}
>
{label}
</Link>
)
})}
</div>
)
}
+256
View File
@@ -0,0 +1,256 @@
'use client'
import { useState, useEffect } from 'react'
import Link from 'next/link'
import { usePathname } from '@/lib/navigation'
import { useAccount, useConnect, useDisconnect } from 'wagmi'
import { useTranslations } from 'next-intl'
import { getFirstReadyConnector, walletConnectErrorLabel } from '@/lib/walletConnect'
import { needsMobileWallet } from '@/lib/mobileWallet'
import MobileWalletSheet from '@/components/wallet/MobileWalletSheet'
// i18n shelved — LanguageSwitch hidden but kept on disk for future revival.
// import LanguageSwitch from './LanguageSwitch'
function BrandMark() {
return <span className="brand-mark">α</span>
}
function ThemeToggle() {
const [theme, setTheme] = useState<'light' | 'dark'>('light')
useEffect(() => {
const stored = localStorage.getItem('theme') as 'light' | 'dark' | null
const t = stored || 'light'
setTheme(t)
document.documentElement.dataset.theme = t
}, [])
function toggle() {
const next = theme === 'dark' ? 'light' : 'dark'
setTheme(next)
localStorage.setItem('theme', next)
document.documentElement.dataset.theme = next
}
return (
<button
className="icon-btn theme-toggle"
onClick={toggle}
aria-label={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
title={theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'}
>
{theme === 'dark' ? (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="2" />
<path
d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
/>
</svg>
) : (
<svg width="16" height="16" viewBox="0 0 24 24" fill="none">
<path
d="M21 12.8A9 9 0 1 1 11.2 3a7 7 0 0 0 9.8 9.8z"
stroke="currentColor"
strokeWidth="2"
strokeLinejoin="round"
/>
</svg>
)}
</button>
)
}
export default function Navbar() {
const t = useTranslations('nav')
const pathname = usePathname()
const { address, isConnected } = useAccount()
const { connectAsync, connectors } = useConnect()
const { disconnect } = useDisconnect()
const [mounted, setMounted] = useState(false)
const [walletMenuOpen, setWalletMenuOpen] = useState(false)
const [copied, setCopied] = useState(false)
const [connectError, setConnectError] = useState('')
const [mobileSheetOpen, setMobileSheetOpen] = useState(false)
async function copyAddress(addr: string) {
let ok = false
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(addr)
ok = true
} else {
// Fallback for non-secure contexts where the Clipboard API is absent.
const ta = document.createElement('textarea')
ta.value = addr
ta.style.position = 'fixed'
ta.style.opacity = '0'
document.body.appendChild(ta)
ta.select()
ok = document.execCommand('copy')
document.body.removeChild(ta)
}
} catch {
ok = false
}
setCopied(ok)
setTimeout(() => setCopied(false), 1500)
}
useEffect(() => {
setMounted(true)
}, [])
useEffect(() => {
setWalletMenuOpen(false)
}, [pathname, address])
useEffect(() => {
if (isConnected) setConnectError('')
}, [isConnected])
const locale = pathname.split('/')[1] || 'en'
const path = '/' + pathname.split('/').slice(2).join('/')
async function handleConnectWallet() {
setConnectError('')
// On mobile without an injected provider, show the wallet deep-link sheet
// instead of throwing "No wallet found". This lets users open the dApp
// inside MetaMask / Trust / Coinbase without a confusing error.
if (needsMobileWallet()) {
setMobileSheetOpen(true)
return
}
try {
const connector = await getFirstReadyConnector(connectors)
if (!connector) {
// Desktop with no extension — give a helpful hint instead of raw error.
setConnectError('No wallet extension found. Install MetaMask or another browser wallet.')
return
}
await connectAsync({ connector })
} catch (err: unknown) {
setConnectError(walletConnectErrorLabel(err))
}
}
// Two independent trading systems get their own top-level tabs — no
// intermediate "Signals" hub. Trump = event scalp; BTC = reversal.
const tabs = [
{ key: '/', label: t('tabs.overview') },
{ key: '/trump', label: t('tabs.trump') },
{ key: '/macro', label: t('tabs.vibes') },
{ key: '/kol', label: t('tabs.kol') },
{ key: '/trades', label: t('tabs.trades') },
{ key: '/analytics', label: t('tabs.analytics') },
{ key: '/settings', label: t('tabs.settings') },
]
function isActive(key: string) {
if (key === '/') return path === '/' || path === '//'
// /posts (legacy hub) still resolves but isn't a tab; treat it + /archive
// as part of the Trump section so a tab stays highlighted there.
if (key === '/trump')
return path.startsWith('/trump') || path.startsWith('/posts') || path.startsWith('/archive')
return path.startsWith(key)
}
const shortAddr = address ? `${address.slice(0, 6)}…${address.slice(-4)}` : null
return (
<>
<MobileWalletSheet open={mobileSheetOpen} onClose={() => setMobileSheetOpen(false)} />
<nav className="nav">
<Link
href={`/${locale}`}
className="brand"
style={{ textDecoration: 'none', color: 'inherit' }}
>
<BrandMark />
<span>{t('brand')}</span>
</Link>
<div className="nav-tabs">
{tabs.map((tab) => (
<Link
key={tab.key}
href={`/${locale}${tab.key === '/' ? '' : tab.key}`}
className={`nav-tab ${isActive(tab.key) ? 'active' : ''}`}
prefetch
>
{tab.label}
</Link>
))}
</div>
<div className="nav-spacer" />
<div className="nav-right">
{/* <LanguageSwitch /> — shelved until i18n coverage is complete */}
<ThemeToggle />
<div className="wallet-anchor">
{!mounted ? (
<button className="connect-btn lg" suppressHydrationWarning>
{t('actions.connectWallet')}
</button>
) : isConnected && shortAddr ? (
<div className="wallet-menu-wrap" style={{ position: 'relative' }}>
<button
className="wallet-chip"
onClick={() => setWalletMenuOpen((open) => !open)}
onBlur={(e) => {
if (!e.currentTarget.parentElement?.contains(e.relatedTarget as Node | null)) {
setWalletMenuOpen(false)
}
}}
aria-expanded={walletMenuOpen}
aria-haspopup="menu"
>
<span className="ava" />
<span className="mono">{shortAddr}</span>
</button>
<div className={`wallet-menu ${walletMenuOpen ? 'open' : ''}`} role="menu">
<button
role="menuitem"
onMouseDown={(e) => {
e.preventDefault()
if (address) copyAddress(address)
}}
>
{copied ? t('actions.copied') : t('actions.copyAddress')}
</button>
<button
role="menuitem"
className="danger"
onMouseDown={(e) => {
e.preventDefault()
disconnect()
setWalletMenuOpen(false)
}}
>
{t('actions.disconnect')}
</button>
</div>
</div>
) : (
<button
className="connect-btn lg"
onClick={() => {
void handleConnectWallet()
}}
>
{t('actions.connectWallet')}
</button>
)}
{!isConnected && connectError ? (
<p className="wallet-connect-error" role="alert">
{connectError}
</p>
) : null}
</div>
</div>
</nav>
</>
)
}
+89
View File
@@ -0,0 +1,89 @@
'use client'
/**
* Ticker — horizontal scrolling price tape under the navbar, the way a crypto
* terminal shows a running market strip. Driven by the shared WebSocket price
* feed (no new socket). Each asset cell flashes green/red on a price change and
* shows the live last price.
*
* Behaviour notes:
* - The strip is duplicated once and translated -50% in a CSS marquee so the
* loop is seamless (`ticker-marquee` keyframe in globals.css).
* - prefers-reduced-motion disables the scroll (CSS), so the tape becomes a
* static, readable row instead of moving.
* - The animation is paused on hover so a user can read a specific price.
* - Assets with no tick yet render "—" rather than a stale zero.
*/
import { useRef, useState } from 'react'
import { useWsSubscribe } from '@/lib/wsContext'
// Assets the backend streams (see binance ASSET_MAP + hl_price_feed). Order is
// the display order in the tape.
const ASSETS = ['BTC', 'ETH', 'SOL', 'BNB', 'DOGE', 'LINK', 'AAVE', 'TRUMP', 'HYPE'] as const
interface Cell {
price: number | null
dir: 'up' | 'down' | null
}
function fmtPrice(p: number): string {
if (p >= 1000) return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 0 })
if (p >= 1) return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 2 })
return '$' + p.toLocaleString('en-US', { maximumFractionDigits: 4 })
}
export default function Ticker() {
const [cells, setCells] = useState<Record<string, Cell>>({})
// Per-asset flash-clear timers so a fast stream doesn't leak setTimeouts.
const timers = useRef<Record<string, ReturnType<typeof setTimeout>>>({})
useWsSubscribe('price', (msg) => {
const m = msg as { asset?: string; price?: number }
if (!m.asset || typeof m.price !== 'number') return
const asset = m.asset.toUpperCase()
if (!ASSETS.includes(asset as (typeof ASSETS)[number])) return
setCells((prev) => {
const old = prev[asset]
const dir: Cell['dir'] =
old?.price != null && m.price !== old.price
? m.price! > old.price
? 'up'
: 'down'
: (old?.dir ?? null)
return { ...prev, [asset]: { price: m.price!, dir } }
})
// Clear the flash after 600ms.
clearTimeout(timers.current[asset])
timers.current[asset] = setTimeout(() => {
setCells((prev) => (prev[asset] ? { ...prev, [asset]: { ...prev[asset], dir: null } } : prev))
}, 600)
})
const strip = ASSETS.map((a) => {
const c = cells[a]
return (
<span key={a} className={`ticker-cell ${c?.dir ? `tick-flash-${c.dir}` : ''}`}>
<span className="ticker-sym">{a}</span>
<span className="ticker-px">{c?.price != null ? fmtPrice(c.price) : '—'}</span>
<span className={`ticker-arrow ${c?.dir ?? ''}`} aria-hidden>
{c?.dir === 'up' ? '▲' : c?.dir === 'down' ? '▼' : ''}
</span>
</span>
)
})
return (
<div className="ticker" role="region" aria-label="Live market prices">
<div className="ticker-track">
{strip}
{/* duplicate for seamless loop */}
<span aria-hidden style={{ display: 'contents' }}>
{strip}
</span>
</div>
</div>
)
}
@@ -0,0 +1,795 @@
'use client'
/**
* Open positions panel — what's currently on the book.
*
* The single most-asked question on any trading dashboard: "what do I hold
* right now?" Polls /api/positions/open + /api/positions/today every 15s.
* Compact enough to embed at the top of Dashboard AND Trades.
*
* Empty state is intentional: explicitly says "0 open" rather than hiding,
* so the user can confirm the bot isn't doing anything weird off-screen.
*/
import { useEffect, useState } from 'react'
import Link from 'next/link'
import { useLocale } from 'next-intl'
import { useAccount, useSignMessage } from 'wagmi'
import {
getOpenPositions,
getTodayStats,
manualCloseTrade,
setTradeGrow,
type OpenPosition,
type TodayStats,
} from '@/lib/api'
import {
getCachedViewEnvelope,
getOrCreateViewEnvelope,
signRequest,
type SignedEnvelope,
} from '@/lib/signedRequest'
import { isUserRejection, walletErrorLabel } from '@/lib/walletError'
const POLL_MS = 15_000
function fmtMoney(n: number | null | undefined, opts: { sign?: boolean } = {}) {
if (n == null || isNaN(n)) return '—'
const sign = opts.sign === true
const abs = Math.abs(n).toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
})
if (n < 0) return '-$' + abs
if (sign && n > 0) return '+$' + abs
return '$' + abs
}
function fmtPct(n: number | null | undefined) {
if (n == null || isNaN(n)) return '—'
return (n >= 0 ? '+' : '') + n.toFixed(2) + '%'
}
function fmtHold(min: number) {
if (min < 60) return `${min}m`
const h = Math.floor(min / 60),
m = min % 60
if (h < 24) return `${h}h ${m}m`
return `${Math.floor(h / 24)}d ${h % 24}h`
}
function PositionRow({
p,
onClose,
onToggleGrow,
growBusy,
isZh,
}: {
p: OpenPosition
onClose: (p: OpenPosition) => void
onToggleGrow: (p: OpenPosition) => void
growBusy: boolean
isZh: boolean
}) {
const pnlTone = (p.unrealized_pct ?? 0) > 0 ? 'up' : (p.unrealized_pct ?? 0) < 0 ? 'down' : 'idle'
const pnlColor =
pnlTone === 'up' ? 'var(--up)' : pnlTone === 'down' ? 'var(--down)' : 'var(--ink-3)'
return (
<div
style={{
display: 'grid',
gridTemplateColumns: '70px 60px 1fr 1fr 80px 1fr 90px',
gap: 12,
alignItems: 'center',
padding: '10px 14px',
borderTop: '1px solid var(--line)',
fontSize: 13,
}}
>
{/* Asset + paper tag */}
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span className={`asset-dot ${p.asset.toLowerCase()}`} />
<span style={{ fontWeight: 600 }}>{p.asset}</span>
{p.is_paper && (
<span
style={{
fontSize: 9,
padding: '1px 5px',
borderRadius: 3,
background: 'rgba(245,158,11,0.15)',
color: '#f59e0b',
}}
>
P
</span>
)}
</div>
{/* Side */}
<span className={`side-pill ${p.side}`}>{p.side === 'long' ? '↗ LONG' : '↘ SHORT'}</span>
{/* Entry → Current */}
<div className="mono" style={{ fontSize: 12 }}>
<div style={{ color: 'var(--ink-3)', fontSize: 10 }}>entry / current price</div>
<div>
{fmtMoney(p.entry_price)}
<span style={{ color: 'var(--ink-4)' }}> → </span>
{p.current_price != null ? (
fmtMoney(p.current_price)
) : (
<span style={{ color: 'var(--ink-4)' }}>n/a</span>
)}
</div>
</div>
{/* Size + leverage (size = OPEN notional after de-risk) */}
<div className="mono" style={{ fontSize: 12 }}>
<div style={{ color: 'var(--ink-3)', fontSize: 10 }}>open size · lev</div>
<div>
{p.size_usd != null ? '$' + p.size_usd.toFixed(0) : '—'}
{p.leverage != null && <span style={{ color: 'var(--ink-4)' }}> · {p.leverage}×</span>}
</div>
{((p.derisk_steps ?? 0) > 0 || (p.addon_steps ?? 0) > 0) && (
<div style={{ fontSize: 9, marginTop: 2 }}>
{(p.addon_steps ?? 0) > 0 && (
<span style={{ color: 'var(--up)' }}>{`↑ scaled in ×${p.addon_steps} `}</span>
)}
{(p.derisk_steps ?? 0) > 0 && (
<span style={{ color: 'var(--down)' }}>{`↓ trimmed ×${p.derisk_steps}`}</span>
)}
</div>
)}
{/* Per-trade Grow (pyramiding) switch */}
<button
onClick={() => onToggleGrow(p)}
disabled={growBusy}
title={
p.grow_mode
? isZh
? '加仓已开启:趋势确认后自动追加仓位。点击关闭。'
: 'Scale-in ON — bot adds to this position when trend is confirmed. Click to turn off.'
: isZh
? '加仓已关闭:仅持有并做保护性减仓。'
: 'Scale-in OFF — hold + protective trim only. Click to allow adding.'
}
style={{
marginTop: 4,
fontSize: 9,
fontWeight: 700,
padding: '2px 7px',
borderRadius: 999,
cursor: growBusy ? 'wait' : 'pointer',
border: '1px solid var(--line)',
background: p.grow_mode ? 'var(--up, #16a34a)' : 'transparent',
color: p.grow_mode ? '#fff' : 'var(--ink-3)',
}}
>
{p.grow_mode ? '↑ Scale-in ON' : 'Scale-in OFF'}
</button>
</div>
{/* Hold time */}
<div className="mono" style={{ fontSize: 12, color: 'var(--ink-2)' }}>
{fmtHold(p.hold_minutes)}
</div>
{/* Unrealized PnL */}
<div style={{ textAlign: 'right' }}>
<div
style={{
fontSize: 14,
fontWeight: 600,
color: pnlColor,
fontVariantNumeric: 'tabular-nums',
}}
>
{fmtMoney(p.unrealized_usd, { sign: true })}
</div>
<div style={{ fontSize: 11, color: pnlColor, opacity: 0.85 }}>
{fmtPct(p.unrealized_pct)}
</div>
{p.realized_usd != null && p.realized_usd !== 0 && (
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
banked {fmtMoney(p.realized_usd, { sign: true })} from partial close
</div>
)}
</div>
{/* Emergency close — bypasses TP/SL/schedule. Always available. */}
<button
onClick={() => onClose(p)}
className="btn ghost"
style={{
padding: '6px 10px',
fontSize: 11,
fontWeight: 600,
color: 'var(--down)',
border: '1px solid color-mix(in oklab, var(--down) 25%, var(--line))',
}}
title={isZh ? '立即平掉这个仓位' : 'Close this position immediately'}
>
{isZh ? '立即平仓' : 'Close now'}
</button>
</div>
)
}
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<OpenPosition[] | null>(null)
const [today, setToday] = useState<TodayStats | null>(null)
const [err, setErr] = useState<string | null>(null)
const [needsUnlock, setNeedsUnlock] = useState(false)
const [unlocking, setUnlocking] = useState(false)
// Close-confirmation modal state
const [closing, setClosing] = useState<OpenPosition | null>(null)
const [closeState, setCloseState] = useState<'idle' | 'signing' | 'closing' | 'err'>('idle')
useEffect(() => {
setMounted(true)
}, [])
const [closeErr, setCloseErr] = useState('')
const [growId, setGrowId] = useState<number | null>(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 (
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div
style={{
fontSize: 11,
color: 'var(--ink-3)',
letterSpacing: '0.06em',
textTransform: 'uppercase',
fontWeight: 600,
marginBottom: 6,
}}
>
Open positions
</div>
<div style={{ fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>
Sign in to see open positions
</div>
<div style={{ fontSize: 12, color: 'var(--ink-3)', marginTop: 4, lineHeight: 1.6 }}>
Sign once on this device to unlock your positions (valid for a few minutes, no
transaction, no gas).
</div>
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
marginTop: 10,
flexWrap: 'wrap',
}}
>
<button
className="btn amber"
style={{ fontSize: 13, padding: '8px 16px' }}
disabled={unlocking}
onClick={handleUnlock}
>
{unlocking ? 'Waiting for signature…' : 'Unlock positions'}
</button>
<Link
href={`/${locale}/settings`}
style={{ fontSize: 12, color: 'var(--ink-3)', textDecoration: 'none' }}
>
or go to Settings →
</Link>
</div>
{err && <div style={{ fontSize: 11, color: 'var(--down)', marginTop: 8 }}>⚠️ {err}</div>}
</div>
)
}
// 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 (
<div
className="card"
style={{ padding: '12px 16px', marginBottom: 16, fontSize: 12, color: 'var(--down)' }}
>
⚠️ Could not load positions — {err}
</div>
)
}
return null
}
const totalUnrealized = (positions ?? []).reduce((s, p) => s + (p.unrealized_usd ?? 0), 0)
const pnlTone = today
? today.realized_pnl_usd > 0
? 'up'
: today.realized_pnl_usd < 0
? 'down'
: 'idle'
: 'idle'
const todayColor =
pnlTone === 'up' ? 'var(--up)' : pnlTone === 'down' ? 'var(--down)' : 'var(--ink-2)'
return (
<div className="card" style={{ padding: 0, marginBottom: 16, overflow: 'hidden' }}>
{/* Header strip — at-a-glance status */}
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '14px 18px',
flexWrap: 'wrap',
gap: 12,
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 18, flexWrap: 'wrap' }}>
<div>
<div
style={{
fontSize: 10,
color: 'var(--ink-3)',
letterSpacing: '0.06em',
textTransform: 'uppercase',
fontWeight: 600,
marginBottom: 2,
}}
>
Open
</div>
<div style={{ fontSize: 18, fontWeight: 700 }}>
{today?.open_count ?? 0}
<span style={{ fontSize: 12, color: 'var(--ink-3)', marginLeft: 6, fontWeight: 400 }}>
{`position${(today?.open_count ?? 0) === 1 ? '' : 's'}`}
</span>
</div>
</div>
<div style={{ width: 1, height: 32, background: 'var(--line)' }} />
<div>
<div
style={{
fontSize: 10,
color: 'var(--ink-3)',
letterSpacing: '0.06em',
textTransform: 'uppercase',
fontWeight: 600,
marginBottom: 2,
}}
>
Unrealized
</div>
<div
style={{
fontSize: 18,
fontWeight: 700,
color:
totalUnrealized > 0
? 'var(--up)'
: totalUnrealized < 0
? 'var(--down)'
: 'var(--ink-2)',
fontVariantNumeric: 'tabular-nums',
}}
>
{fmtMoney(totalUnrealized, { sign: true })}
</div>
</div>
<div style={{ width: 1, height: 32, background: 'var(--line)' }} />
<div>
<div
style={{
fontSize: 10,
color: 'var(--ink-3)',
letterSpacing: '0.06em',
textTransform: 'uppercase',
fontWeight: 600,
marginBottom: 2,
}}
>
Today&apos;s realized
</div>
<div
style={{
fontSize: 18,
fontWeight: 700,
color: todayColor,
fontVariantNumeric: 'tabular-nums',
}}
>
{fmtMoney(today?.realized_pnl_usd ?? 0, { sign: true })}
</div>
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
{today ? `${today.trades_closed} closed · ${today.wins}W · ${today.losses}L` : '—'}
</div>
{today != null && (today.open_realized_usd ?? 0) !== 0 && (
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 1 }}>
{`incl. ${fmtMoney(today.open_realized_usd, { sign: true })} banked from partial closes`}
</div>
)}
</div>
</div>
{err && <span style={{ fontSize: 11, color: 'var(--down)' }}>● {err}</span>}
{growErr && !err && <span style={{ fontSize: 11, color: 'var(--down)' }}>● {growErr}</span>}
</div>
{/* Position list (or empty state) */}
{positions && positions.length > 0 ? (
<div>
<div
style={{
display: 'grid',
gridTemplateColumns: '70px 60px 1fr 1fr 80px 1fr 90px',
gap: 12,
padding: '8px 14px',
background: 'var(--bg-sunk)',
fontSize: 10,
fontWeight: 600,
letterSpacing: '0.05em',
color: 'var(--ink-3)',
textTransform: 'uppercase',
}}
>
<span>Asset</span>
<span>Side</span>
<span>Prices</span>
<span>Size</span>
<span>Hold</span>
<span style={{ textAlign: 'right' }}>Unrealized</span>
<span style={{ textAlign: 'right' }}>Action</span>
</div>
{positions.map((p) => (
<PositionRow
key={p.trade_id}
p={p}
onClose={setClosing}
onToggleGrow={toggleGrow}
growBusy={growId === p.trade_id}
isZh={isZh}
/>
))}
</div>
) : (
<div
style={{
borderTop: '1px solid var(--line)',
padding: '20px 18px',
fontSize: 13,
color: 'var(--ink-3)',
textAlign: 'center',
}}
>
No open positions. When the bot opens a trade, it will show up here.
</div>
)}
{/* ── Confirmation modal (P0.1 safety valve) ───────────────────
Two-step UX so the wallet popup isn't surprising. The user
presses "Close now", reads the impact summary, then confirms. */}
{closing && (
<div
onClick={() => {
// Backdrop dismisses in both idle (never started) and err
// (failed, user wants out) states. NOT during signing/closing —
// the wallet popup or in-flight POST shouldn't be orphaned.
if (closeState === 'idle' || closeState === 'err') {
setClosing(null)
setCloseState('idle')
setCloseErr('')
}
}}
style={{
position: 'fixed',
inset: 0,
zIndex: 1000,
background: 'rgba(0,0,0,0.55)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 20,
}}
>
<div
onClick={(e) => e.stopPropagation()}
className="card"
style={{ padding: 24, maxWidth: 440, width: '100%' }}
>
<div style={{ fontSize: 16, fontWeight: 700, marginBottom: 4 }}>
{isZh
? `现在平掉 ${closing.asset} ${closing.side === 'long' ? '多单' : '空单'}?`
: `Close ${closing.side === 'long' ? 'long' : 'short'} ${closing.asset} now?`}
</div>
<div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 16 }}>
{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.'}
</div>
<div
style={{
background: 'var(--bg-sunk)',
borderRadius: 8,
padding: 14,
marginBottom: 16,
}}
>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
fontSize: 12,
marginBottom: 6,
}}
>
<span style={{ color: 'var(--ink-3)' }}>{isZh ? '开仓价' : 'Entry'}</span>
<span className="mono">{fmtMoney(closing.entry_price)}</span>
</div>
<div
style={{
display: 'flex',
justifyContent: 'space-between',
fontSize: 12,
marginBottom: 6,
}}
>
<span style={{ color: 'var(--ink-3)' }}>{isZh ? '现价' : 'Current price'}</span>
<span className="mono">
{closing.current_price != null
? fmtMoney(closing.current_price)
: isZh
? '暂无'
: 'n/a'}
</span>
</div>
{closing.realized_usd != null && closing.realized_usd !== 0 && (
<div
style={{
display: 'flex',
justifyContent: 'space-between',
fontSize: 12,
marginBottom: 6,
color: 'var(--ink-3)',
}}
>
<span>{isZh ? '已落袋(之前减仓)' : 'Already banked'}</span>
<span className="mono">{fmtMoney(closing.realized_usd, { sign: true })}</span>
</div>
)}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
fontSize: 13,
fontWeight: 600,
marginTop: 8,
paddingTop: 8,
borderTop: '1px solid var(--line)',
}}
>
<span>{isZh ? '平仓后将结算' : "You'll get if you close now"}</span>
<span
style={{
color:
(closing.unrealized_usd ?? 0) > 0
? 'var(--up)'
: (closing.unrealized_usd ?? 0) < 0
? 'var(--down)'
: 'var(--ink-2)',
fontVariantNumeric: 'tabular-nums',
}}
>
{fmtMoney(closing.unrealized_usd, { sign: true })}
<span style={{ marginLeft: 6, opacity: 0.7, fontSize: 11 }}>
({fmtPct(closing.unrealized_pct)})
</span>
</span>
</div>
</div>
{closeState === 'err' && (
<div style={{ fontSize: 12, color: 'var(--down)', marginBottom: 12 }}>{closeErr}</div>
)}
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button
onClick={() => setClosing(null)}
disabled={closeState === 'signing' || closeState === 'closing'}
className="btn ghost"
style={{ padding: '8px 16px', fontSize: 13 }}
>
{isZh ? '取消' : 'Cancel'}
</button>
<button
onClick={confirmCloseTrade}
disabled={closeState === 'signing' || closeState === 'closing'}
className="btn"
style={{
padding: '8px 18px',
fontSize: 13,
fontWeight: 600,
background: 'var(--down)',
color: '#fff',
border: 'none',
}}
>
{closeState === 'signing'
? isZh
? '钱包签名中…'
: 'Sign in wallet…'
: closeState === 'closing'
? isZh
? '平仓中…'
: 'Closing…'
: isZh
? `立即平掉 ${closing.asset}`
: `Close ${closing.asset} now`}
</button>
</div>
</div>
</div>
)}
</div>
)
}
+34
View File
@@ -0,0 +1,34 @@
// Emits a schema.org/BreadcrumbList as JSON-LD. Server-component friendly —
// renders only a <script> tag, no visible DOM. Helps Google breadcrumb rich
// results and gives AI answer engines the page's entity hierarchy.
//
// Usage (server component):
// <Breadcrumbs items={[{ name: 'Methodology', path: '/en/methodology' }]} />
// "Home" is prepended automatically; pass the page itself as the last item.
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || 'https://trumpsignal.com'
export interface Crumb {
name: string
path: string // e.g. "/en/methodology"
}
export default function Breadcrumbs({ items }: { items: Crumb[] }) {
const all: Crumb[] = [{ name: 'Trump Alpha', path: '/en' }, ...items]
const jsonLd = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: all.map((c, i) => ({
'@type': 'ListItem',
position: i + 1,
name: c.name,
item: `${siteUrl}${c.path}`,
})),
}
return (
<script
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
/>
)
}
@@ -0,0 +1,87 @@
'use client'
import type { SignalSource } from '@/lib/api'
interface Props {
sources: SignalSource[]
activeSource: string
onChange: (src: string) => void
/** Count map keyed by source (computed by parent from live post list). */
liveCounts: Record<string, number>
}
function relativeTime(iso: string | null): string {
if (!iso) return '—'
const diff = (Date.now() - new Date(iso).getTime()) / 1000
if (diff < 60) return `${Math.round(diff)}s ago`
if (diff < 3600) return `${Math.round(diff / 60)}m ago`
if (diff < 86400) return `${Math.round(diff / 3600)}h ago`
return `${Math.round(diff / 86400)}d ago`
}
/**
* Source filter chips for the signals page.
*
* Each chip = one entry from /api/signals/sources. Shows total historical
* count from the server + the (filtered) live count from the current post
* payload — so the user can see "this filter would drop me from 700 to 13".
*/
export default function SourceChips({ sources, activeSource, onChange, liveCounts }: Props) {
// Always have an "all" pseudo-source first
const totalCount = sources.reduce((s, x) => s + x.count, 0)
return (
<div className="card" style={{ padding: 16, marginBottom: 12 }}>
<div
style={{
fontSize: 11,
fontWeight: 600,
letterSpacing: '0.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
marginBottom: 10,
}}
>
Signal sources
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
{/* All */}
<button
onClick={() => onChange('all')}
className={`chip ${activeSource === 'all' ? 'up' : ''}`}
style={{ padding: '8px 14px', cursor: 'pointer', border: '1px solid var(--line)' }}
>
<span style={{ fontWeight: 600 }}>All</span>
<span style={{ marginLeft: 8, color: 'var(--ink-4)' }}>{totalCount}</span>
</button>
{sources.map((s) => (
<button
key={s.source}
onClick={() => onChange(s.source)}
className={`chip ${activeSource === s.source ? 'up' : ''}`}
style={{
padding: '8px 14px',
cursor: 'pointer',
border: '1px solid var(--line)',
background: activeSource === s.source ? 'var(--up-soft)' : undefined,
}}
title={`Last signal: ${relativeTime(s.latest)}`}
>
<span style={{ fontWeight: 600 }}>{s.source}</span>
<span style={{ marginLeft: 8, color: 'var(--ink-4)' }}>{s.count}</span>
{/* Show live filtered count when different from total */}
{liveCounts[s.source] !== undefined && liveCounts[s.source] !== s.count && (
<span style={{ marginLeft: 6, fontSize: 10, color: 'var(--ink-3)' }}>
({liveCounts[s.source]} loaded)
</span>
)}
<span style={{ marginLeft: 8, fontSize: 10, color: 'var(--ink-4)' }}>
· {relativeTime(s.latest)}
</span>
</button>
))}
</div>
</div>
)
}
@@ -0,0 +1,483 @@
'use client'
import Link from 'next/link'
import { useState, useEffect, useCallback, useRef } from 'react'
import { useLocale } from 'next-intl'
import { useAccount, useSignMessage } from 'wagmi'
import { getUserPublic, setAutoTrade, type UserPublic } from '@/lib/api'
import { signRequest } from '@/lib/signedRequest'
import { isUserRejection, walletErrorLabel } from '@/lib/walletError'
import { confirmSign } from '@/components/wallet/SignConfirmSheet'
/**
* ONE control: the master Auto-Trade switch.
*
* OFF (default, safe) — signals are still scanned & shown in the feed,
* but NO trade is opened. Pure monitoring.
* ON — a qualifying signal auto-opens a trade (full
* System-2 risk: dynamic leverage, staged de-risk,
* ratchet, peak-trail). De-risk / stop-loss always
* run on open positions regardless — never toggleable.
*
* Replaces the old scanner-toggle / timed manual-window / schedule / paper
* trio. Circuit breaker is read-only; turning Auto-Trade ON acknowledges +
* clears a tripped breaker. Per-trade pyramiding is the "Grow" switch on
* each open position (Trades page), not here.
*/
const SYS = {
trump: { idx: '', name: 'Trump Signal', accent: '#b45309', soft: 'rgba(180,83,9,0.08)' },
btc: { idx: '', name: 'Macro Vibes', accent: '#16a34a', soft: 'rgba(22,163,74,0.08)' },
} as const
const ROW: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
padding: '8px 0',
flexWrap: 'wrap',
}
const LABEL: React.CSSProperties = { fontSize: 13, color: 'var(--ink-2)' }
export default function SystemControl({ system }: { system: 'trump' | 'btc' }) {
const locale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const s = SYS[system]
const { address, isConnected } = useAccount()
const { signMessageAsync } = useSignMessage()
const [mounted, setMounted] = useState(false)
const [pub, setPub] = useState<UserPublic | null>(null)
const [busy, setBusy] = useState(false)
const [err, setErr] = useState('')
useEffect(() => {
setMounted(true)
}, [])
// Generation counter: each address change increments it so any in-flight
// refresh from the previous address can detect it's stale.
// `snap !== address` inside a useCallback is a stale-closure trap — both
// refer to the same closed-over value so the check is always false.
const genRef = useRef(0)
useEffect(() => {
genRef.current++
}, [address])
const refresh = useCallback(async () => {
if (!address) {
setPub(null)
return
}
const gen = genRef.current
const p = await getUserPublic(address.toLowerCase()).catch(() => null)
if (gen !== genRef.current) return // wallet changed while in-flight
setPub(p)
}, [address])
useEffect(() => {
refresh()
const poll = setInterval(refresh, 30_000)
return () => clearInterval(poll)
}, [refresh])
const subscribed = !!pub?.active
const paper = !!pub?.paper_mode
const autoOn = !!pub?.auto_trade
const cbTripped =
!!pub?.circuit_breaker_tripped_at &&
Date.now() - new Date(pub!.circuit_breaker_tripped_at!).getTime() < 24 * 3600 * 1000
async function flipAuto(on: boolean) {
if (busy) return
if (!address) {
setErr(isZh ? '请先连接右上角的钱包。' : 'Connect your wallet first (top-right).')
return
}
if (!subscribed) {
setErr(
isZh
? '钱包尚未订阅,请先去设置页完成订阅。'
: 'Wallet not subscribed — subscribe on the Settings page first.',
)
return
}
// B51: live users without an HL API key cannot actually execute trades —
// block the toggle so the ON state never silently becomes a no-op.
if (on && !paper && !pub?.hl_api_key_set) {
setErr(
isZh
? '未绑定 Hyperliquid API Key。请先在设置页保存 API Key,Auto-Trade 才能真实下单。'
: 'No Hyperliquid API key saved. Add your HL API key on the Settings page before enabling Auto-Trade.',
)
return
}
if (autoOn === on) return
// Claim the busy slot BEFORE awaiting confirmSign — otherwise a rapid
// second click on the same pill (or the opposite pill) slips past the
// `if (busy) return` guard and queues a second sheet + second signature.
// We still clear it in `finally` below.
setBusy(true)
setErr('')
// Show pre-signing confirmation sheet before triggering MetaMask
const confirmed = await confirmSign(
on
? {
label: paper
? isZh
? '开启 Auto-Trade(模拟模式)'
: 'Enable Auto-Trade (paper mode)'
: isZh
? '开启 Auto-Trade(真实资金)'
: 'Enable Auto-Trade (live capital)',
description: paper
? isZh
? '机器人将在信号触发时自动开仓(Paper 模式,无真实资金)。钱包签名仅用于身份验证。'
: 'The bot will auto-open positions when a qualifying signal fires in paper mode. No real capital is used. The wallet signature is only for identity verification.'
: isZh
? '机器人将在 Hyperliquid 上用真实资金自动开仓。止损与分级减仓始终生效保护仓位。'
: 'The bot will auto-open real positions on Hyperliquid. Stop-loss and staged de-risking remain active to protect the position.',
danger: !paper,
}
: {
label: isZh ? '关闭 Auto-Trade' : 'Disable Auto-Trade',
description: isZh
? '停止自动开仓。已有持仓的止损与减仓逻辑仍会继续运行。'
: 'Stop opening new trades automatically. Risk controls on existing positions will keep running.',
danger: false,
},
)
if (!confirmed) {
setBusy(false)
return
} // release the slot we claimed
try {
const env = await signRequest({
action: 'set_auto_trade',
wallet: address,
body: { enabled: on },
signMessageAsync,
})
const r = await setAutoTrade(env, on)
setPub((p) =>
p
? {
...p,
auto_trade: r.auto_trade,
...(r.circuit_breaker_cleared
? { circuit_breaker_tripped_at: null, circuit_breaker_reason: null }
: {}),
}
: p,
)
} catch (e) {
if (isUserRejection(e)) {
setErr(isZh ? '已取消' : 'Cancelled')
} else {
setErr(
walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 110) ||
(isZh ? 'Auto-Trade 切换失败' : 'Auto-Trade toggle failed'),
)
}
} finally {
setBusy(false)
}
}
// SSR / pre-hydration: render nothing to avoid hydration mismatch with
// wagmi state that resolves client-side.
if (!mounted) return null
const settingsHref = `/${locale}/settings#bot-config`
// Macro Vibes (System 2) is MANAGE-ONLY by design — it NEVER auto-opens a
// trade. bot_engine.process_post early-returns for sys2 sources, so the
// master Auto-Trade switch only governs Trump (System 1). Presenting an
// ON/OFF auto-trade toggle here would (a) falsely imply Macro signals
// auto-open and (b) be a confusing second copy of the SAME global switch
// shown on the Trump page. Show the adopt-only flow instead.
if (system === 'btc') {
// Compact inline strip — signal fires → you open → bot manages.
// No big card; the data panel is the main content. Settings link stays
// for users who want to configure, but the explanation is one line.
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 12,
flexWrap: 'wrap',
padding: '9px 14px',
marginBottom: 14,
borderRadius: 8,
background: s.soft,
borderLeft: `3px solid ${s.accent}`,
}}
>
<span style={{ fontSize: 12, color: 'var(--ink-2)', lineHeight: 1.4 }}>
<strong style={{ color: s.accent }}>You open · bot manages exit</strong>
<span style={{ color: 'var(--ink-4)', marginLeft: 8 }}>
Signal → Telegram → open on Hyperliquid → <code style={{ fontSize: 11 }}>/adopt</code>
</span>
</span>
<Link
href={settingsHref}
style={{
fontSize: 11,
color: s.accent,
textDecoration: 'none',
fontWeight: 700,
flexShrink: 0,
opacity: 0.8,
}}
>
Settings ↗
</Link>
</div>
)
}
// Wallet not connected: a previous version showed a giant full-width
// "Connect a wallet..." card here, which was redundant with the navbar's
// Connect button. The opposite extreme — rendering null — silently hid
// the existence of Auto-Trade for unconnected users. Compromise: a SLIM
// inline strip that simply announces the feature without pushing the
// page around. Once connected, the full control panel renders below.
if (!isConnected) {
return (
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: 10,
flexWrap: 'wrap',
padding: '10px 14px',
marginBottom: 16,
background: 'var(--bg-sunk)',
border: '1px dashed var(--line)',
borderRadius: 8,
fontSize: 12,
color: 'var(--ink-3)',
}}
>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
<span
style={{
width: 6,
height: 6,
borderRadius: '50%',
background: 'var(--ink-4)',
flexShrink: 0,
}}
/>
{/* No "{s.name}" prefix — the page title right above already names
the system; repeating it here read "Trump Signal" twice per screen. */}
<span style={{ color: 'var(--ink-2)', fontWeight: 600 }}>Auto-Trade</span>
<span>·</span>
<span style={{ color: 'var(--ink-4)' }}>OFF — connect wallet (top-right) to enable</span>
</div>
<Link
href={settingsHref}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 8,
padding: '8px 12px',
borderRadius: 999,
border: '1px solid var(--line)',
background: 'var(--surface)',
fontSize: 12,
color: 'var(--ink)',
textDecoration: 'none',
fontWeight: 700,
boxShadow: 'var(--shadow-1)',
}}
>
<span>Settings</span>
<span aria-hidden="true">↗</span>
</Link>
</div>
)
}
// ── Net result — the single sentence that matters ─────────────────────────
let netOk = false
let netMsg = ''
if (!subscribed) {
netMsg = isZh
? '钱包还没订阅,请先去设置页完成订阅。'
: 'Wallet not subscribed — subscribe on the Settings page first.'
} else if (cbTripped) {
netMsg = isZh
? `熔断器已触发(${pub?.circuit_breaker_reason || '风险限制'})。重新打开 Auto-Trade 才会确认并恢复。`
: `Circuit breaker tripped (${pub?.circuit_breaker_reason || 'risk limit'}). Turn Auto-Trade ON to acknowledge & resume.`
} else if (!autoOn) {
netMsg = isZh
? 'Auto-Trade 当前为关闭: Trump 信号仍会显示,但不会自动开仓。'
: 'Auto-Trade is OFF — Trump signals are shown in the feed but NOT traded.'
} else if (pub?.trump_enabled === false) {
// Auto-Trade is ON but the Trump (System-1) gate is OFF, so the backend
// skips every Trump signal (bot_engine: trump_enabled OFF → not traded).
// Without this branch the UI falsely promised "next signal auto-opens".
netMsg = isZh
? 'Auto-Trade 已开启,但 Trump 系统①未启用: 在设置页打开 Trump 开关后才会自动开仓。'
: 'Auto-Trade is ON, but the Trump system is disabled — enable Trump in Settings before signals will trade.'
} else {
netOk = true
netMsg = isZh
? `Auto-Trade 已开启(Trump 系统①): 下一条合格 Trump 信号会自动开出${paper ? '模拟' : '真实'}仓位。`
: `Auto-Trade ON — will open a ${paper ? 'PAPER' : 'LIVE'} trade on the next qualifying Trump signal.`
}
const Pill = ({
active,
onClick,
children,
tone,
}: {
active: boolean
onClick: () => void
children: React.ReactNode
tone: 'green' | 'idle'
}) => {
const bg = active ? (tone === 'green' ? 'var(--up, #16a34a)' : 'var(--ink-3)') : 'transparent'
return (
<button
onClick={onClick}
disabled={busy}
style={{
padding: '8px 20px',
fontSize: 13,
fontWeight: 800,
borderRadius: 8,
cursor: busy ? 'wait' : 'pointer',
border: active ? `1px solid ${bg}` : '1px solid var(--line)',
background: active ? bg : 'transparent',
color: active ? '#fff' : 'var(--ink-3)',
}}
>
{children}
</button>
)
}
return (
<div className="card" style={{ padding: 0, marginBottom: 16, overflow: 'hidden' }}>
{/* Header */}
<div
style={{ padding: '14px 16px', background: s.soft, borderLeft: `4px solid ${s.accent}` }}
>
{/* Header is just "Auto-Trade" — the page title already names the
system, and the switch row below repeats "Auto-Trade" otherwise. */}
<div style={{ fontSize: 14, fontWeight: 700, color: s.accent }}>
{isZh ? '控制面板' : 'Auto-Trade'}
</div>
</div>
{/* Master Auto-Trade switch */}
<div style={{ padding: '16px' }}>
<div style={ROW}>
{/* The card header above already says "Auto-Trade" — this row only
carries the ON/OFF legend, not a second title. */}
<div style={{ fontSize: 12, color: 'var(--ink-3)' }}>
{isZh
? 'OFF = 只监控信号 · ON = 自动开仓'
: 'OFF = monitor only · ON = auto-open on qualifying Trump signals'}
</div>
<div style={{ display: 'flex', gap: 6 }}>
<Pill active={autoOn} onClick={() => flipAuto(true)} tone="green">
ON
</Pill>
<Pill active={!autoOn} onClick={() => flipAuto(false)} tone="idle">
OFF
</Pill>
</div>
</div>
{/* Read-only status */}
<div style={{ ...ROW, borderTop: '1px solid var(--line)', marginTop: 8, paddingTop: 12 }}>
<span style={LABEL}>{isZh ? '执行模式' : 'Execution mode'}</span>
<span style={{ fontSize: 12, fontWeight: 700, color: paper ? '#f59e0b' : 'var(--up)' }}>
{paper ? (isZh ? '📝 模拟' : '📝 PAPER') : isZh ? '💰 真实资金' : '💰 LIVE'}
<span style={{ color: 'var(--ink-4)', fontWeight: 400, marginLeft: 8 }}>
{isZh ? '· 订阅时确定' : '· set when subscribing'}
</span>
</span>
</div>
<div style={ROW}>
<span style={LABEL}>{isZh ? '熔断器' : 'Circuit breaker'}</span>
<span
style={{
fontSize: 12,
fontWeight: 700,
color: cbTripped ? 'var(--down)' : 'var(--up)',
}}
>
{cbTripped
? isZh
? `🚨 已触发(${pub?.circuit_breaker_reason})`
: `🚨 tripped (${pub?.circuit_breaker_reason})`
: isZh
? '✓ 正常'
: '✓ clear'}
</span>
</div>
{err && <div style={{ fontSize: 11, color: 'var(--down)', marginTop: 10 }}>● {err}</div>}
</div>
{/* Net result */}
<div
style={{
padding: '14px 16px',
background: netOk ? 'var(--up-soft)' : 'var(--down-soft, rgba(220,38,38,.08))',
borderTop: '1px solid var(--line)',
}}
>
<div
style={{
fontSize: 11,
fontWeight: 700,
letterSpacing: '.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
marginBottom: 4,
}}
>
{isZh ? '⟹ 当前状态' : '⟹ Current status'}
</div>
<div style={{ fontSize: 14, fontWeight: 700, color: netOk ? 'var(--up)' : 'var(--down)' }}>
{netOk ? '✅ ' : '⛔ '}
{netMsg}
</div>
<div style={{ marginTop: 8 }}>
<Link
href={settingsHref}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 8,
padding: '8px 12px',
borderRadius: 999,
border: '1px solid var(--line)',
background: 'var(--surface)',
fontSize: 12,
color: 'var(--ink)',
textDecoration: 'none',
fontWeight: 700,
boxShadow: 'var(--shadow-1)',
}}
>
<span>Settings</span>
<span aria-hidden="true">↗</span>
</Link>
</div>
</div>
</div>
)
}
@@ -0,0 +1,481 @@
'use client'
import { useState, useEffect, useCallback, useRef } from 'react'
import { useLocale } from 'next-intl'
import { useAccount, useSignMessage } from 'wagmi'
import { getTelegramStatus, tgInit, tgUnbind, type TelegramStatus } from '@/lib/api'
import { signRequest } from '@/lib/signedRequest'
import { walletErrorLabel } from '@/lib/walletError'
import { confirmSign } from '@/components/wallet/SignConfirmSheet'
/**
* Settings → Telegram alerts card.
*
* Three states:
* 1. Server not configured → show "ask the admin to set up the bot"
* 2. Not bound → deep-link to bot + optional wallet-link code
* 3. Bound → status line + link to bot for preferences
*
* Preferences are managed entirely inside the bot (/trump /btc /funding /kol
* /conf /quiet). This card is just discovery + wallet-linking for Pro users.
*/
export default function TelegramCard() {
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 [status, setStatus] = useState<TelegramStatus | null>(null)
const [loading, setLoading] = useState(true)
const [err, setErr] = useState('')
const [busy, setBusy] = useState(false)
const [code, setCode] = useState<{ code: string; deep_link: string } | null>(null)
useEffect(() => {
setMounted(true)
}, [])
// Generation counter guards against stale-closure trap: `snap !== address`
// inside useCallback compares two closed-over copies of the same value and
// is always false. genRef is a mutable ref readable from any closure.
const genRef = useRef(0)
useEffect(() => {
genRef.current++
}, [address])
const refresh = useCallback(async () => {
if (!address) {
setLoading(false)
setStatus(null)
return
}
const gen = genRef.current
setLoading(true)
try {
const { getCachedViewEnvelope } = await import('@/lib/signedRequest')
const cached = getCachedViewEnvelope('view_user', address)
const s = await getTelegramStatus(address.toLowerCase(), cached ?? undefined)
if (gen !== genRef.current) return // wallet changed while in-flight
setStatus(s)
setErr('')
} catch (e) {
if (gen !== genRef.current) return
setErr(e instanceof Error ? e.message : 'load failed')
} finally {
if (gen === genRef.current) setLoading(false)
}
}, [address])
// B32: clear stale status immediately when wallet changes so the previous
// wallet's binding info never flickers in before the new fetch resolves.
useEffect(() => {
setStatus(null)
setCode(null)
setErr('')
}, [address])
useEffect(() => {
refresh()
}, [refresh])
// Poll while waiting for wallet-link to complete.
useEffect(() => {
if (!code || status?.bound) return
const id = setInterval(refresh, 3000)
return () => clearInterval(id)
}, [code, status?.bound, refresh])
const botUsername = status?.bot_username ?? 'TrumpAlpha_bot'
const botLink = `https://t.me/${botUsername}`
async function handleLinkWallet() {
if (!address) return
setBusy(true)
setErr('')
try {
const confirmed = await confirmSign({
label: 'Generate Telegram link code',
description:
'A one-time 6-char code valid for 10 min. Paste it into the bot to link your wallet for Pro features.',
})
if (!confirmed) {
setBusy(false)
return
}
const env = await signRequest({
action: 'telegram_init',
wallet: address,
body: null,
signMessageAsync,
})
const r = await tgInit(address.toLowerCase(), env)
setCode({ code: r.code, deep_link: r.deep_link })
} catch (e) {
setErr(walletErrorLabel(e, 'Cancelled'))
} finally {
setBusy(false)
}
}
async function handleUnbind() {
if (!address) return
setBusy(true)
setErr('')
try {
const confirmed = await confirmSign({
label: 'Disconnect Telegram',
description:
'Unlinks this wallet from Telegram. Your free subscription stays active in the bot.',
})
if (!confirmed) {
setBusy(false)
return
}
const env = await signRequest({
action: 'telegram_unbind',
wallet: address,
body: null,
signMessageAsync,
})
await tgUnbind(address.toLowerCase(), env)
setCode(null)
await refresh()
} catch (e) {
setErr(walletErrorLabel(e, 'Cancelled'))
} finally {
setBusy(false)
}
}
// ── Render ───────────────────────────────────────────────────────────────
if (!mounted) return null
if (!isConnected) {
return (
<div className="card" style={{ padding: 20, marginBottom: 16 }}>
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Telegram alerts</div>
<div style={{ fontSize: 12, color: 'var(--ink-3)', lineHeight: 1.6 }}>
You can get free Telegram alerts without a wallet — just open the bot. Connect a wallet
here to also get alerts tailored to your own positions.
</div>
</div>
)
}
return (
<div className="card" style={{ padding: 20, marginBottom: 16 }}>
{/* Header */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: 12,
gap: 12,
flexWrap: 'wrap',
}}
>
<div>
<div
style={{
fontSize: 11,
fontWeight: 600,
letterSpacing: '0.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
}}
>
{isZh ? 'Telegram 提醒' : 'Telegram alerts'}
</div>
<div style={{ fontSize: 13, color: 'var(--ink-2)', marginTop: 2 }}>
{isZh
? '高置信度信号触发时发送推送提醒'
: 'Push notifications when high-conviction signals fire'}
</div>
</div>
{status?.bound && status.alerts_enabled && (
<span
style={{
fontSize: 11,
color: 'var(--up)',
fontWeight: 600,
padding: '4px 10px',
borderRadius: 6,
background: 'var(--up-soft)',
}}
>
● {isZh ? '已开启' : 'Active'}
</span>
)}
{status?.bound && !status.alerts_enabled && (
<span
style={{
fontSize: 11,
color: 'var(--ink-4)',
fontWeight: 600,
padding: '4px 10px',
borderRadius: 6,
background: 'var(--bg-sunk)',
}}
>
○ {isZh ? '已暂停' : 'Paused'}
</span>
)}
</div>
{loading && <div className="skeleton sk-line sk-w-full" style={{ marginBottom: 8 }} />}
{/* Server not configured */}
{!loading && status && !status.configured && (
<div
style={{
padding: 12,
fontSize: 12,
color: 'var(--ink-3)',
background: 'var(--bg-sunk)',
borderRadius: 6,
}}
>
⚠️{' '}
{isZh
? '当前服务器还没有配置 Telegram 提醒。请让管理员设置'
: 'Telegram alerts are not configured on this server. Ask the operator to set'}
<code style={{ margin: '0 4px' }}>TELEGRAM_BOT_TOKEN</code> and
<code style={{ margin: '0 4px' }}>TELEGRAM_BOT_USERNAME</code>.
</div>
)}
{/* Configured — main body */}
{!loading && status?.configured && (
<div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
{/* Bot link row — always visible */}
<div
style={{
display: 'flex',
alignItems: 'center',
gap: 10,
padding: '10px 14px',
borderRadius: 8,
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
}}
>
<span style={{ fontSize: 18 }}>✈️</span>
<div style={{ flex: 1 }}>
<div style={{ fontSize: 13, fontWeight: 500 }}>
<a
href={botLink}
target="_blank"
rel="noopener noreferrer"
style={{ color: 'var(--amber, #f59e0b)', textDecoration: 'none' }}
>
@{botUsername} ↗
</a>
</div>
<div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 2 }}>
{status.bound
? isZh
? '在机器人里可开关各类提醒、设置免打扰时段'
: 'Open the bot to choose which alerts you get and set quiet hours'
: isZh
? '打开机器人并发送 /start,无需额外账号'
: 'Open the bot and tap Start — no account needed'}
</div>
</div>
</div>
{/* Bound: wallet status + disconnect */}
{status.bound && (
<div
style={{
fontSize: 12,
color: 'var(--ink-3)',
display: 'flex',
alignItems: 'center',
gap: 8,
flexWrap: 'wrap',
}}
>
<span>
{status.tg_username ? (
<>
{isZh ? '已绑定账号' : 'Linked as'}{' '}
<strong style={{ color: 'var(--ink)' }}>@{status.tg_username}</strong>
</>
) : (
<>
{isZh ? '聊天 ID' : 'Chat'}{' '}
<strong style={{ color: 'var(--ink)' }}>#{status.chat_id}</strong>
</>
)}
</span>
{status.wallet_address ? (
<>
<span style={{ color: 'var(--ink-4)' }}>·</span>
<span style={{ color: 'var(--up)', fontSize: 11 }}>Pro</span>
<span style={{ color: 'var(--ink-4)' }}>·</span>
<span>
{isZh
? `已发送 ${status.total_alerts_sent ?? 0} 条提醒`
: `${status.total_alerts_sent ?? 0} alerts sent`}
</span>
<span style={{ color: 'var(--ink-4)' }}>·</span>
<button
className="btn ghost"
disabled={busy}
onClick={handleUnbind}
style={{ fontSize: 11, color: 'var(--down)', padding: '2px 8px' }}
>
{isZh ? '断开钱包绑定' : 'Disconnect wallet'}
</button>
</>
) : (
<>
<span style={{ color: 'var(--ink-4)' }}>·</span>
<span>
{isZh
? `已发送 ${status.total_alerts_sent ?? 0} 条提醒`
: `${status.total_alerts_sent ?? 0} alerts sent`}
</span>
</>
)}
</div>
)}
{/* Not bound: optional wallet-link for Pro */}
{!status.bound && !code && (
<div style={{ fontSize: 12, color: 'var(--ink-4)' }}>
{isZh ? '已经在机器人里了?' : 'Already in the bot?'}{' '}
<button
onClick={handleLinkWallet}
disabled={busy}
style={{
background: 'none',
border: 'none',
cursor: 'pointer',
color: 'var(--amber, #f59e0b)',
fontSize: 12,
padding: 0,
textDecoration: 'underline',
}}
>
{isZh ? '绑定这个钱包以启用 Pro 功能' : 'Link this wallet for Pro features'}
</button>
</div>
)}
{/* Wallet-link code flow */}
{!status.bound && code && (
<WalletLinkPanel
code={code.code}
link={code.deep_link}
onCancel={() => setCode(null)}
isZh={isZh}
/>
)}
</div>
)}
{err && <div style={{ fontSize: 11, color: 'var(--down)', marginTop: 8 }}>● {err}</div>}
</div>
)
}
// ── Subcomponents ────────────────────────────────────────────────────────────
function WalletLinkPanel({
code,
link,
onCancel,
isZh,
}: {
code: string
link: string
onCancel: () => void
isZh: boolean
}) {
const [copied, setCopied] = useState(false)
function copy() {
navigator.clipboard
.writeText(code)
.then(() => {
setCopied(true)
setTimeout(() => setCopied(false), 1500)
})
.catch(() => {})
}
return (
<div
style={{
padding: 14,
background: 'var(--bg-sunk)',
borderRadius: 8,
border: '1px solid var(--line)',
}}
>
<div style={{ fontSize: 13, fontWeight: 600, marginBottom: 8 }}>
{isZh ? '绑定钱包(Pro):' : 'Link wallet (Pro):'}
</div>
<ol
style={{
paddingLeft: 18,
fontSize: 12,
color: 'var(--ink-2)',
lineHeight: 1.7,
marginBottom: 12,
}}
>
<li>
{isZh ? '打开机器人:' : 'Open the bot:'}&nbsp;
<a
href={link}
target="_blank"
rel="noopener noreferrer"
style={{ color: 'var(--amber, #f59e0b)', fontWeight: 600 }}
>
{link.replace('https://', '')} ↗
</a>
</li>
<li>
{isZh ? '发送' : 'Send'}{' '}
<code style={{ background: 'var(--bg)', padding: '1px 6px', borderRadius: 3 }}>
/start {code}
</code>
<button
onClick={copy}
style={{
marginLeft: 6,
fontSize: 11,
padding: '2px 8px',
borderRadius: 4,
border: '1px solid var(--line)',
background: 'var(--bg)',
cursor: 'pointer',
color: 'var(--ink-3)',
}}
>
{copied ? (isZh ? '✓ 已复制' : '✓ copied') : isZh ? '复制验证码' : 'copy code'}
</button>
</li>
</ol>
<div style={{ fontSize: 11, color: 'var(--ink-4)', marginBottom: 10 }}>
{isZh
? '验证码 10 分钟内有效,绑定成功后这里会自动刷新。'
: 'Code expires in 10 min. This panel updates automatically once linked.'}
</div>
<button
onClick={onCancel}
style={{
fontSize: 11,
color: 'var(--ink-3)',
background: 'none',
border: 'none',
cursor: 'pointer',
padding: 0,
}}
>
{isZh ? '取消' : 'Cancel'}
</button>
</div>
)
}
File diff suppressed because it is too large Load Diff
+562
View File
@@ -0,0 +1,562 @@
'use client'
import { useState, useMemo, useEffect } from 'react'
import { useLocale } from 'next-intl'
import type { BotTrade } from '@/types'
import Pagination from '@/components/ui/Pagination'
// ── Formatters ────────────────────────────────────────────────────────────────
function fmtMoney(n: number, opts: { sign?: boolean; decimals?: number } = {}) {
const { decimals = 2, sign = false } = opts
if (n == null || isNaN(n)) return '—'
const abs = Math.abs(n)
const s = abs.toLocaleString('en-US', {
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
})
if (n < 0) return '-$' + s
if (sign && n > 0) return '+$' + s
return '$' + s
}
function fmtPct(n: number) {
return (n >= 0 ? '+' : '') + n.toFixed(2) + '%'
}
function fmtHold(s: number | null | undefined) {
if (s == null) return '—'
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'
}
interface Props {
trades: BotTrade[]
loading: boolean
locked?: boolean // true = waiting for wallet signature, not "no trades"
}
// ASSETS filter is derived dynamically from the trade set (see useMemo below)
// so new assets (TRUMP, BNB, DOGE, LINK, AAVE, ...) appear automatically.
const SIDES = ['all', 'long', 'short'] as const
// Human-readable labels for raw signal-source identifiers. Keeps the trade
// history readable for non-technical users (matches PostCards source labels).
const SOURCE_LABEL: Record<string, string> = {
truth: 'Trump',
btc_bottom_reversal: 'BTC Macro Bottom',
funding_reversal: 'Funding Reversal',
kol_divergence: 'KOL Divergence',
sma_reclaim: 'SMA Reclaim',
rsi_reversal: 'RSI Reversal',
breakout: 'Breakout',
adopted: 'Adopted',
manual: 'Manual',
unknown: 'Unknown',
}
function sourceLabel(src: string): string {
return SOURCE_LABEL[src?.toLowerCase()] ?? src
}
const TRADES_PER_PAGE = 25
export default function TradeTable({ trades, loading, locked = false }: Props) {
const locale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const [assetFilter, setAssetFilter] = useState('all')
const [sideFilter, setSideFilter] = useState('all')
const [sourceFilter, setSourceFilter] = useState('all')
const [hidePaper, setHidePaper] = useState(false)
const [page, setPage] = useState(1)
// Distinct assets present in the loaded trade set — drives the asset filter.
// Dynamic so new perps (TRUMP, BNB, DOGE, LINK, AAVE, ...) appear without
// a code change; sorted alphabetically with BTC/ETH first for familiarity.
const assets: string[] = useMemo(() => {
const set = new Set<string>()
for (const t of trades) if (t.asset) set.add(t.asset)
const priority = ['BTC', 'ETH', 'SOL', 'TRUMP']
const rest = Array.from(set)
.filter((a) => !priority.includes(a))
.sort()
return ['all', ...priority.filter((a) => set.has(a)), ...rest]
}, [trades])
// Distinct sources present in the loaded trade set — drives the filter UI.
// Includes 'unknown' as a bucket for trades whose trigger post was deleted.
const sources = useMemo(() => {
const set = new Set<string>()
for (const t of trades) set.add(t.trigger_source || 'unknown')
return Array.from(set).sort()
}, [trades])
// Reset filters that no longer apply to the loaded trade set. On a wallet
// switch the trades prop changes but the local filter state persists, so a
// source/asset/side the previous wallet had could stay "stuck" — and when
// the new wallet has a single source the breakdown card (sources.length > 1)
// disappears, removing the only Clear affordance. Clamping here guarantees
// the user always sees their full new history.
useEffect(() => {
if (sourceFilter !== 'all' && !sources.includes(sourceFilter)) setSourceFilter('all')
if (assetFilter !== 'all' && !assets.includes(assetFilter)) setAssetFilter('all')
}, [sources, assets, sourceFilter, assetFilter])
// Per-source PnL aggregate — the critical view for "which module makes money".
// Apply asset/side/paper filters for the source breakdown so the cards stay
// consistent with the KPI and table rows below. We intentionally do NOT apply
// sourceFilter here — filtering by source would trivially make one card 100%.
const filteredForSources = useMemo(
() =>
trades.filter((t) => {
if (assetFilter !== 'all' && t.asset !== assetFilter) return false
if (sideFilter !== 'all' && t.side !== sideFilter) return false
if (hidePaper && t.is_paper) return false
return true
}),
[trades, assetFilter, sideFilter, hidePaper],
)
const perSource = useMemo(() => {
const acc: Record<string, { trades: number; pnl: number; wins: number; paper: number }> = {}
for (const t of filteredForSources) {
const k = t.trigger_source || 'unknown'
if (!acc[k]) acc[k] = { trades: 0, pnl: 0, wins: 0, paper: 0 }
acc[k].trades += 1
if (t.pnl_usd != null) {
acc[k].pnl += t.pnl_usd
if (t.pnl_usd > 0) acc[k].wins += 1
}
if (t.is_paper) acc[k].paper += 1
}
return acc
}, [filteredForSources])
const filtered = useMemo(
() =>
trades.filter((t) => {
if (sourceFilter !== 'all' && (t.trigger_source || 'unknown') !== sourceFilter) return false
if (assetFilter !== 'all' && t.asset !== assetFilter) return false
if (sideFilter !== 'all' && t.side !== sideFilter) return false
if (hidePaper && t.is_paper) return false
return true
}),
[trades, sourceFilter, assetFilter, sideFilter, hidePaper],
)
const totalPages = Math.max(1, Math.ceil(filtered.length / TRADES_PER_PAGE))
const safePage = Math.min(page, totalPages)
const pageRows = filtered.slice((safePage - 1) * TRADES_PER_PAGE, safePage * TRADES_PER_PAGE)
// Exclude externally-closed trades (pnl_usd null) from aggregates.
const priced = filtered.filter((t) => t.pnl_usd !== null && t.pnl_usd !== undefined)
const totalPnl = priced.reduce((s, t) => s + (t.pnl_usd ?? 0), 0)
const wins = priced.filter((t) => (t.pnl_usd ?? 0) > 0).length
const losses = priced.length - wins
const withHold = filtered.filter((t) => t.hold_seconds !== null)
const avgHold =
withHold.length > 0
? Math.round(withHold.reduce((s, t) => s + (t.hold_seconds ?? 0), 0) / withHold.length)
: 0
return (
<>
{/* ── Per-source breakdown (the "which module makes money" view) ── */}
{sources.length > 1 && (
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div
style={{
fontSize: 11,
fontWeight: 600,
letterSpacing: '0.06em',
textTransform: 'uppercase',
color: 'var(--ink-3)',
marginBottom: 10,
}}
>
{isZh ? '按信号来源拆分盈亏' : 'Which signal makes money'}
</div>
<div
style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
gap: 10,
}}
>
{sources.map((src) => {
const s = perSource[src]
const winRate = s.trades ? (s.wins / s.trades) * 100 : 0
const tone = s.pnl > 0 ? 'up' : s.pnl < 0 ? 'down' : 'idle'
const bg =
tone === 'up'
? 'var(--up-soft)'
: tone === 'down'
? 'var(--down-soft)'
: 'var(--bg-sunk)'
const fg =
tone === 'up' ? 'var(--up)' : tone === 'down' ? 'var(--down)' : 'var(--ink-2)'
return (
<button
key={src}
onClick={() => {
setSourceFilter(sourceFilter === src ? 'all' : src)
setPage(1)
}}
style={{
textAlign: 'left',
cursor: 'pointer',
background: bg,
borderRadius: 8,
padding: '12px 14px',
border: `1px solid ${sourceFilter === src ? fg : 'transparent'}`,
}}
>
<div
style={{
fontSize: 11,
fontWeight: 600,
color: 'var(--ink-2)',
marginBottom: 4,
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{sourceLabel(src)}
{s.paper > 0 && (
<span
style={{
fontSize: 9,
marginLeft: 6,
padding: '1px 5px',
borderRadius: 3,
background: 'rgba(245,158,11,0.15)',
color: '#f59e0b',
}}
>
{s.paper}P
</span>
)}
</div>
<div
style={{
fontSize: 16,
fontWeight: 700,
color: fg,
fontVariantNumeric: 'tabular-nums',
}}
>
{fmtMoney(s.pnl, { sign: true, decimals: 0 })}
</div>
<div style={{ fontSize: 10, color: 'var(--ink-3)', marginTop: 2 }}>
{isZh
? `${s.trades} 笔交易 · ${winRate.toFixed(0)}% 胜率`
: `${s.trades} trades · ${winRate.toFixed(0)}% win`}
</div>
</button>
)
})}
</div>
<div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 8 }}>
{isZh ? '点击来源可筛选表格。' : 'Click a source to filter the table.'}{' '}
{sourceFilter !== 'all' && (
<button
onClick={() => {
setSourceFilter('all')
setPage(1)
}}
style={{
marginLeft: 8,
padding: '2px 8px',
fontSize: 10,
border: '1px solid var(--line)',
borderRadius: 4,
background: 'transparent',
cursor: 'pointer',
color: 'var(--ink-2)',
}}
>
{isZh
? `清除(当前为 “${sourceLabel(sourceFilter)}”)`
: `Clear (showing “${sourceLabel(sourceFilter)}”)`}
</button>
)}
</div>
</div>
)}
{/* KPI row */}
<div className="kpi-row" style={{ gridTemplateColumns: 'repeat(4,1fr)', marginBottom: 20 }}>
<div className="kpi">
<div className="label">{isZh ? '总交易数' : 'Total trades'}</div>
<div className="value">{filtered.length}</div>
</div>
<div className="kpi">
<div className="label">{isZh ? '胜率' : 'Win rate'}</div>
<div className="value">
{priced.length ? ((wins / priced.length) * 100).toFixed(1) + '%' : '—'}
</div>
<div className="foot">
<span>{isZh ? `${wins} 赢 · ${losses} 亏` : `${wins}W · ${losses}L`}</span>
</div>
</div>
<div className="kpi accent">
<div className="label">{isZh ? '净盈亏' : 'Net P&L'}</div>
<div className="value">{fmtMoney(totalPnl, { sign: true, decimals: 0 })}</div>
</div>
<div className="kpi">
<div className="label">{isZh ? '平均持仓' : 'Avg hold'}</div>
<div className="value">{avgHold ? fmtHold(avgHold) : '—'}</div>
</div>
</div>
{/* Filters */}
<div
style={{
display: 'flex',
gap: 10,
flexWrap: 'wrap',
alignItems: 'center',
marginBottom: 14,
}}
>
<div className="nav-tabs">
{assets.map((a) => (
<button
key={a}
className={`nav-tab ${assetFilter === a ? 'active' : ''}`}
onClick={() => {
setAssetFilter(a)
setPage(1)
}}
>
{a === 'all' ? (isZh ? '全部资产' : 'All assets') : a}
</button>
))}
</div>
<div className="nav-tabs">
{SIDES.map((s) => (
<button
key={s}
className={`nav-tab ${sideFilter === s ? 'active' : ''}`}
onClick={() => {
setSideFilter(s)
setPage(1)
}}
>
{s === 'all'
? isZh
? '全部方向'
: 'All'
: s === 'long'
? isZh
? '做多'
: 'Long'
: isZh
? '做空'
: 'Short'}
</button>
))}
</div>
{/* Hide-paper toggle: paper trades inflate volume but aren't real $ — */}
{/* let users blend them out before reading the KPI row. */}
<label
style={{
display: 'flex',
alignItems: 'center',
gap: 6,
fontSize: 12,
color: 'var(--ink-3)',
cursor: 'pointer',
marginLeft: 'auto',
}}
>
<input
type="checkbox"
checked={hidePaper}
onChange={(e) => {
setHidePaper(e.target.checked)
setPage(1)
}}
/>
{isZh ? '隐藏模拟交易' : 'Hide paper trades'}
</label>
</div>
{/* Loading state */}
{loading && (
<div style={{ textAlign: 'center', padding: 60, color: 'var(--ink-3)' }}>
{isZh ? '加载中…' : 'Loading…'}
</div>
)}
{/* Table */}
{!loading && (
<div className="card flush" style={{ overflow: 'hidden' }}>
<table className="table">
<thead>
<tr>
{/* P&L right after Side — it's the column this page exists for.
As the last of 8 columns it sat off-screen on phones (the
table scrolls inside its card) until the user swiped past
entry/exit/hold/trigger to find it. */}
<th>{isZh ? '来源' : 'Source'}</th>
<th>{isZh ? '资产' : 'Asset'}</th>
<th>{isZh ? '方向' : 'Side'}</th>
<th>P&amp;L</th>
<th>{isZh ? '开仓' : 'Entry'}</th>
<th>{isZh ? '平仓' : 'Exit'}</th>
<th>{isZh ? '持仓' : 'Hold'}</th>
<th>{isZh ? '触发信号' : 'What triggered it'}</th>
</tr>
</thead>
<tbody>
{filtered.length === 0 && (
<tr>
<td
colSpan={8}
style={{ textAlign: 'center', padding: 40, color: 'var(--ink-3)' }}
>
{locked
? isZh
? '签名解锁后即可查看交易历史。'
: 'Sign to unlock your trade history above.'
: isZh
? '没有符合条件的交易。'
: 'No trades found'}
</td>
</tr>
)}
{pageRows.map((t) => {
const roi =
t.entry_price && t.exit_price != null
? ((t.exit_price - t.entry_price) / t.entry_price) *
100 *
(t.side === 'long' ? 1 : -1)
: 0
const src = t.trigger_source || 'unknown'
return (
<tr key={t.id}>
<td>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span
style={{
fontSize: 11,
fontWeight: 600,
color: 'var(--ink-2)',
padding: '2px 7px',
borderRadius: 4,
background: 'var(--bg-sunk)',
}}
>
{sourceLabel(src)}
</span>
{t.is_paper && (
<span
style={{
fontSize: 9,
padding: '1px 5px',
borderRadius: 3,
background: 'rgba(245,158,11,0.15)',
color: '#f59e0b',
}}
>
PAPER
</span>
)}
</div>
</td>
<td>
<div className="row gap-s">
<span className={`asset-dot ${t.asset.toLowerCase()}`} />
<span style={{ fontWeight: 500 }}>{t.asset}</span>
</div>
</td>
<td>
<span className={`side-pill ${t.side}`}>
{t.side === 'long'
? isZh
? '↗ 做多'
: '↗ LONG'
: isZh
? '↘ 做空'
: '↘ SHORT'}
</span>
</td>
<td>
<div className="stack" style={{ alignItems: 'flex-start' }}>
{t.pnl_usd === null || t.pnl_usd === undefined ? (
<span
style={{ fontSize: 12, color: 'var(--ink-4)' }}
title={
isZh
? '在 Hyperliquid 外部平仓,PnL 未记录'
: 'Closed externally on Hyperliquid — PnL not recorded'
}
>
n/a
</span>
) : (
<>
<span
className={`delta ${t.pnl_usd >= 0 ? 'up' : 'down'}`}
style={{ fontWeight: 600, fontSize: 14 }}
>
{fmtMoney(t.pnl_usd, { sign: true })}
</span>
<span
className={`delta ${roi >= 0 ? 'up' : 'down'}`}
style={{ fontSize: 11, opacity: 0.7 }}
>
{fmtPct(roi)}
</span>
</>
)}
</div>
</td>
<td className="mono">
{t.entry_price ? '$' + t.entry_price.toLocaleString() : '—'}
</td>
<td className="mono">
{t.exit_price != null ? '$' + t.exit_price.toLocaleString() : '—'}
</td>
<td className="mono" style={{ color: 'var(--ink-2)' }}>
{fmtHold(t.hold_seconds)}
</td>
<td style={{ maxWidth: 260 }}>
{t.trigger_post_text ? (
<span
style={{
fontSize: 12,
color: 'var(--ink-2)',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
display: 'block',
}}
>
{t.trigger_post_text.slice(0, 60)}…
</span>
) : (
<span style={{ fontSize: 12, color: 'var(--ink-4)' }}>—</span>
)}
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
{/* Pagination */}
{!loading && (
<Pagination
page={safePage}
total={totalPages}
count={filtered.length}
pageSize={TRADES_PER_PAGE}
onChange={setPage}
scrollTop={false}
/>
)}
</>
)
}
+45
View File
@@ -0,0 +1,45 @@
'use client'
/**
* AnimatedNumber — flashes green/red when its value changes, the way a live
* trading terminal ticks. Pure presentational: it renders `display` (already
* formatted) but watches `value` (the raw number) to decide flash direction.
*
* The flash is a CSS class toggled for ~600ms via a keyframe (`tick-flash-up` /
* `tick-flash-down` in globals.css). Respects prefers-reduced-motion (the CSS
* keyframes are disabled there, so this degrades to a plain number).
*/
import { useEffect, useRef, useState } from 'react'
interface Props {
/** Raw numeric value — drives the flash direction when it changes. */
value: number | null | undefined
/** Pre-formatted string to actually show (e.g. "$72,140"). */
display: string
/** Extra className(s) for the wrapper. */
className?: string
style?: React.CSSProperties
}
export default function AnimatedNumber({ value, display, className = '', style }: Props) {
const prev = useRef<number | null | undefined>(value)
const [dir, setDir] = useState<'up' | 'down' | null>(null)
useEffect(() => {
const p = prev.current
if (value != null && p != null && value !== p) {
setDir(value > p ? 'up' : 'down')
const id = setTimeout(() => setDir(null), 600)
prev.current = value
return () => clearTimeout(id)
}
prev.current = value
}, [value])
return (
<span className={`tick-num ${dir ? `tick-flash-${dir}` : ''} ${className}`} style={style}>
{display}
</span>
)
}
+89
View File
@@ -0,0 +1,89 @@
'use client'
/**
* Inline "?"" hint icon with a hover tooltip.
*
* Use this for any UI element whose meaning isn't obvious from its label —
* stat boxes, tab names, jargon-y settings. Goal is the same as the (i)
* dots in Linear / Hyperliquid / Coinglass: small, ignorable, one hover
* away from a one-line plain-English explanation.
*
* Design rules:
* * `text` MUST be one short sentence — never paste long docs in here.
* If you need a paragraph, you're explaining the wrong thing.
* * The icon is intentionally subtle (12 px circle, ink-4 colour). It
* should disappear visually until the user actively scans for help.
* * The tooltip uses CSS hover positioning — no portals. The only JS is
* an on-reveal measurement that clamps the bubble inside the viewport
* (a centred bubble on an icon near the screen edge used to hang
* off-screen, worst on phones). Trade-off: it's still clipped by the
* nearest `overflow:hidden` ancestor. Pages that need tooltips inside
* a `<table>` cell should add `overflow: visible` to that row/td.
*
* Usage:
* <span>Latest cycle <InfoTip text="The single most recent funding payment, in %." /></span>
*
* <InfoTip
* text="Last 24h of cycles, averaged. Smooths the noise of one print."
* placement="bottom" // default 'top'
* />
*/
import { useRef } from 'react'
import type { CSSProperties } from 'react'
type Placement = 'top' | 'bottom' | 'left' | 'right'
interface Props {
text: string
placement?: Placement
/** Tip max-width in px. Default 240 — fits ~2 short lines. */
width?: number
/** Tweak the icon's vertical alignment for fussy contexts. */
iconStyle?: CSSProperties
}
export default function InfoTip({ text, placement = 'top', width = 240, iconStyle }: Props) {
const rootRef = useRef<HTMLSpanElement>(null)
// Clamp the bubble inside the viewport when it's revealed. The bubble is
// CSS-centred on the icon, so near a screen edge it overflowed off-screen.
// Measured at shift=0, then the needed horizontal offset is written to the
// --tip-shift var consumed by the .infotip-top/-bottom transforms.
function clampIntoViewport() {
const bubble = rootRef.current?.querySelector<HTMLElement>('.infotip-bubble')
if (!bubble) return
bubble.style.setProperty('--tip-shift', '0px')
const r = bubble.getBoundingClientRect()
const vw = document.documentElement.clientWidth
const margin = 8
let shift = 0
if (r.left < margin) shift = margin - r.left
else if (r.right > vw - margin) shift = vw - margin - r.right
if (shift !== 0) bubble.style.setProperty('--tip-shift', `${shift}px`)
}
return (
<span
ref={rootRef}
className={`infotip infotip-${placement}`}
// role=button is a slight overstatement but it lets screen-reader users
// know there's a thing to tab to. The actual content is in data-tip and
// also as a regular <span> child for non-CSS-tooltip fallback.
role="button"
tabIndex={0}
aria-label={text}
style={{ ['--tip-w' as string]: `${width}px`, ...iconStyle }}
onMouseEnter={clampIntoViewport}
onFocus={clampIntoViewport}
onTouchStart={clampIntoViewport}
>
<span aria-hidden="true" className="infotip-icon">
?
</span>
<span className="infotip-bubble" role="tooltip">
{text}
</span>
</span>
)
}
+27
View File
@@ -0,0 +1,27 @@
/**
* One-line "what is this page" tagline that sits right under the page title.
*
* Replaces ad-hoc <p className="page-sub"> spots that ended up as ghost-gray
* unreadable status lines ("Macro cycle bottom · 2 signals"). The new contract:
*
* * ALWAYS one short sentence — game-tutorial style. Tells the user the
* "what" in plain English, not the "how" (the how lives in InfoTip's).
* * Slightly bigger + higher contrast than page-sub. Meant to be read,
* not glanced past.
* * Optional `count` slot for the dim stat ("2 signals", "30 posts").
* Renders muted after a separator so the tagline itself stays clean.
*/
export default function PageHint({
children,
count,
}: {
children: React.ReactNode
count?: string
}) {
return (
<p className="page-hint">
{children}
{count && <span className="page-hint-count">{count}</span>}
</p>
)
}
+233
View File
@@ -0,0 +1,233 @@
'use client'
import React from 'react'
interface PaginationProps {
page: number
total: number // total pages
count: number // total items
pageSize: number
onChange: (page: number) => void
/** Scroll to top on page change. Default true. */
scrollTop?: boolean
}
/**
* Shared pagination control used across all list pages.
*
* Visual design:
* ‹ 1 2 … 5 [6] 7 … 12 › Showing 151–180 of 340
*
* Active page uses brand orange. Ellipsis collapses distant pages.
* Prev/Next disabled at boundaries (dimmed, not hidden).
*/
export default function Pagination({
page,
total,
count,
pageSize,
onChange,
scrollTop = true,
}: PaginationProps) {
if (total <= 1) return null
const from = (page - 1) * pageSize + 1
const to = Math.min(page * pageSize, count)
function go(p: number) {
if (p < 1 || p > total || p === page) return
onChange(p)
if (scrollTop) window.scrollTo({ top: 0, behavior: 'smooth' })
}
/** Page number list with ellipsis compression. */
function pages(): (number | '…')[] {
if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1)
const out: (number | '…')[] = []
const push = (n: number | '…') => {
if (out[out.length - 1] !== n) out.push(n)
}
push(1)
if (page > 3) push('…')
for (let i = Math.max(2, page - 1); i <= Math.min(total - 1, page + 1); i++) push(i)
if (page < total - 2) push('…')
push(total)
return out
}
return (
<div style={wrapStyle}>
{/* ← Prev */}
<NavBtn onClick={() => go(page - 1)} disabled={page === 1} label="Previous page">
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path
d="M9 11L5 7l4-4"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
<span>Prev</span>
</NavBtn>
{/* Page numbers */}
<div style={numsStyle}>
{pages().map((n, i) =>
n === '…' ? (
<span key={`e${i}`} style={ellipsisStyle}>
…
</span>
) : (
<PageBtn key={n} num={n as number} active={n === page} onClick={go} />
),
)}
</div>
{/* Next → */}
<NavBtn onClick={() => go(page + 1)} disabled={page === total} label="Next page">
<span>Next</span>
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path
d="M5 3l4 4-4 4"
stroke="currentColor"
strokeWidth="1.8"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</NavBtn>
{/* Count */}
<span style={countStyle}>
{from}–{to} <span style={{ opacity: 0.5 }}>of</span> {count.toLocaleString()}
</span>
</div>
)
}
// ── Sub-components ────────────────────────────────────────────────────────────
function PageBtn({
num,
active,
onClick,
}: {
num: number
active: boolean
onClick: (n: number) => void
}) {
const [hover, setHover] = React.useState(false)
const bg = active ? 'var(--amber)' : hover ? 'var(--bg-sunk)' : 'transparent'
const color = active ? '#fff' : hover ? 'var(--ink)' : 'var(--ink-2)'
const border = active ? '1.5px solid var(--amber)' : '1.5px solid var(--line)'
return (
<button
onClick={() => onClick(num)}
onMouseEnter={() => setHover(true)}
onMouseLeave={() => setHover(false)}
aria-current={active ? 'page' : undefined}
style={{
width: 34,
height: 34,
display: 'inline-flex',
alignItems: 'center',
justifyContent: 'center',
borderRadius: 8,
border,
background: bg,
color,
fontSize: 13,
fontWeight: active ? 700 : 400,
cursor: 'pointer',
transition: 'background 0.12s, color 0.12s, border-color 0.12s',
boxShadow: active ? '0 1px 4px rgba(245,165,36,0.25)' : 'none',
flexShrink: 0,
}}
>
{num}
</button>
)
}
function NavBtn({
onClick,
disabled,
label,
children,
}: {
onClick: () => void
disabled: boolean
label: string
children: React.ReactNode
}) {
const [hover, setHover] = React.useState(false)
return (
<button
onClick={onClick}
disabled={disabled}
aria-label={label}
onMouseEnter={() => !disabled && setHover(true)}
onMouseLeave={() => setHover(false)}
style={{
display: 'inline-flex',
alignItems: 'center',
gap: 5,
height: 34,
padding: '0 12px',
borderRadius: 8,
border: '1.5px solid var(--line)',
background: hover && !disabled ? 'var(--bg-sunk)' : 'transparent',
color: disabled ? 'var(--ink-4)' : hover ? 'var(--ink)' : 'var(--ink-2)',
fontSize: 12,
fontWeight: 500,
cursor: disabled ? 'not-allowed' : 'pointer',
transition: 'background 0.12s, color 0.12s',
flexShrink: 0,
}}
>
{children}
</button>
)
}
// ── Styles ────────────────────────────────────────────────────────────────────
const wrapStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
padding: '28px 0 8px',
flexWrap: 'wrap',
}
const numsStyle: React.CSSProperties = {
display: 'flex',
alignItems: 'center',
gap: 4,
flexWrap: 'wrap',
justifyContent: 'center',
}
const ellipsisStyle: React.CSSProperties = {
width: 28,
textAlign: 'center',
fontSize: 13,
color: 'var(--ink-4)',
userSelect: 'none',
flexShrink: 0,
}
const countStyle: React.CSSProperties = {
fontSize: 11,
color: 'var(--ink-3)',
fontVariantNumeric: 'tabular-nums',
marginLeft: 6,
whiteSpace: 'nowrap',
}
+202
View File
@@ -0,0 +1,202 @@
'use client'
import { useState, useEffect, useCallback } from 'react'
import { useAccount } from 'wagmi'
import { useWsSubscribe } from '@/lib/wsContext'
interface TradeAlert {
id: number
event:
| 'execution_failed'
| 'insufficient_balance'
| 'budget_reached'
| 'reconcile_drift'
| 'circuit_breaker_tripped'
asset?: string
reason?: string
balance_usd?: number
required_usd?: number
spent_usd?: number
cap_usd?: number
// reconcile_drift fields (from reconciler.py broadcast)
// orphan_hl is a list of {asset, trade_id} dicts, NOT a number
orphan_hl?: unknown[]
marked_closed?: number
ghost_positions?: unknown[]
// circuit_breaker_tripped fields (from circuit_breaker.py broadcast)
system?: string
cb_reason?: string
unlock_at?: string
}
// How long each alert stays visible before auto-dismissing.
const AUTO_DISMISS_MS = 10_000
function alertMessage(alert: TradeAlert): string {
switch (alert.event) {
case 'execution_failed':
return `Auto-trade failed${alert.asset ? ` on ${alert.asset}` : ''}${alert.reason ? `: ${alert.reason}` : ''}. Check your HL API key and account status.`
case 'insufficient_balance':
return `Insufficient balance to open${alert.asset ? ` ${alert.asset}` : ''}: account has $${alert.balance_usd?.toFixed(2) ?? '?'}, trade requires $${alert.required_usd?.toFixed(2) ?? '?'}. Top up your Hyperliquid account.`
case 'budget_reached':
return `Daily budget reached${alert.asset ? ` (${alert.asset})` : ''}: $${alert.spent_usd?.toFixed(0) ?? '?'} spent of $${alert.cap_usd?.toFixed(0) ?? '?'} cap. No more trades today.`
// B47: reconciler detects DB ↔ HL mismatch (ghost/orphan position)
case 'reconcile_drift': {
const parts = []
const orphanCount = (alert.orphan_hl as unknown[])?.length ?? 0
if (orphanCount > 0) parts.push(`${orphanCount} orphan(s) on HL`)
if (alert.marked_closed) parts.push(`${alert.marked_closed} auto-closed`)
if ((alert.ghost_positions as unknown[])?.length)
parts.push(`${(alert.ghost_positions as unknown[]).length} ghost(s)`)
return `Position drift detected: ${parts.join(', ') || 'mismatch between DB and HL'}. Check your Hyperliquid account.`
}
// B53: circuit breaker fired — Auto-Trade suspended
case 'circuit_breaker_tripped':
return `Circuit breaker tripped${alert.system ? ` (${alert.system})` : ''}${alert.cb_reason ? `: ${alert.cb_reason}` : ''}. Auto-Trade suspended — turn it back ON on the Trump page to acknowledge and resume.`
default:
return 'Auto-trade event — check your account.'
}
}
let _seq = 0
export default function TradeAlertBanner() {
const { address } = useAccount()
const [alerts, setAlerts] = useState<TradeAlert[]>([])
const dismiss = useCallback((id: number) => {
setAlerts((prev) => prev.filter((a) => a.id !== id))
}, [])
// Auto-dismiss each alert after AUTO_DISMISS_MS.
// Effect re-runs whenever the alert list changes. For each alert we schedule
// a timeout; cleanup cancels all pending timers when the list updates or
// the component unmounts — prevents a dismissed-then-re-added alert from
// triggering a ghost dismiss.
useEffect(() => {
if (alerts.length === 0) return
const timers = alerts.map((a) => window.setTimeout(() => dismiss(a.id), AUTO_DISMISS_MS))
return () => timers.forEach(clearTimeout)
}, [alerts, dismiss])
useWsSubscribe(
'trade_alert',
useCallback(
(raw) => {
const msg = raw as { wallet?: string; event?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
const alert = { id: ++_seq, ...msg } as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
// B47: reconcile_drift — DB↔HL position mismatch flagged by the reconciler.
useWsSubscribe(
'reconcile_drift',
useCallback(
(raw) => {
const msg = raw as { wallet?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
const alert = { id: ++_seq, event: 'reconcile_drift' as const, ...msg } as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
// B53: circuit_breaker_tripped — Auto-Trade suspended by the CB.
useWsSubscribe(
'circuit_breaker_tripped',
useCallback(
(raw) => {
const msg = raw as { wallet?: string; reason?: string } & Record<string, unknown>
if (!address || msg.wallet?.toLowerCase() !== address.toLowerCase()) return
// Rename 'reason' → 'cb_reason' to avoid collision with the trade_alert 'reason' field.
const { reason: cb_reason, ...rest } = msg
const alert = {
id: ++_seq,
event: 'circuit_breaker_tripped' as const,
cb_reason,
...rest,
} as TradeAlert
setAlerts((prev) => [alert, ...prev].slice(0, 3))
},
[address],
),
)
if (alerts.length === 0) return null
return (
<>
<style>{`
@keyframes tradeAlertIn {
from { opacity: 0; transform: translateX(-50%) translateY(-8px); }
to { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes tradeAlertOut {
from { opacity: 1; }
to { opacity: 0; }
}
`}</style>
<div
style={{
position: 'fixed',
top: 60,
left: '50%',
transform: 'translateX(-50%)',
zIndex: 9999,
display: 'flex',
flexDirection: 'column',
gap: 8,
width: 'min(480px, calc(100vw - 32px))',
pointerEvents: 'none',
animation: 'tradeAlertIn 0.2s ease',
}}
>
{alerts.map((alert) => (
<div
key={alert.id}
style={{
display: 'flex',
alignItems: 'flex-start',
gap: 10,
padding: '12px 14px',
borderRadius: 10,
background: 'var(--bg)',
border: '1px solid var(--down)',
boxShadow: '0 4px 20px rgba(0,0,0,.3)',
pointerEvents: 'auto',
}}
>
<span style={{ fontSize: 16, flexShrink: 0, marginTop: 1 }}>⚠️</span>
<div style={{ flex: 1, fontSize: 12, lineHeight: 1.5, color: 'var(--ink)' }}>
<strong style={{ color: 'var(--down)', display: 'block', marginBottom: 2 }}>
Auto-trade blocked
</strong>
{alertMessage(alert)}
</div>
<button
onClick={() => dismiss(alert.id)}
style={{
flexShrink: 0,
padding: 0,
border: 'none',
background: 'transparent',
cursor: 'pointer',
color: 'var(--ink-4)',
fontSize: 16,
lineHeight: 1,
}}
aria-label="Dismiss"
>
×
</button>
</div>
))}
</div>
</>
)
}
@@ -0,0 +1,219 @@
'use client'
/**
* MobileWalletSheet — bottom-drawer shown on mobile when no injected wallet
* is detected. Offers deep links to common mobile wallets so the user can
* open MetaMask (or Trust / Coinbase / OKX) and land directly on this dApp.
*
* Rendered as a fixed overlay + slide-up panel. Backdrop tap dismisses it.
* The CSS animation class `mobile-sheet-enter` is defined in globals.css.
*
* Usage:
* <MobileWalletSheet open={open} onClose={() => setOpen(false)} />
*/
import { useEffect, useState } from 'react'
import { getWalletLinks } from '@/lib/mobileWallet'
import type { WalletLink } from '@/lib/mobileWallet'
interface Props {
open: boolean
onClose: () => void
}
export default function MobileWalletSheet({ open, onClose }: Props) {
const [links, setLinks] = useState<WalletLink[]>([])
// Build deep links client-side only (needs window.location.href).
useEffect(() => {
if (open) {
setLinks(getWalletLinks(window.location.href))
}
}, [open])
// Lock body scroll while sheet is open.
useEffect(() => {
if (open) {
document.body.style.overflow = 'hidden'
return () => {
document.body.style.overflow = ''
}
}
}, [open])
// Escape key closes.
useEffect(() => {
if (!open) return
function onKey(e: KeyboardEvent) {
if (e.key === 'Escape') onClose()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onClose])
if (!open) return null
return (
/* Backdrop */
<div
style={{
position: 'fixed',
inset: 0,
zIndex: 9000,
background: 'rgba(0,0,0,0.55)',
display: 'flex',
alignItems: 'flex-end',
backdropFilter: 'blur(4px)',
WebkitBackdropFilter: 'blur(4px)',
}}
onClick={onClose}
aria-modal="true"
role="dialog"
aria-label="Connect a wallet"
>
{/* Sheet */}
<div
className="mobile-sheet-enter"
style={{
width: '100%',
background: 'var(--bg-elev)',
borderRadius: '20px 20px 0 0',
padding: '20px 20px 32px',
boxShadow: '0 -8px 40px rgba(0,0,0,0.18)',
maxHeight: '80vh',
overflowY: 'auto',
}}
onClick={(e) => e.stopPropagation()}
>
{/* Handle bar */}
<div
style={{
width: 40,
height: 4,
background: 'var(--line-2)',
borderRadius: 99,
margin: '0 auto 20px',
}}
/>
{/* Header */}
<div style={{ marginBottom: 20 }}>
<div style={{ fontSize: 18, fontWeight: 700, letterSpacing: '-0.01em', marginBottom: 4 }}>
Connect a wallet
</div>
<div style={{ fontSize: 13, color: 'var(--ink-3)', lineHeight: 1.5 }}>
Open the dApp inside your wallet's built-in browser to connect.
</div>
</div>
{/* Wallet list */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
{links.map((link) => (
<a
key={link.name}
href={link.href}
target="_blank"
rel="noopener noreferrer"
style={{
display: 'flex',
alignItems: 'center',
gap: 14,
padding: '14px 16px',
borderRadius: 'var(--r-md)',
border: '1px solid var(--line)',
background: 'var(--surface)',
textDecoration: 'none',
color: 'inherit',
transition: 'background 120ms, border-color 120ms',
}}
onTouchStart={(e) => {
;(e.currentTarget as HTMLAnchorElement).style.background = 'var(--bg-sunk)'
}}
onTouchEnd={(e) => {
;(e.currentTarget as HTMLAnchorElement).style.background = 'var(--surface)'
}}
>
{/* Icon */}
<div
style={{
width: 44,
height: 44,
borderRadius: 12,
background: link.color,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: link.abbr.length > 2 ? 12 : 20,
fontWeight: 700,
color: '#fff',
flexShrink: 0,
letterSpacing: '-0.01em',
}}
>
{link.abbr}
</div>
{/* Text */}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 15, fontWeight: 600, marginBottom: 2 }}>{link.name}</div>
<div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{link.hint}</div>
</div>
{/* Arrow */}
<svg
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
style={{ color: 'var(--ink-3)', flexShrink: 0 }}
>
<path
d="M9 18l6-6-6-6"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
</a>
))}
</div>
{/* WalletConnect note */}
<div
style={{
marginTop: 18,
padding: '12px 14px',
borderRadius: 'var(--r-sm)',
background: 'var(--bg-sunk)',
fontSize: 12,
color: 'var(--ink-3)',
lineHeight: 1.55,
}}
>
<strong style={{ color: 'var(--ink-2)' }}>Already in your wallet's browser?</strong> Tap
Cancel to dismiss, then use the built-in browser navigation to reload the page — MetaMask
should auto-detect the dApp.
</div>
{/* Close */}
<button
onClick={onClose}
style={{
marginTop: 14,
width: '100%',
padding: '14px',
borderRadius: 'var(--r-md)',
background: 'var(--bg-sunk)',
border: '1px solid var(--line)',
fontSize: 14,
fontWeight: 500,
color: 'var(--ink-2)',
}}
>
Cancel
</button>
</div>
</div>
)
}
@@ -0,0 +1,259 @@
'use client'
/**
* SignConfirmSheet — elegant pre-signing confirmation UI.
*
* Usage (imperative, no context needed):
*
* import { confirmSign } from '@/components/wallet/SignConfirmSheet'
*
* const ok = await confirmSign({
* label: 'Enable Auto-Trade',
* description: 'Bot will open live trades on Hyperliquid when signals fire.',
* danger: true,
* })
* if (!ok) return // user cancelled
* const env = await signRequest(...) // only NOW triggers MetaMask
*/
import { createRoot } from 'react-dom/client'
export interface SignConfirmOptions {
/** Short action title, e.g. "Enable Auto-Trade" */
label: string
/** One-sentence explanation shown to the user */
description: string
/** If true, renders a red/warning accent — for irreversible / live-money actions */
danger?: boolean
}
// Track the currently-mounted sheet so a second confirmSign() call can resolve
// the first one with `false` instead of leaving its promise dangling forever.
let _activeCancel: (() => void) | null = null
/** Renders a confirmation sheet and resolves true (confirm) or false (cancel). */
export function confirmSign(opts: SignConfirmOptions): Promise<boolean> {
return new Promise((resolve) => {
// If another sheet is already mounted, cancel it first so its awaiting
// caller resolves with `false` rather than hanging indefinitely.
if (_activeCancel) {
try {
_activeCancel()
} catch {
/* ignore */
}
}
const existing = document.getElementById('sign-confirm-sheet-root')
if (existing?.parentNode) {
existing.parentNode.removeChild(existing)
}
const container = document.createElement('div')
container.id = 'sign-confirm-sheet-root'
document.body.appendChild(container)
const root = createRoot(container)
let settled = false
function cleanup(result: boolean) {
if (settled) return
settled = true
// Clear the active-cancel slot only if it still points to *this* sheet —
// a later confirmSign() may have already replaced it.
if (_activeCancel === cancelSelf) _activeCancel = null
root.unmount()
if (container.parentNode) {
container.parentNode.removeChild(container)
}
resolve(result)
}
// Stable reference used both as the active-cancel handle and inside cleanup.
const cancelSelf = () => cleanup(false)
_activeCancel = cancelSelf
root.render(<Sheet {...opts} onConfirm={() => cleanup(true)} onCancel={cancelSelf} />)
})
}
/* ─── Internal sheet component ─────────────────────────────────────────────── */
function Sheet({
label,
description,
danger,
onConfirm,
onCancel,
}: SignConfirmOptions & { onConfirm: () => void; onCancel: () => void }) {
const accent = danger ? '#ef4444' : '#f5a524'
const accentSoft = danger ? 'rgba(239,68,68,0.1)' : 'rgba(245,165,36,0.1)'
// Dismiss on backdrop click
function handleBackdrop(e: React.MouseEvent<HTMLDivElement>) {
if (e.target === e.currentTarget) onCancel()
}
// Dismiss on Escape
function handleKey(e: React.KeyboardEvent) {
if (e.key === 'Escape') onCancel()
}
return (
<div
onClick={handleBackdrop}
onKeyDown={handleKey}
role="dialog"
aria-modal="true"
aria-label={label}
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0,0,0,0.70)',
backdropFilter: 'blur(3px)',
WebkitBackdropFilter: 'blur(3px)',
zIndex: 99999,
display: 'flex',
alignItems: 'flex-end',
justifyContent: 'center',
padding: '0 0 env(safe-area-inset-bottom, 0)',
}}
>
<div
style={{
width: '100%',
maxWidth: 480,
background: '#111',
borderRadius: '16px 16px 0 0',
border: '1px solid #2a2a2a',
borderBottom: 'none',
padding: '28px 24px 32px',
boxShadow: '0 -12px 48px rgba(0,0,0,0.5)',
animation: 'signSheetIn 0.22s cubic-bezier(0.32,0.72,0,1)',
}}
>
{/* 拖拽条 */}
<div
style={{
width: 36,
height: 4,
borderRadius: 2,
background: '#333',
margin: '0 auto 24px',
}}
/>
{/* 图标 + 标题 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
<div
style={{
width: 40,
height: 40,
borderRadius: 10,
background: accentSoft,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: 20,
flexShrink: 0,
}}
>
🔏
</div>
<div>
<div
style={{
fontSize: 11,
color: '#666',
letterSpacing: '0.07em',
textTransform: 'uppercase',
marginBottom: 2,
}}
>
Wallet signature required
</div>
<div style={{ fontSize: 17, fontWeight: 700, color: '#fff', lineHeight: 1.2 }}>
{label}
</div>
</div>
</div>
{/* 说明文字 */}
<div
style={{
fontSize: 14,
color: '#999',
lineHeight: 1.6,
margin: '16px 0 24px',
paddingLeft: 52, // 与标题对齐
}}
>
{description}
</div>
{/* 说明条 */}
<div
style={{
padding: '10px 12px',
borderRadius: 8,
background: 'rgba(255,255,255,0.04)',
border: '1px solid #2a2a2a',
fontSize: 12,
color: '#666',
lineHeight: 1.5,
marginBottom: 20,
}}
>
Signing is used only to verify your identity. It will NOT authorize any on-chain transfer
and will NOT cost any gas. The MetaMask popup will appear after you click Confirm.
</div>
{/* 按钮组 */}
<div style={{ display: 'flex', gap: 10 }}>
<button
onClick={onCancel}
style={{
flex: 1,
padding: '12px 0',
borderRadius: 10,
border: '1px solid #2a2a2a',
background: 'transparent',
color: '#888',
fontSize: 14,
fontWeight: 600,
cursor: 'pointer',
}}
>
Cancel
</button>
<button
onClick={onConfirm}
autoFocus
style={{
flex: 2,
padding: '12px 0',
borderRadius: 10,
border: 'none',
background: accent,
color: danger ? '#fff' : '#000',
fontSize: 14,
fontWeight: 700,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: 6,
}}
>
<span>Open MetaMask</span>
<span style={{ opacity: 0.7, fontSize: 16 }}>→</span>
</button>
</div>
</div>
<style>{`
@keyframes signSheetIn {
from { transform: translateY(100%); opacity: 0; }
to { transform: translateY(0); opacity: 1; }
}
`}</style>
</div>
)
}