fix: pre-launch UI hardening + KOL reduce-action type, proxy IP relay, settings redesign

Frontend half of the pre-launch audit campaign:

- types/index.ts + kol/KolPageClient.tsx: add missing 'reduce' KolAction
  (backend emits it; frontend lacked the type + color/label maps → undefined
  styling). Adds ACTION_COLOR/actionLabel/postActionLabel entries.
- proxy/[...path]/route.ts: relay real client IP (x-forwarded-for / x-real-ip)
  so the backend rate limiter buckets per-user instead of per-Next-server (BUG-02).
- Settings/BotConfigPanel redesign, paper-mode clarity, copy cleanup.
- Assorted page/display fixes, loading states, Pagination component.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
k
2026-05-29 11:57:43 +08:00
parent b76de36af0
commit d50c05b120
32 changed files with 1003 additions and 224 deletions
+60 -2
View File
@@ -166,8 +166,10 @@ Tokens in `app/[locale]/globals.css`:
## Things that LOOK like bugs but aren't ## Things that LOOK like bugs but aren't
- **Old code references "/en/btc"** — Macro Vibes was renamed from "BTC - **Old code references "/en/btc"** — Macro Vibes was renamed from "BTC
Signal" in v2.0. All routes are now `/en/macro`. If you find a stale Signal" in v2.0. All routes are now `/en/macro`. `app/[locale]/btc/page.tsx`
`/en/btc` reference, it's a real bug — fix it (we've found and fixed 3). EXISTS intentionally as a permanent redirect to `/en/macro` — that's fine.
If you find a stale `/en/btc` hardcoded link anywhere else, it's a real
bug — fix it.
- **`isZh = false` in metadata generators** — i18n was shelved pre-launch. - **`isZh = false` in metadata generators** — i18n was shelved pre-launch.
See "Stack quirks" above. See "Stack quirks" above.
- **Multiple `proxy.ts` patterns** — Next.js 16 split middleware behaviour. - **Multiple `proxy.ts` patterns** — Next.js 16 split middleware behaviour.
@@ -175,9 +177,65 @@ Tokens in `app/[locale]/globals.css`:
- **`'use client'` directives on many pages** — necessary for client-side - **`'use client'` directives on many pages** — necessary for client-side
WS / wallet interactions. Don't try to convert without verifying the WS WS / wallet interactions. Don't try to convert without verifying the WS
+ wagmi imports work in server components. + wagmi imports work in server components.
- **`telegram.send_message` accepting `int | str` for chat_id** — the backend
uses string form for the public channel (`"@trumpalpha"`) and integer for
private user chats. Both are valid; no frontend change needed.
- **`x-forwarded-for` is deleted in the proxy** — KNOWN BUG (see below).
Don't "fix" it by just removing the delete; the correct fix is to relay the
real client IP. See Open Known Issues.
--- ---
## Open known issues (frontend)
- ~~**Rate limit bypass via proxy** (FIXED 2026-05-29):~~ `route.ts` no longer
deletes `x-forwarded-for`. It now reads the real client IP from the incoming
`x-forwarded-for` or `x-real-ip` header (set by Vercel/CDN) and sets it on
the upstream request so `slowapi` can distinguish individual clients.
- ~~**`signMessageAsync` in `OpenPositions` polling deps** (MEDIUM, FIXED 2026-05-29):~~
Removed `signMessageAsync` and `isZh` from the `useEffect` dependency array
in `components/positions/OpenPositions.tsx`. Neither is used inside the effect;
including them caused wagmi reference churn to restart the 15s poll timer.
- ~~**Stale types after BUG-08/BUG-14** (FE-0106, FIXED 2026-05-29):~~
- `types/index.ts`: `price_impact.asset` widened from `'BTC' | 'ETH'` to
`string` (BUG-14 now tracks the actually-traded asset which may be
SOL/TRUMP/etc.).
- `lib/useRealtimeData.ts`: `PriceMsg.asset` and `Handlers.onPrice` widened
to `string` (BUG-08 expanded the WS price stream to all ASSET_MAP entries).
- `store/dashboard.ts`: `livePrices` changed from `{ BTC; ETH }` to
`Record<string, number | null>`; `setLivePrice` param widened to `string`.
- `lib/api.ts`: `getPrices` asset param widened to `string`.
- `components/trades/TradeTable.tsx`: hardcoded `ASSETS = ['all','BTC','ETH','SOL']`
replaced by a dynamic `useMemo` that builds the asset list from the actual
trade set — new perps (TRUMP, BNB, etc.) appear in the filter automatically.
- `DashboardClient.tsx` + `TradesPageClient.tsx`: removed `isZh` from
`useEffect` deps (compile-time constant; including it restarted effects
on every render).
- ~~**Interaction/button bugs sweep** (UI-A..G, FIXED 2026-05-29):~~
- **A** `OpenPositions.tsx` close-modal backdrop now dismisses in `'err'`
state too (previously stuck — only `'idle'` dismissed). State is reset on
dismiss so the next open is clean.
- **B** `confirmCloseTrade` distinguishes user-cancelled signature
(`isUserRejection`) from real failure: cancellation closes the modal
silently; real errors stay open in `'err'` state with the message.
- **C** `SystemControl.flipAuto` claims `busy=true` **before** `await
confirmSign(...)`. Rapid double-click on the ON/OFF pill no longer slips
past the guard. The slot is released if the user cancels the sheet.
- **D** `BotConfigPanel` "Rotate" API-key button resets `keyState`/`keyErr`
so a previously-failed save's red error doesn't bleed into the new edit.
- **E** Paper/Live `Switch` clears `subErr` when toggled so a stale
subscribe-error doesn't sit next to the new choice.
- **F** `confirmSign` keeps a module-scope `_activeCancel`; a second call
while a sheet is mounted resolves the first promise with `false` instead
of leaving its caller hanging forever. All 9 call sites verified to
cleanly handle the `false` return (`setBusy(false)` / `setLoadState('idle')`).
- **G** `OpenPositions.toggleGrow` errors now write to a dedicated
`growErr` state with a 4-second auto-clear, instead of squatting in the
panel-header `err` banner shared with the 15-s poll error.
## How to verify changes locally ## How to verify changes locally
```bash ```bash
+12 -2
View File
@@ -1,6 +1,7 @@
'use client' 'use client'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import dynamic from 'next/dynamic'
import Link from 'next/link' import Link from 'next/link'
import { useParams } from 'next/navigation' import { useParams } from 'next/navigation'
import { useLocale } from 'next-intl' import { useLocale } from 'next-intl'
@@ -11,11 +12,17 @@ import { usePriceSocket } from '@/lib/useRealtimeData'
import { getMacroSnapshot, getPerformance, getPrices, getUserPublic, type MacroSnapshot } from '@/lib/api' import { getMacroSnapshot, getPerformance, getPrices, getUserPublic, type MacroSnapshot } from '@/lib/api'
import { getCachedViewEnvelope } from '@/lib/signedRequest' import { getCachedViewEnvelope } from '@/lib/signedRequest'
import { swrFetch } from '@/lib/cache' import { swrFetch } from '@/lib/cache'
import ChartPanel from '@/components/dashboard/ChartPanel'
import PostRow, { SignalPill, SourceIcon, fmtPct, TimeAgo, LocalDateTime } from '@/components/dashboard/PostCards' import PostRow, { SignalPill, SourceIcon, fmtPct, TimeAgo, LocalDateTime } from '@/components/dashboard/PostCards'
import OpenPositions from '@/components/positions/OpenPositions' import OpenPositions from '@/components/positions/OpenPositions'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
// Heavy components — lazy-loaded so they don't bloat the initial JS bundle.
// ChartPanel pulls in lightweight-charts (~200KB gz); split it out.
const ChartPanel = dynamic(() => import('@/components/dashboard/ChartPanel'), {
ssr: false,
loading: () => <div style={{ height: 320, background: 'var(--bg-sunk)', borderRadius: 12, marginBottom: 16 }} />,
})
interface Props { interface Props {
initialPosts: TrumpPost[] initialPosts: TrumpPost[]
} }
@@ -211,7 +218,10 @@ export default function DashboardClient({ initialPosts }: Props) {
getPrices(asset, timeframe) getPrices(asset, timeframe)
.then(c => { setCandles(c); setChartErr('') }) .then(c => { setCandles(c); setChartErr('') })
.catch(e => setChartErr(e instanceof Error ? e.message : (isZh ? '价格数据加载失败' : 'Failed to load price data'))) .catch(e => setChartErr(e instanceof Error ? e.message : (isZh ? '价格数据加载失败' : 'Failed to load price data')))
}, [asset, timeframe, chartReload, isZh]) // isZh intentionally excluded: it is a compile-time constant (always false)
// and including it would restart the chart fetch on every render.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [asset, timeframe, chartReload])
useEffect(() => { useEffect(() => {
let alive = true let alive = true
+21 -5
View File
@@ -6,6 +6,9 @@ import type { TrumpPost } from '@/types'
import { getPosts } from '@/lib/api' import { getPosts } from '@/lib/api'
import PostRow from '@/components/dashboard/PostCards' import PostRow from '@/components/dashboard/PostCards'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
import Pagination from '@/components/ui/Pagination'
const ARCHIVE_PAGE_SIZE = 30
const LIVE_SOURCES = new Set([ const LIVE_SOURCES = new Set([
'truth', 'truth',
@@ -25,6 +28,7 @@ export default function ArchivePage() {
const [loading, setLoading] = useState(true) const [loading, setLoading] = useState(true)
const [loadErr, setLoadErr] = useState('') const [loadErr, setLoadErr] = useState('')
const [src, setSrc] = useState<string>('all') const [src, setSrc] = useState<string>('all')
const [archivePage, setArchivePage] = useState(1)
useEffect(() => { useEffect(() => {
getPosts(500, 1) getPosts(500, 1)
@@ -49,6 +53,9 @@ export default function ArchivePage() {
() => src === 'all' ? archivePosts : archivePosts.filter(p => p.source === src), () => src === 'all' ? archivePosts : archivePosts.filter(p => p.source === src),
[archivePosts, src], [archivePosts, src],
) )
const archiveTotalPages = Math.max(1, Math.ceil(filtered.length / ARCHIVE_PAGE_SIZE))
const archiveSafePage = Math.min(archivePage, archiveTotalPages)
const archivePageItems = filtered.slice((archiveSafePage - 1) * ARCHIVE_PAGE_SIZE, archiveSafePage * ARCHIVE_PAGE_SIZE)
return ( return (
<div className="page"> <div className="page">
@@ -67,7 +74,7 @@ export default function ArchivePage() {
{[['all', archivePosts.length] as [string, number], ...sources].map(([s, n]) => ( {[['all', archivePosts.length] as [string, number], ...sources].map(([s, n]) => (
<button <button
key={s} key={s}
onClick={() => setSrc(s)} onClick={() => { setSrc(s); setArchivePage(1) }}
style={{ style={{
padding: '4px 10px', borderRadius: 6, border: '1px solid var(--line)', padding: '4px 10px', borderRadius: 6, border: '1px solid var(--line)',
background: src === s ? 'var(--ink)' : 'transparent', background: src === s ? 'var(--ink)' : 'transparent',
@@ -95,10 +102,19 @@ export default function ArchivePage() {
{isZh ? '' : 'No archived signals.'} {isZh ? '' : 'No archived signals.'}
</div> </div>
)} )}
{!loading && filtered.length > 0 && ( {!loading && archivePageItems.length > 0 && (
<div className="post-stream"> <>
{filtered.map(p => <PostRow key={p.id} post={p} />)} <div className="post-stream">
</div> {archivePageItems.map(p => <PostRow key={p.id} post={p} />)}
</div>
<Pagination
page={archiveSafePage}
total={archiveTotalPages}
count={filtered.length}
pageSize={ARCHIVE_PAGE_SIZE}
onChange={setArchivePage}
/>
</>
)} )}
</div> </div>
) )
+8 -8
View File
@@ -363,7 +363,7 @@ html[data-theme="dark"] .asset-switch button.on { background: var(--surface-2);
.page { .page {
max-width: 1360px; max-width: 1360px;
margin: 0 auto; margin: 0 auto;
padding: 32px 28px 80px; padding: 28px 28px 64px;
width: 100%; width: 100%;
} }
.page.wide { max-width: 1600px; } .page.wide { max-width: 1600px; }
@@ -372,20 +372,20 @@ html[data-theme="dark"] .asset-switch button.on { background: var(--surface-2);
display: flex; display: flex;
align-items: flex-end; align-items: flex-end;
justify-content: space-between; justify-content: space-between;
margin-bottom: 28px; margin-bottom: 24px;
gap: 24px; gap: 24px;
} }
.page-title { .page-title {
font-size: 34px; font-size: 28px;
letter-spacing: -0.02em; letter-spacing: -0.025em;
font-weight: 600; font-weight: 700;
line-height: 1.05; line-height: 1.1;
margin: 0; margin: 0;
} }
.page-sub { .page-sub {
color: var(--ink-3); color: var(--ink-3);
font-size: 14px; font-size: 13px;
margin-top: 6px; margin-top: 5px;
margin-bottom: 0; margin-bottom: 0;
} }
+26 -5
View File
@@ -10,6 +10,7 @@ import type {
import { getKolPosts, getKolPost, getKolDigest, getKolChanges, getKolDivergence } from '@/lib/api' import { getKolPosts, getKolPost, getKolDigest, getKolChanges, getKolDivergence } from '@/lib/api'
import { swrFetch } from '@/lib/cache' import { swrFetch } from '@/lib/cache'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
import Pagination from '@/components/ui/Pagination'
/** /**
* KOL feed — independent module. Lists analyzed posts from tracked KOLs * KOL feed — independent module. Lists analyzed posts from tracked KOLs
@@ -22,6 +23,7 @@ const ACTION_COLOR: Record<KolTicker['action'], string> = {
bullish: '#16a34a', bullish: '#16a34a',
sell: '#dc2626', sell: '#dc2626',
bearish: '#dc2626', bearish: '#dc2626',
reduce: '#f59e0b',
mention: '#9ca3af', mention: '#9ca3af',
} }
@@ -31,6 +33,7 @@ function actionLabel(action: KolTicker['action'], isZh: boolean) {
const labels: Record<KolTicker['action'], string> = { const labels: Record<KolTicker['action'], string> = {
buy: 'BUY', buy: 'BUY',
sell: 'SELL', sell: 'SELL',
reduce: 'Reduce',
bullish: 'Bullish', bullish: 'Bullish',
bearish: 'Bearish', bearish: 'Bearish',
mention: 'Mention', mention: 'Mention',
@@ -78,6 +81,7 @@ function postActionLabel(action: string, isZh: boolean) {
const labels: Record<string, string> = { const labels: Record<string, string> = {
buy: 'BUY', buy: 'BUY',
sell: 'SELL', sell: 'SELL',
reduce: 'Reducing',
bullish: 'Bullish post', bullish: 'Bullish post',
bearish: 'Bearish post', bearish: 'Bearish post',
} }
@@ -780,12 +784,14 @@ export default function KolPage({
const locale = useLocale() const locale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json
const dateLocale = isZh ? 'zh-CN' : 'en-US' const dateLocale = isZh ? 'zh-CN' : 'en-US'
const KOL_PAGE_SIZE = 20
const [posts, setPosts] = useState<KolPostSummary[]>(initialPosts ?? []) const [posts, setPosts] = useState<KolPostSummary[]>(initialPosts ?? [])
const [loading, setLoading] = useState(initialPosts === null) const [loading, setLoading] = useState(initialPosts === null)
const [err, setErr] = useState('') const [err, setErr] = useState('')
const [openPost, setOpenPost] = useState<KolPostDetail | null>(null) const [openPost, setOpenPost] = useState<KolPostDetail | null>(null)
const [handleFilter, setHandleFilter] = useState<string>('all') const [handleFilter, setHandleFilter] = useState<string>('all')
const [tickerFilter, setTickerFilter] = useState<string | null>(null) const [tickerFilter, setTickerFilter] = useState<string | null>(null)
const [kolPage, setKolPage] = useState(1)
useEffect(() => { useEffect(() => {
swrFetch( swrFetch(
@@ -812,6 +818,10 @@ export default function KolPage({
return out return out
}, [posts, handleFilter, tickerFilter]) }, [posts, handleFilter, tickerFilter])
const kolTotalPages = Math.max(1, Math.ceil(filtered.length / KOL_PAGE_SIZE))
const kolSafePage = Math.min(kolPage, kolTotalPages)
const kolPageItems = filtered.slice((kolSafePage - 1) * KOL_PAGE_SIZE, kolSafePage * KOL_PAGE_SIZE)
async function openDetail(id: number) { async function openDetail(id: number) {
try { try {
const detail = await getKolPost(id) const detail = await getKolPost(id)
@@ -837,8 +847,10 @@ export default function KolPage({
isZh={isZh} isZh={isZh}
initialDigest={initialDigest} initialDigest={initialDigest}
activeTicker={tickerFilter} activeTicker={tickerFilter}
onTickerClick={(sym) => onTickerClick={(sym) => {
setTickerFilter(prev => prev === sym ? null : sym)} setTickerFilter(prev => prev === sym ? null : sym)
setKolPage(1)
}}
/> />
<WalletCheckWidget <WalletCheckWidget
@@ -858,7 +870,7 @@ export default function KolPage({
<span style={{ color: 'var(--ink-3)' }}>{isZh ? '当前筛选标的:' : 'Filtered asset:'}</span> <span style={{ color: 'var(--ink-3)' }}>{isZh ? '当前筛选标的:' : 'Filtered asset:'}</span>
<strong>{tickerFilter}</strong> <strong>{tickerFilter}</strong>
<button <button
onClick={() => setTickerFilter(null)} onClick={() => { setTickerFilter(null); setKolPage(1) }}
style={{ style={{
background: 'var(--bg-sunk)', border: '1px solid var(--line)', background: 'var(--bg-sunk)', border: '1px solid var(--line)',
borderRadius: 4, padding: '2px 8px', borderRadius: 4, padding: '2px 8px',
@@ -873,7 +885,7 @@ export default function KolPage({
{handles.map(h => ( {handles.map(h => (
<button <button
key={h} key={h}
onClick={() => setHandleFilter(h)} onClick={() => { setHandleFilter(h); setKolPage(1) }}
className={`nav-tab ${handleFilter === h ? 'active' : ''}`} className={`nav-tab ${handleFilter === h ? 'active' : ''}`}
style={{ border: 'none', cursor: 'pointer' }} style={{ border: 'none', cursor: 'pointer' }}
> >
@@ -895,7 +907,7 @@ export default function KolPage({
: 'No data yet. Wait for the next feed ingestion run (daily 01:15 UTC).'} : 'No data yet. Wait for the next feed ingestion run (daily 01:15 UTC).'}
</div> </div>
)} )}
{filtered.map(p => ( {kolPageItems.map(p => (
<div <div
key={p.id} key={p.id}
onClick={() => openDetail(p.id)} onClick={() => openDetail(p.id)}
@@ -954,6 +966,15 @@ export default function KolPage({
<TickerChips tickers={p.tickers} isZh={isZh} /> <TickerChips tickers={p.tickers} isZh={isZh} />
</div> </div>
))} ))}
<Pagination
page={kolSafePage}
total={kolTotalPages}
count={filtered.length}
pageSize={KOL_PAGE_SIZE}
onChange={setKolPage}
scrollTop={false}
/>
</div> </div>
)} )}
+7 -1
View File
@@ -1,6 +1,7 @@
'use client' 'use client'
import { useState, useEffect, useMemo } from 'react' import { useState, useEffect, useMemo } from 'react'
import dynamic from 'next/dynamic'
import { useLocale } from 'next-intl' import { useLocale } from 'next-intl'
import type { TrumpPost } from '@/types' import type { TrumpPost } from '@/types'
import { getPosts, getFundingSnapshot, type FundingSnapshot } from '@/lib/api' import { getPosts, getFundingSnapshot, type FundingSnapshot } from '@/lib/api'
@@ -9,7 +10,12 @@ import PostRow from '@/components/dashboard/PostCards'
import SystemControl from '@/components/signals/SystemControl' import SystemControl from '@/components/signals/SystemControl'
import InfoTip from '@/components/ui/InfoTip' import InfoTip from '@/components/ui/InfoTip'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
import MacroPanel from '@/components/btc/MacroPanel'
// MacroPanel is 631 lines with heavy indicator math — split it out.
const MacroPanel = dynamic(() => import('@/components/btc/MacroPanel'), {
ssr: false,
loading: () => <div style={{ height: 280, background: 'var(--bg-sunk)', borderRadius: 12, marginBottom: 20 }} />,
})
/** /**
* System 2 — BTC bottom-reversal. Its own dedicated page. * System 2 — BTC bottom-reversal. Its own dedicated page.
+7 -1
View File
@@ -1,14 +1,20 @@
'use client' 'use client'
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import dynamic from 'next/dynamic'
import Link from 'next/link' import Link from 'next/link'
import { usePathname } from 'next/navigation' import { usePathname } from 'next/navigation'
import { useLocale } from 'next-intl' import { useLocale } from 'next-intl'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import BotConfigPanel from '@/components/trades/BotConfigPanel'
import TelegramCard from '@/components/telegram/TelegramCard' import TelegramCard from '@/components/telegram/TelegramCard'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
// BotConfigPanel is 867 lines and only needed after wallet connect — lazy load it.
const BotConfigPanel = dynamic(() => import('@/components/trades/BotConfigPanel'), {
ssr: false,
loading: () => <div style={{ height: 200, background: 'var(--bg-sunk)', borderRadius: 12, marginBottom: 16 }} />,
})
/** /**
* Settings page — the home for all configuration. * Settings page — the home for all configuration.
* *
+3 -1
View File
@@ -69,7 +69,9 @@ export default function TradesPageClient() {
} }
})() })()
return () => { cancelled = true } return () => { cancelled = true }
}, [address, isConnected, isZh]) // isZh intentionally excluded: compile-time constant (always false).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [address, isConnected])
const needsSetup = mounted && isConnected && (!isSubscribed || !hlApiKeySet) const needsSetup = mounted && isConnected && (!isSubscribed || !hlApiKeySet)
+21
View File
@@ -0,0 +1,21 @@
export default function TradesLoading() {
return (
<div className="page">
<div className="page-head">
<div className="skeleton sk-title" style={{ width: 140, marginBottom: 8 }} />
</div>
<div style={{ marginTop: 16 }}>
{Array.from({ length: 6 }).map((_, i) => (
<div key={i} className="skeleton-card" style={{ marginBottom: 8, padding: 16 }}>
<div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
<div className="skeleton sk-line" style={{ width: 40 }} />
<div className="skeleton sk-line" style={{ width: 60 }} />
<div className="skeleton sk-line" style={{ width: 80 }} />
<div className="skeleton sk-line" style={{ width: 100 }} />
</div>
</div>
))}
</div>
</div>
)
}
+44 -30
View File
@@ -9,11 +9,9 @@ import PostRow from '@/components/dashboard/PostCards'
import SystemControl from '@/components/signals/SystemControl' import SystemControl from '@/components/signals/SystemControl'
import PageHint from '@/components/ui/PageHint' import PageHint from '@/components/ui/PageHint'
import InfoTip from '@/components/ui/InfoTip' import InfoTip from '@/components/ui/InfoTip'
import Pagination from '@/components/ui/Pagination'
/** const PAGE_SIZE = 30
* System 1 Trump (event-driven scalp). Its own dedicated page.
* Shows ONLY source === 'truth'. No scanner panel (that's System 2).
*/
const SENTIMENTS = ['all', 'bullish', 'bearish', 'neutral'] as const const SENTIMENTS = ['all', 'bullish', 'bearish', 'neutral'] as const
type SentimentFilter = (typeof SENTIMENTS)[number] type SentimentFilter = (typeof SENTIMENTS)[number]
@@ -25,29 +23,32 @@ interface TrumpSignalPageProps {
export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPageProps) { export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPageProps) {
const locale = useLocale() const locale = useLocale()
const isZh = false // i18n shelved — Chinese branches kept as dead code for future revival; see messages/zh.json const isZh = false
const [posts, setPosts] = useState<TrumpPost[]>(initialPosts ?? []) const [posts, setPosts] = useState<TrumpPost[]>(initialPosts ?? [])
const [loading, setLoading] = useState(initialPosts === null) const [loading, setLoading] = useState(initialPosts === null)
const [loadErr, setLoadErr] = useState('') const [loadErr, setLoadErr] = useState('')
const [sentFilter, setSentFilter] = useState<SentimentFilter>('all') const [sentFilter, setSentFilter] = useState<SentimentFilter>('all')
const [sigFilter, setSigFilter] = useState<SignalFilter>('all') const [sigFilter, setSigFilter] = useState<SignalFilter>('all')
const [page, setPage] = useState(1)
useEffect(() => { useEffect(() => {
swrFetch( swrFetch(
'posts-500', 'posts-500',
3 * 60_000, // 3 min TTL 3 * 60_000,
() => getPosts(500, 1), () => getPosts(500, 1),
fresh => setPosts(fresh), // background revalidation callback fresh => setPosts(fresh),
) )
.then(p => { setPosts(p); setLoadErr('') }) .then(p => { setPosts(p); setLoadErr('') })
.catch(e => setLoadErr(e instanceof Error ? e.message : (isZh ? '帖子加载失败' : 'Failed to load posts'))) .catch(e => setLoadErr(e instanceof Error ? e.message : 'Failed to load posts'))
.finally(() => setLoading(false)) .finally(() => setLoading(false))
}, [isZh]) }, [])
const trumpPosts = useMemo( const trumpPosts = useMemo(
() => posts.filter(p => (p.source || '') === 'truth'), () => posts.filter(p => (p.source || '') === 'truth'),
[posts], [posts],
) )
const filtered = useMemo(() => trumpPosts.filter(p => { const filtered = useMemo(() => trumpPosts.filter(p => {
if (sentFilter !== 'all' && p.sentiment !== sentFilter) return false if (sentFilter !== 'all' && p.sentiment !== sentFilter) return false
if (sigFilter === 'actionable' && p.signal !== 'buy' && p.signal !== 'short') return false if (sigFilter === 'actionable' && p.signal !== 'buy' && p.signal !== 'short') return false
@@ -56,6 +57,10 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
return true return true
}), [trumpPosts, sentFilter, sigFilter]) }), [trumpPosts, sentFilter, sigFilter])
const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE))
const safePage = Math.min(page, totalPages)
const pageItems = filtered.slice((safePage - 1) * PAGE_SIZE, safePage * PAGE_SIZE)
const sigCounts = useMemo(() => ({ const sigCounts = useMemo(() => ({
all: trumpPosts.length, all: trumpPosts.length,
actionable: trumpPosts.filter(p => p.signal === 'buy' || p.signal === 'short').length, actionable: trumpPosts.filter(p => p.signal === 'buy' || p.signal === 'short').length,
@@ -64,24 +69,17 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
}), [trumpPosts]) }), [trumpPosts])
const signalLabels: Record<SignalFilter, string> = { const signalLabels: Record<SignalFilter, string> = {
all: isZh ? '全部' : 'All', all: 'All', actionable: 'Actionable', buy: 'Buy', short: 'Short',
actionable: isZh ? '可执行' : 'Actionable',
buy: isZh ? '做多' : 'Buy',
short: isZh ? '做空' : 'Short',
} }
const sentimentLabels: Record<SentimentFilter, string> = { const sentimentLabels: Record<SentimentFilter, string> = {
all: isZh ? '全部' : 'All', all: 'All', bullish: 'Bullish', bearish: 'Bearish', neutral: 'Neutral',
bullish: isZh ? '看多' : 'Bullish',
bearish: isZh ? '看空' : 'Bearish',
neutral: isZh ? '中性' : 'Neutral',
} }
return ( return (
<div className="page"> <div className="page">
<div className="page-head"> <div className="page-head">
<div> <div>
<h1 className="page-title">{isZh ? '① Trump 信号' : '① Trump Signal'}</h1> <h1 className="page-title"> Trump Signal</h1>
<PageHint count={`${sigCounts.actionable} actionable / ${trumpPosts.length} posts`}> <PageHint count={`${sigCounts.actionable} actionable / ${trumpPosts.length} posts`}>
Watches Trump's Truth Social posts in real time, AI-scores each one, Watches Trump's Truth Social posts in real time, AI-scores each one,
and only fires a trade when the conviction is high enough to move price. and only fires a trade when the conviction is high enough to move price.
@@ -96,6 +94,7 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
display: 'flex', justifyContent: 'space-between', alignItems: 'center', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
gap: 12, margin: '16px 0 12px', flexWrap: 'wrap', gap: 12, margin: '16px 0 12px', flexWrap: 'wrap',
}}> }}>
{/* Signal filter tabs */}
<div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}> <div className="nav-tabs" style={{ background: 'var(--bg-sunk)' }}>
{([ {([
{ key: 'all', hint: 'Every post the scraper has captured.' }, { key: 'all', hint: 'Every post the scraper has captured.' },
@@ -106,7 +105,7 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
<button <button
key={f.key} key={f.key}
className={`nav-tab ${sigFilter === f.key ? 'active' : ''}`} className={`nav-tab ${sigFilter === f.key ? 'active' : ''}`}
onClick={() => setSigFilter(f.key)} onClick={() => { setSigFilter(f.key); setPage(1) }}
> >
{f.key === 'actionable' ? '🔥 ' : ''} {f.key === 'actionable' ? '🔥 ' : ''}
{signalLabels[f.key]} {signalLabels[f.key]}
@@ -114,6 +113,8 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
</button> </button>
))} ))}
</div> </div>
{/* Sentiment filter */}
<div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}> <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', alignItems: 'center' }}>
<span style={{ fontSize: 11, color: 'var(--ink-4)', marginRight: 4 }}> <span style={{ fontSize: 11, color: 'var(--ink-4)', marginRight: 4 }}>
Sentiment Sentiment
@@ -125,7 +126,7 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
{SENTIMENTS.map(f => ( {SENTIMENTS.map(f => (
<button <button
key={f} key={f}
onClick={() => setSentFilter(f)} onClick={() => { setSentFilter(f); setPage(1) }}
style={{ style={{
padding: '4px 10px', borderRadius: 6, border: '1px solid var(--line)', padding: '4px 10px', borderRadius: 6, border: '1px solid var(--line)',
background: sentFilter === f ? 'var(--ink)' : 'transparent', background: sentFilter === f ? 'var(--ink)' : 'transparent',
@@ -140,24 +141,37 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage
</div> </div>
{loading && <TrumpSkeleton />} {loading && <TrumpSkeleton />}
{!loading && loadErr && ( {!loading && loadErr && (
<div className="card" style={{ padding: 24, textAlign: 'center', color: 'var(--down)' }}> <div className="card" style={{ padding: 24, textAlign: 'center', color: 'var(--down)' }}>
{`Couldnt load signals — ${loadErr}`} {`Couldn't load signals — ${loadErr}`}
<div style={{ marginTop: 10 }}> <div style={{ marginTop: 10 }}>
<button className="btn ghost" style={{ fontSize: 12, padding: '6px 14px' }} <button className="btn ghost" style={{ fontSize: 12, padding: '6px 14px' }}
onClick={() => location.reload()}>{isZh ? '重试' : 'Retry'}</button> onClick={() => location.reload()}>Retry</button>
</div> </div>
</div> </div>
)} )}
{!loading && !loadErr && filtered.length === 0 && ( {!loading && !loadErr && filtered.length === 0 && (
<div className="card" style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}> <div className="card" style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>
No Trump signals match the current filter. No Trump signals match the current filter.
</div> </div>
)} )}
{!loading && filtered.length > 0 && (
<div className="post-stream"> {!loading && pageItems.length > 0 && (
{filtered.map(p => <PostRow key={p.id} post={p} />)} <>
</div> <div className="post-stream">
{pageItems.map(p => <PostRow key={p.id} post={p} />)}
</div>
<Pagination
page={safePage}
total={totalPages}
count={filtered.length}
pageSize={PAGE_SIZE}
onChange={setPage}
/>
</>
)} )}
</div> </div>
) )
+26
View File
@@ -0,0 +1,26 @@
/** Instant skeleton shown by Next.js while TrumpPage compiles / fetches. */
export default function TrumpLoading() {
return (
<div className="page">
<div className="page-head">
<div>
<div className="skeleton sk-title" style={{ width: 180, marginBottom: 8 }} />
<div className="skeleton sk-line" style={{ width: 320 }} />
</div>
</div>
<div className="post-stream" style={{ marginTop: 16 }}>
{Array.from({ length: 8 }).map((_, i) => (
<div key={i} className="skeleton-card" style={{ marginBottom: 8 }}>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<div className="skeleton sk-line sk-w-q" />
<div className="skeleton sk-line" style={{ width: 60 }} />
</div>
<div className="skeleton sk-title sk-w-3q" />
<div className="skeleton sk-line sk-w-full" />
<div className="skeleton sk-line sk-w-half" />
</div>
))}
</div>
</div>
)
}
+13 -2
View File
@@ -8,12 +8,23 @@ async function handler(request: NextRequest): Promise<NextResponse> {
const targetUrl = `${API_BASE}${targetPath}${url.search}` const targetUrl = `${API_BASE}${targetPath}${url.search}`
const headers = new Headers(request.headers) const headers = new Headers(request.headers)
// Remove Next.js internal headers // Remove Next.js internal headers that would confuse the upstream server.
// Keep (or relay) x-forwarded-for so the backend's rate limiter can
// identify individual clients — without it, all users share the Next.js
// server IP and a single rate-limit bucket.
headers.delete('host') headers.delete('host')
headers.delete('x-forwarded-for')
headers.delete('x-forwarded-host') headers.delete('x-forwarded-host')
headers.delete('x-forwarded-proto') headers.delete('x-forwarded-proto')
// Relay real client IP. Prefer the header Vercel/CDN already set; fall
// back to x-real-ip; ultimately unknown if neither is present (e.g. local
// dev through a raw Node server).
const clientIp =
request.headers.get('x-forwarded-for') ??
request.headers.get('x-real-ip') ??
'unknown'
headers.set('x-forwarded-for', clientIp)
const body = const body =
request.method !== 'GET' && request.method !== 'HEAD' request.method !== 'GET' && request.method !== 'HEAD'
? await request.arrayBuffer() ? await request.arrayBuffer()
+222 -73
View File
@@ -4,21 +4,21 @@
============================================================ */ ============================================================ */
.lp-root { .lp-root {
--lp-bg: #0a0907; --lp-bg: #060605;
--lp-bg-2: #12100c; --lp-bg-2: #0e0d0b;
--lp-surface: rgba(255, 255, 255, 0.04); --lp-surface: rgba(255, 255, 255, 0.045);
--lp-surface-2: rgba(255, 255, 255, 0.07); --lp-surface-2: rgba(255, 255, 255, 0.08);
--lp-line: rgba(255, 255, 255, 0.08); --lp-line: rgba(255, 255, 255, 0.10);
--lp-line-2: rgba(255, 255, 255, 0.14); --lp-line-2: rgba(255, 255, 255, 0.18);
--lp-ink: #f5f2ea; --lp-ink: #ffffff;
--lp-ink-2: #c9c3b5; --lp-ink-2: #d4cfc5;
--lp-ink-3: #8a8578; --lp-ink-3: #8a8578;
--lp-ink-4: #5c584e; --lp-ink-4: #5c584e;
--lp-amber: #f5a524; --lp-amber: #f5a524;
--lp-amber-2: #e68a00; --lp-amber-2: #e68a00;
--lp-amber-glow: rgba(245, 165, 36, 0.35); --lp-amber-glow: rgba(245, 165, 36, 0.40);
--lp-red: #ef4444; --lp-red: #f43f3f;
--lp-green: #22c55e; --lp-green: #1fdb63;
--lp-violet: #a78bfa; --lp-violet: #a78bfa;
min-height: 100vh; min-height: 100vh;
@@ -104,7 +104,7 @@
.lp-nav-inner { .lp-nav-inner {
max-width: 1180px; max-width: 1180px;
margin: 0 auto; margin: 0 auto;
padding: 14px 24px; padding: 12px 24px;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: space-between; justify-content: space-between;
@@ -142,24 +142,46 @@
/* ---------- Hero ---------- */ /* ---------- Hero ---------- */
.lp-hero { .lp-hero {
min-height: calc(100vh - 60px); min-height: calc(100vh - 56px);
display: grid;
grid-template-columns: 1.1fr 0.9fr;
gap: 52px;
align-items: start;
padding: 72px 0 60px;
text-align: left;
}
.lp-hero-left {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
justify-content: center; align-items: flex-start;
padding: 80px 0 100px; padding-top: 4px;
text-align: center; }
.lp-hero-right {
position: relative;
padding-top: 2px;
}
@media (max-width: 960px) {
.lp-hero {
grid-template-columns: 1fr;
text-align: center;
padding: 52px 0 56px;
gap: 0;
align-items: center;
}
.lp-hero-left { align-items: center; }
.lp-hero-right { display: none; }
} }
.lp-live-badge { .lp-live-badge {
display: inline-flex; align-items: center; gap: 8px; display: inline-flex; align-items: center; gap: 8px;
margin: 0 auto 28px; margin: 0 0 22px;
padding: 7px 14px 7px 10px; padding: 5px 12px 5px 9px;
font-size: 12px; font-weight: 600; font-size: 11px; font-weight: 700;
color: var(--lp-ink-2); color: var(--lp-ink-3);
background: rgba(239, 68, 68, 0.1); background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(239, 68, 68, 0.25); border: 1px solid rgba(255, 255, 255, 0.10);
border-radius: 999px; border-radius: 6px;
letter-spacing: 0.04em; letter-spacing: 0.08em;
text-transform: uppercase; text-transform: uppercase;
animation: lp-fade-up 0.7s ease both; animation: lp-fade-up 0.7s ease both;
} }
@@ -176,11 +198,11 @@
} }
.lp-h1 { .lp-h1 {
font-size: clamp(40px, 7.2vw, 88px); font-size: clamp(36px, 5.0vw, 72px);
font-weight: 800; font-weight: 900;
line-height: 1.02; line-height: 1.05;
letter-spacing: -0.035em; letter-spacing: -0.04em;
margin: 0 0 22px; margin: 0 0 18px;
animation: lp-fade-up 0.9s 0.1s ease both; animation: lp-fade-up 0.9s 0.1s ease both;
} }
.lp-h1 .grad { .lp-h1 .grad {
@@ -210,28 +232,36 @@
} }
.lp-sub { .lp-sub {
max-width: 640px; max-width: 480px;
margin: 0 auto 40px; margin: 0 0 32px;
font-size: clamp(16px, 1.8vw, 20px); font-size: clamp(14px, 1.5vw, 17px);
line-height: 1.55; line-height: 1.55;
color: var(--lp-ink-2); color: var(--lp-ink-3);
animation: lp-fade-up 0.9s 0.25s ease both; animation: lp-fade-up 0.9s 0.25s ease both;
} }
@media (max-width: 960px) {
.lp-sub { margin: 0 auto 32px; max-width: 520px; }
.lp-engine-chips { justify-content: center; }
}
.lp-ctas { .lp-ctas {
display: flex; gap: 14px; display: flex; gap: 12px;
justify-content: center; justify-content: flex-start;
flex-wrap: wrap; flex-wrap: wrap;
animation: lp-fade-up 0.9s 0.4s ease both; animation: lp-fade-up 0.9s 0.4s ease both;
} }
@media (max-width: 920px) {
.lp-ctas { justify-content: center; }
}
.lp-btn { .lp-btn {
display: inline-flex; align-items: center; gap: 10px; display: inline-flex; align-items: center; gap: 8px;
padding: 16px 28px; padding: 14px 24px;
font-size: 16px; font-weight: 600; font-size: 15px; font-weight: 700;
border-radius: 14px; border-radius: 10px;
text-decoration: none; text-decoration: none;
transition: all 0.18s ease; transition: all 0.18s ease;
cursor: pointer; border: none; cursor: pointer; border: none;
letter-spacing: -0.01em;
} }
/* Primary CTA kept static on purpose. Previously the button had a magnetic /* Primary CTA kept static on purpose. Previously the button had a magnetic
pull, a shimmer sweep, a hover lift, and a glow expansion stacked together. pull, a shimmer sweep, a hover lift, and a glow expansion stacked together.
@@ -265,8 +295,8 @@
/* ---------- Ticker strip ---------- */ /* ---------- Ticker strip ---------- */
.lp-ticker { .lp-ticker {
margin-top: 64px; margin-top: 0;
padding: 18px 0; padding: 16px 0;
border-top: 1px solid var(--lp-line); border-top: 1px solid var(--lp-line);
border-bottom: 1px solid var(--lp-line); border-bottom: 1px solid var(--lp-line);
overflow: hidden; overflow: hidden;
@@ -277,7 +307,7 @@
display: flex; display: flex;
gap: 48px; gap: 48px;
width: max-content; width: max-content;
animation: lp-scroll 40s linear infinite; animation: lp-scroll 28s linear infinite;
white-space: nowrap; white-space: nowrap;
} }
@keyframes lp-scroll { @keyframes lp-scroll {
@@ -302,30 +332,30 @@
/* ---------- Section ---------- */ /* ---------- Section ---------- */
.lp-section { .lp-section {
padding: 80px 0; padding: 72px 0;
position: relative; position: relative;
} }
.lp-eyebrow { .lp-eyebrow {
font-size: 12px; font-size: 11px;
font-weight: 600; font-weight: 700;
letter-spacing: 0.16em; letter-spacing: 0.14em;
text-transform: uppercase; text-transform: uppercase;
color: var(--lp-amber); color: var(--lp-amber);
margin-bottom: 16px; margin-bottom: 12px;
} }
.lp-h2 { .lp-h2 {
font-size: clamp(30px, 4.5vw, 52px); font-size: clamp(26px, 3.8vw, 48px);
font-weight: 700; font-weight: 800;
letter-spacing: -0.025em; letter-spacing: -0.03em;
line-height: 1.08; line-height: 1.1;
margin: 0 0 20px; margin: 0 0 16px;
} }
.lp-lead { .lp-lead {
max-width: 600px; max-width: 580px;
font-size: 17px; font-size: 16px;
line-height: 1.55; line-height: 1.6;
color: var(--lp-ink-2); color: var(--lp-ink-3);
margin: 0 0 40px; margin: 0 0 36px;
} }
/* ---------- Scroll reveal ---------- */ /* ---------- Scroll reveal ---------- */
@@ -545,7 +575,7 @@
/* ---------- Final CTA ---------- */ /* ---------- Final CTA ---------- */
.lp-cta-final { .lp-cta-final {
padding: 120px 0; padding: 88px 0 96px;
text-align: center; text-align: center;
position: relative; position: relative;
} }
@@ -1469,19 +1499,19 @@
/* ===== Mobile polish (≤720px / ≤480px) ===== */ /* ===== Mobile polish (≤720px / ≤480px) ===== */
@media (max-width: 720px) { @media (max-width: 720px) {
.lp-wrap { padding: 0 16px; } .lp-wrap { padding: 0 16px; }
.lp-nav-inner { padding: 12px 16px; } .lp-nav-inner { padding: 10px 16px; }
.lp-logo { font-size: 14px; } .lp-logo { font-size: 14px; }
.lp-nav-cta { padding: 8px 12px; font-size: 12px; } .lp-nav-cta { padding: 7px 12px; font-size: 12px; }
.lp-hero { .lp-hero {
min-height: auto; min-height: auto;
padding: 48px 0 56px; padding: 44px 0 52px;
} }
.lp-h1 { .lp-h1 {
font-size: clamp(30px, 8.4vw, 56px); font-size: clamp(28px, 8.0vw, 52px);
margin-bottom: 18px; margin-bottom: 16px;
} }
.lp-sub { margin-bottom: 28px; font-size: 15px; } .lp-sub { margin-bottom: 24px; font-size: 14px; }
.lp-live-badge { .lp-live-badge {
font-size: 10px; font-size: 10px;
padding: 6px 10px 6px 8px; padding: 6px 10px 6px 8px;
@@ -1496,10 +1526,10 @@
.lp-ticker-track { gap: 24px; } .lp-ticker-track { gap: 24px; }
.lp-ticker-item { font-size: 11px; } .lp-ticker-item { font-size: 11px; }
.lp-section { padding: 60px 0; } .lp-section { padding: 52px 0; }
.lp-h2 { font-size: clamp(24px, 6.4vw, 40px); } .lp-h2 { font-size: clamp(22px, 6.0vw, 38px); }
.lp-lead { font-size: 15px; } .lp-lead { font-size: 14px; }
.lp-eyebrow { font-size: 11px; } .lp-eyebrow { font-size: 10px; }
/* Terminal */ /* Terminal */
.lp-term { border-radius: 14px; } .lp-term { border-radius: 14px; }
@@ -1535,7 +1565,7 @@
.lp-stat-val { font-size: 28px; } .lp-stat-val { font-size: 28px; }
/* Final CTA */ /* Final CTA */
.lp-cta-final { padding: 64px 0 72px; } .lp-cta-final { padding: 56px 0 64px; }
} }
@media (max-width: 420px) { @media (max-width: 420px) {
@@ -1649,12 +1679,128 @@
} }
*/ */
/* ── Engine chips — 6-signal breadth strip ─────────────────── */
.lp-engine-chips {
display: flex; flex-wrap: wrap; gap: 6px;
margin-top: 18px;
animation: lp-fade-up 0.9s 0.55s ease both;
}
.lp-engine-chip {
font-size: 11px; font-weight: 600;
padding: 4px 10px; border-radius: 5px;
font-family: 'Geist Mono', monospace;
letter-spacing: 0.04em;
border: 1px solid;
white-space: nowrap;
}
.lp-engine-chip.trump { color: var(--lp-amber); background: rgba(245,165,36,0.10); border-color: rgba(245,165,36,0.28); }
.lp-engine-chip.macro { color: var(--lp-green); background: rgba(31,219,99,0.09); border-color: rgba(31,219,99,0.25); }
.lp-engine-chip.kol { color: var(--lp-violet); background: rgba(167,139,250,0.10); border-color: rgba(167,139,250,0.28); }
.lp-engine-chip.tvt { color: var(--lp-red); background: rgba(244,63,63,0.09); border-color: rgba(244,63,63,0.25); }
.lp-engine-chip.fund { color: #60c8f5; background: rgba(96,200,245,0.09); border-color: rgba(96,200,245,0.25); }
.lp-engine-chip.auto { color: var(--lp-ink-2); background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.13); }
/* ── Live feed (X-timeline style, hero right column) ───────── */
.lp-livefeed {
background: rgba(8,8,8,0.85);
border: 1px solid var(--lp-line-2);
border-radius: 14px;
overflow: hidden;
backdrop-filter: blur(24px);
box-shadow:
0 40px 100px rgba(0,0,0,0.7),
0 0 0 1px rgba(255,255,255,0.04),
inset 0 1px 0 rgba(255,255,255,0.04);
animation: lp-fade-up 1s 0.5s ease both;
}
.lp-livefeed-head {
display: flex; align-items: center; gap: 8px;
padding: 11px 16px;
border-bottom: 1px solid rgba(255,255,255,0.07);
font-size: 10px; font-weight: 700;
letter-spacing: 0.12em; text-transform: uppercase;
color: var(--lp-ink-3);
background: rgba(255,255,255,0.015);
}
.lp-livefeed-dot {
width: 7px; height: 7px; border-radius: 50%;
background: var(--lp-green);
box-shadow: 0 0 8px var(--lp-green);
animation: lp-ping 1.4s infinite;
flex-shrink: 0;
}
.lp-livefeed-count {
margin-left: auto;
font-size: 10px;
color: var(--lp-ink-4);
font-family: 'Geist Mono', monospace;
}
.lp-signal-post {
padding: 13px 16px;
border-bottom: 1px solid rgba(255,255,255,0.05);
transition: background 0.15s;
cursor: default;
}
.lp-signal-post:last-child { border-bottom: none; }
.lp-signal-post.is-new {
background: rgba(245,165,36,0.04);
border-left: 2px solid var(--lp-amber);
padding-left: 14px;
}
.lp-signal-post:hover { background: rgba(255,255,255,0.025); }
.lp-signal-post-head {
display: flex; align-items: center; gap: 6px;
margin-bottom: 6px;
}
.lp-signal-handle {
font-size: 13px; font-weight: 700;
color: var(--lp-ink);
}
.lp-signal-at { font-size: 12px; color: var(--lp-ink-4); }
.lp-signal-ts { font-size: 11px; color: var(--lp-ink-4); margin-left: auto; font-family: 'Geist Mono', monospace; }
.lp-signal-new-badge {
margin-left: 4px;
font-size: 9px; font-weight: 700;
padding: 1px 6px; border-radius: 3px;
background: var(--lp-amber);
color: #060605;
letter-spacing: 0.08em;
text-transform: uppercase;
animation: lp-pulse-soft 1.8s ease-in-out infinite;
}
.lp-signal-text {
font-size: 13.5px; line-height: 1.4;
color: var(--lp-ink-2);
margin: 0 0 9px;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.lp-signal-chips {
display: flex; gap: 5px; flex-wrap: wrap; align-items: center;
}
.lp-signal-chip {
font-size: 10px; font-weight: 700;
padding: 3px 8px; border-radius: 4px;
font-family: 'Geist Mono', monospace;
letter-spacing: 0.05em;
border: 1px solid transparent;
}
.lp-signal-chip.long { background: rgba(31,219,99,0.15); color: var(--lp-green); border-color: rgba(31,219,99,0.30); }
.lp-signal-chip.short { background: rgba(244,63,63,0.15); color: var(--lp-red); border-color: rgba(244,63,63,0.30); }
.lp-signal-chip.noise { background: rgba(255,255,255,0.05); color: var(--lp-ink-4); border-color: rgba(255,255,255,0.08); }
.lp-signal-chip.asset { background: rgba(245,165,36,0.15); color: var(--lp-amber); border-color: rgba(245,165,36,0.30); }
.lp-signal-chip.conf { background: rgba(167,139,250,0.12); color: var(--lp-violet); border-color: rgba(167,139,250,0.25); }
.lp-signal-chip.action-ok { color: var(--lp-green); background: transparent; border: none; padding-left: 0; font-weight: 500; font-size: 11px; }
.lp-signal-chip.action-skip { color: var(--lp-ink-4); background: transparent; border: none; padding-left: 0; font-weight: 500; font-size: 11px; }
/* ── 6. Hero stats (counter strip) ────────────────────────── */ /* ── 6. Hero stats (counter strip) ────────────────────────── */
.lp-herostats { .lp-herostats {
margin: 56px auto 0; margin: 32px 0 0;
align-self: center; /* center inside .lp-hero flex column */ display: inline-flex; align-items: stretch; gap: 24px;
display: inline-flex; align-items: stretch; gap: 28px; padding: 14px 20px;
padding: 18px 28px;
border: 1px solid var(--lp-line); border: 1px solid var(--lp-line);
border-radius: 16px; border-radius: 16px;
background: background:
@@ -1697,6 +1843,9 @@
background: linear-gradient(180deg, transparent, var(--lp-line), transparent); background: linear-gradient(180deg, transparent, var(--lp-line), transparent);
align-self: stretch; align-self: stretch;
} }
@media (max-width: 960px) {
.lp-herostats { align-self: center; }
}
@media (max-width: 560px) { @media (max-width: 560px) {
.lp-herostats { gap: 16px; padding: 14px 18px; } .lp-herostats { gap: 16px; padding: 14px 18px; }
} }
+140 -51
View File
@@ -224,8 +224,9 @@ export default function LandingPage() {
useCursorVars(rootRef as React.RefObject<HTMLElement>) useCursorVars(rootRef as React.RefObject<HTMLElement>)
// Decoded hero text — assembles from random glyphs on mount. // Decoded hero text — assembles from random glyphs on mount.
const heroLine1 = useScramble('Where crypto alpha actually lives —', 1100) const heroLine1 = useScramble('Trump. KOL. Macro.', 900)
const heroLine2 = useScramble('all in one tab.', 1500) const heroLine2 = useScramble('Six engines.', 1200)
const heroLine3 = useScramble('Always first.', 1500)
// primaryRef / useMagnetic intentionally removed — the hero CTA is now a // primaryRef / useMagnetic intentionally removed — the hero CTA is now a
// static button. The hook is still defined above in case the effect is // static button. The hook is still defined above in case the effect is
// reinstated on another element later. // reinstated on another element later.
@@ -254,56 +255,74 @@ export default function LandingPage() {
<div className="lp-wrap"> <div className="lp-wrap">
{/* ---------- HERO ---------- */} {/* ---------- HERO ---------- */}
<section className="lp-hero"> <section className="lp-hero">
<div className="lp-live-badge"> {/* LEFT column */}
<span className="lp-live-dot" /> <div className="lp-hero-left">
Six signal engines running · right now <div className="lp-live-badge">
</div> <span className="lp-live-dot" />
6 signal engines · live right now
<h1 className="lp-h1 lp-decode">
<span className="lp-decode-line">{heroLine1}</span>
<br />
<span className="grad lp-decode-line">{heroLine2}</span>
</h1>
<p className="lp-sub">
Trump posts. On-chain bottoms. KOL essays. Wallets that move before
they tweet. We scrape every edge, score it with AI, and surface only
what&rsquo;s tradeable. You sleep. It doesn&rsquo;t.
</p>
<div className="lp-ctas">
<Link href="/en" className="lp-btn lp-btn-primary">
Launch Dashboard
<span className="lp-arrow"></span>
</Link>
<a href="#pillars" className="lp-btn lp-btn-secondary">
See all six signals
</a>
</div>
{/* Live counter strip — animates in when hero is visible */}
<HeroStats />
{/* Ticker strip */}
<div className="lp-ticker" aria-hidden>
<div className="lp-ticker-track">
{[0, 1].map((k) => (
<div key={k} style={{ display: 'flex', gap: 48 }}>
<TickerItem asset="BTC" kind="buy" text="Post scored 82 · AUTO-LONG fired" />
<TickerItem asset="ETH" kind="hold" text="Below user confidence floor · skipped" />
<TickerItem asset="BTC" kind="sell" text="Signal SHORT · TP/SL armed" />
<TickerItem asset="ETH" kind="buy" text="Post scored 74 · AUTO-LONG fired" />
<TickerItem asset="BTC" kind="hold" text="Outside active window · standing by" />
<TickerItem asset="ETH" kind="sell" text="Signal SHORT · position opened" />
</div>
))}
</div> </div>
<h1 className="lp-h1 lp-decode">
<span className="lp-decode-line">{heroLine1}</span>
<br />
<span className="grad lp-decode-line">{heroLine2}</span>
<br />
<span className="lp-decode-line">{heroLine3}</span>
</h1>
<p className="lp-sub">
AI reads every signal in under 3&nbsp;seconds.
You&rsquo;re in the position before the headline hits.
</p>
<div className="lp-ctas">
<Link href="/en" className="lp-btn lp-btn-primary">
Launch Dashboard
<span className="lp-arrow"></span>
</Link>
<a href="#pillars" className="lp-btn lp-btn-secondary">
See all six signals
</a>
</div>
{/* Engine chips — show breadth at a glance */}
<div className="lp-engine-chips">
<span className="lp-engine-chip trump">Trump Signal</span>
<span className="lp-engine-chip macro">Macro Vibes</span>
<span className="lp-engine-chip kol">KOL Signal</span>
<span className="lp-engine-chip tvt">Talks vs Trades</span>
<span className="lp-engine-chip fund">Funding Reversal</span>
<span className="lp-engine-chip auto">Auto-Trader</span>
</div>
{/* Live counter strip */}
<HeroStats />
</div>
{/* RIGHT column — X-style live signal feed */}
<div className="lp-hero-right">
<LiveFeed />
</div> </div>
</section> </section>
{/* Ticker strip — below the 2-col hero */}
<div className="lp-ticker" aria-hidden>
<div className="lp-ticker-track">
{[0, 1].map((k) => (
<div key={k} style={{ display: 'flex', gap: 48 }}>
<TickerItem asset="BTC" kind="buy" text="Post scored 82 · AUTO-LONG fired" />
<TickerItem asset="ETH" kind="hold" text="Below user confidence floor · skipped" />
<TickerItem asset="BTC" kind="sell" text="Signal SHORT · TP/SL armed" />
<TickerItem asset="ETH" kind="buy" text="Post scored 74 · AUTO-LONG fired" />
<TickerItem asset="BTC" kind="hold" text="Outside active window · standing by" />
<TickerItem asset="ETH" kind="sell" text="Signal SHORT · position opened" />
</div>
))}
</div>
</div>
{/* ---------- FOUR PILLARS ---------- */} {/* ---------- FOUR PILLARS ---------- */}
<section id="pillars" className="lp-section" style={{ paddingTop: 60 }}> <section id="pillars" className="lp-section" style={{ paddingTop: 48 }}>
<div className="lp-reveal" style={{ maxWidth: 680 }}> <div className="lp-reveal" style={{ maxWidth: 680 }}>
<div className="lp-eyebrow">What runs inside</div> <div className="lp-eyebrow">What runs inside</div>
<h2 className="lp-h2"> <h2 className="lp-h2">
@@ -369,7 +388,7 @@ export default function LandingPage() {
</section> </section>
{/* ---------- THE ENGINE (terminal block) — Pillar 1 deep-dive ---------- */} {/* ---------- THE ENGINE (terminal block) — Pillar 1 deep-dive ---------- */}
<section id="engine" className="lp-section" style={{ paddingTop: 60 }}> <section id="engine" className="lp-section" style={{ paddingTop: 48 }}>
<div className="lp-reveal" style={{ maxWidth: 640 }}> <div className="lp-reveal" style={{ maxWidth: 640 }}>
<div className="lp-eyebrow">Pillar 1 · live engine</div> <div className="lp-eyebrow">Pillar 1 · live engine</div>
<h2 className="lp-h2"> <h2 className="lp-h2">
@@ -439,7 +458,7 @@ export default function LandingPage() {
</section> </section>
{/* ---------- PRESS / HEADLINES ---------- */} {/* ---------- PRESS / HEADLINES ---------- */}
<section className="lp-section" style={{ paddingTop: 60 }}> <section className="lp-section" style={{ paddingTop: 48 }}>
<div className="lp-reveal" style={{ maxWidth: 680 }}> <div className="lp-reveal" style={{ maxWidth: 680 }}>
<div className="lp-eyebrow">Headlines you can Google</div> <div className="lp-eyebrow">Headlines you can Google</div>
<h2 className="lp-h2"> <h2 className="lp-h2">
@@ -598,7 +617,7 @@ export default function LandingPage() {
</section> </section>
{/* ---------- COMPARISON TABLE ---------- */} {/* ---------- COMPARISON TABLE ---------- */}
<section id="compare" className="lp-section" style={{ paddingTop: 60 }}> <section id="compare" className="lp-section" style={{ paddingTop: 48 }}>
<div className="lp-reveal" style={{ maxWidth: 680 }}> <div className="lp-reveal" style={{ maxWidth: 680 }}>
<div className="lp-eyebrow">How it compares</div> <div className="lp-eyebrow">How it compares</div>
<h2 className="lp-h2"> <h2 className="lp-h2">
@@ -631,7 +650,7 @@ export default function LandingPage() {
</section> </section>
{/* ---------- WHAT IS TRUMP ALPHA (canonical definition for GEO) ---------- */} {/* ---------- WHAT IS TRUMP ALPHA (canonical definition for GEO) ---------- */}
<section id="about" className="lp-section" style={{ paddingTop: 80 }}> <section id="about" className="lp-section" style={{ paddingTop: 56 }}>
<div className="lp-reveal" style={{ maxWidth: 720 }}> <div className="lp-reveal" style={{ maxWidth: 720 }}>
<div className="lp-eyebrow">What is Trump Alpha</div> <div className="lp-eyebrow">What is Trump Alpha</div>
<h2 className="lp-h2"> <h2 className="lp-h2">
@@ -730,6 +749,76 @@ export default function LandingPage() {
) )
} }
/* ---------- Live feed (hero right column) ---------- */
function LiveFeed() {
return (
<div className="lp-livefeed">
<div className="lp-livefeed-head">
<span className="lp-livefeed-dot" />
Live signal feed
<span className="lp-livefeed-count">3 today</span>
</div>
<LiveSignalPost
isNew
ts="2m ago"
text="BITCOIN is the FUTURE of money. America will LEAD the world in crypto. BIG things coming very soon. ENJOY!"
signal={{ type: 'LONG', asset: 'BTC', conf: 82, action: 'AUTO-LONG fired' }}
/>
<LiveSignalPost
ts="14m ago"
text="Massive new TARIFFS on China coming — they have RIPPED OFF the USA for decades. No more!"
signal={{ type: 'SHORT', asset: 'BTC', conf: 71, action: 'AUTO-SHORT fired' }}
/>
<LiveSignalPost
ts="38m ago"
text="Crooked Joe and the Radical Left Lunatics are destroying our beautiful country. SAD!"
signal={{ type: 'NOISE', skip: 'off-topic · skipped' }}
/>
</div>
)
}
function LiveSignalPost({
isNew, ts, text, signal,
}: {
isNew?: boolean
ts: string
text: string
signal:
| { type: 'LONG' | 'SHORT'; asset: string; conf: number; action: string }
| { type: 'NOISE'; skip: string }
}) {
const t = signal.type
return (
<div className={`lp-signal-post${isNew ? ' is-new' : ''}`}>
<div className="lp-signal-post-head">
<span className="lp-signal-handle">Donald Trump</span>
<span className="lp-signal-at">@realDonaldTrump</span>
{isNew && <span className="lp-signal-new-badge">new</span>}
<span className="lp-signal-ts">{ts}</span>
</div>
<p className="lp-signal-text">{text}</p>
<div className="lp-signal-chips">
<span className={`lp-signal-chip ${t === 'LONG' ? 'long' : t === 'SHORT' ? 'short' : 'noise'}`}>
{t}
</span>
{'asset' in signal && (
<>
<span className="lp-signal-chip asset">{signal.asset}</span>
<span className="lp-signal-chip conf">CONF&nbsp;{signal.conf}</span>
<span className={`lp-signal-chip ${signal.action.includes('fired') ? 'action-ok' : 'action-skip'}`}>
· {signal.action}
</span>
</>
)}
{'skip' in signal && (
<span className="lp-signal-chip action-skip">· {signal.skip}</span>
)}
</div>
</div>
)
}
/* ---------- Terminal row ---------- */ /* ---------- Terminal row ---------- */
function TermRow({ function TermRow({
isNew, isNew,
+4 -3
View File
@@ -1,6 +1,6 @@
'use client' 'use client'
import { useEffect, useState } from 'react' import { memo, useEffect, useState } from 'react'
import type { TrumpPost } from '@/types' import type { TrumpPost } from '@/types'
function fmtPct(n: number | null | undefined) { function fmtPct(n: number | null | undefined) {
@@ -93,7 +93,7 @@ interface PostRowProps {
onClick?: () => void onClick?: () => void
} }
export default function PostRow({ post, selected, onClick }: PostRowProps) { const PostRow = memo(function PostRow({ post, selected, onClick }: PostRowProps) {
const [expanded, setExpanded] = useState(false) const [expanded, setExpanded] = useState(false)
const impact = post.price_impact const impact = post.price_impact
@@ -260,6 +260,7 @@ export default function PostRow({ post, selected, onClick }: PostRowProps) {
)} )}
</div> </div>
) )
} })
export default PostRow
export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime } export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime }
+1
View File
@@ -136,6 +136,7 @@ export default function Navbar() {
key={tab.key} key={tab.key}
href={`/${locale}${tab.key === '/' ? '' : tab.key}`} href={`/${locale}${tab.key === '/' ? '' : tab.key}`}
className={`nav-tab ${isActive(tab.key) ? 'active' : ''}`} className={`nav-tab ${isActive(tab.key) ? 'active' : ''}`}
prefetch
> >
{tab.label} {tab.label}
</Link> </Link>
+38 -7
View File
@@ -179,11 +179,20 @@ export default function OpenPositions() {
useEffect(() => { setMounted(true) }, []) useEffect(() => { setMounted(true) }, [])
const [closeErr, setCloseErr] = useState('') const [closeErr, setCloseErr] = useState('')
const [growId, setGrowId] = useState<number | null>(null) 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) { async function toggleGrow(p: OpenPosition) {
if (!address || growId !== null) return if (!address || growId !== null) return
const next = !p.grow_mode const next = !p.grow_mode
setGrowId(p.trade_id) setGrowId(p.trade_id); setGrowErr('')
try { try {
const env = await signRequest({ const env = await signRequest({
action: 'set_trade_grow', wallet: address, action: 'set_trade_grow', wallet: address,
@@ -194,9 +203,9 @@ export default function OpenPositions() {
x.trade_id === p.trade_id ? { ...x, grow_mode: r.grow_mode } : x)) x.trade_id === p.trade_id ? { ...x, grow_mode: r.grow_mode } : x))
} catch (e) { } catch (e) {
if (isUserRejection(e)) { if (isUserRejection(e)) {
setErr(isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled') setGrowErr(isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled')
} else { } else {
setErr(walletErrorLabel(e, isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled', 90) setGrowErr(walletErrorLabel(e, isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled', 90)
|| (isZh ? 'Grow 切换失败' : 'grow toggle failed')) || (isZh ? 'Grow 切换失败' : 'grow toggle failed'))
} }
} finally { setGrowId(null) } } finally { setGrowId(null) }
@@ -237,7 +246,12 @@ export default function OpenPositions() {
void load() void load()
const id = setInterval(() => { void load() }, POLL_MS) const id = setInterval(() => { void load() }, POLL_MS)
return () => { cancelled = true; clearInterval(id) } return () => { cancelled = true; clearInterval(id) }
}, [address, isConnected, signMessageAsync, isZh]) // 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])
// Trigger close. Two-step: opens modal, user confirms, we sign + POST. // Trigger close. Two-step: opens modal, user confirms, we sign + POST.
async function confirmCloseTrade() { async function confirmCloseTrade() {
@@ -257,8 +271,15 @@ export default function OpenPositions() {
setClosing(null) setClosing(null)
setCloseState('idle') setCloseState('idle')
} catch (e: unknown) { } catch (e: unknown) {
setCloseErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 120)) // Distinguish a user-cancelled signature (benign, close the modal) from
setCloseState('err') // 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')
}
} }
} }
@@ -351,6 +372,9 @@ export default function OpenPositions() {
{err && ( {err && (
<span style={{ fontSize: 11, color: 'var(--down)' }}> {err}</span> <span style={{ fontSize: 11, color: 'var(--down)' }}> {err}</span>
)} )}
{growErr && !err && (
<span style={{ fontSize: 11, color: 'var(--down)' }}> {growErr}</span>
)}
</div> </div>
{/* Position list (or empty state) */} {/* Position list (or empty state) */}
@@ -396,7 +420,14 @@ export default function OpenPositions() {
presses "Close now", reads the impact summary, then confirms. */} presses "Close now", reads the impact summary, then confirms. */}
{closing && ( {closing && (
<div <div
onClick={() => closeState === 'idle' && setClosing(null)} 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={{ style={{
position: 'fixed', inset: 0, zIndex: 1000, position: 'fixed', inset: 0, zIndex: 1000,
background: 'rgba(0,0,0,0.55)', background: 'rgba(0,0,0,0.55)',
+7 -2
View File
@@ -73,6 +73,12 @@ export default function SystemControl({ system }: { system: 'trump' | 'btc' }) {
if (!subscribed) { setErr(isZh ? '钱包尚未订阅,请先去设置页完成订阅。' : 'Wallet not subscribed — subscribe on the Settings page first.'); return } if (!subscribed) { setErr(isZh ? '钱包尚未订阅,请先去设置页完成订阅。' : 'Wallet not subscribed — subscribe on the Settings page first.'); return }
if (autoOn === on) 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 // Show pre-signing confirmation sheet before triggering MetaMask
const confirmed = await confirmSign(on const confirmed = await confirmSign(on
? { ? {
@@ -96,9 +102,8 @@ export default function SystemControl({ system }: { system: 'trump' | 'btc' }) {
danger: false, danger: false,
} }
) )
if (!confirmed) return if (!confirmed) { setBusy(false); return } // release the slot we claimed
setErr(''); setBusy(true)
try { try {
const env = await signRequest({ const env = await signRequest({
action: 'set_auto_trade', wallet: address, action: 'set_auto_trade', wallet: address,
+17 -4
View File
@@ -389,7 +389,12 @@ export default function BotConfigPanel() {
<span style={{ fontSize: 11, color: subPaperChoice === 'paper' ? 'var(--ink-2)' : 'var(--ink-4)', fontWeight: subPaperChoice === 'paper' ? 600 : 400 }}>Paper</span> <span style={{ fontSize: 11, color: subPaperChoice === 'paper' ? 'var(--ink-2)' : 'var(--ink-4)', fontWeight: subPaperChoice === 'paper' ? 600 : 400 }}>Paper</span>
<Switch <Switch
on={subPaperChoice === 'live'} on={subPaperChoice === 'live'}
onChange={v => setSubPaperChoice(v ? 'live' : 'paper')} onChange={v => {
setSubPaperChoice(v ? 'live' : 'paper')
// Clear any stale subscribe-error from a previous attempt so
// the user sees a clean state for the new paper/live choice.
if (subState === 'err') { setSubState('idle'); setSubErr('') }
}}
tone="amber" tone="amber"
/> />
<span style={{ fontSize: 11, color: subPaperChoice === 'live' ? 'var(--amber-ink)' : 'var(--ink-4)', fontWeight: subPaperChoice === 'live' ? 600 : 400 }}>Live</span> <span style={{ fontSize: 11, color: subPaperChoice === 'live' ? 'var(--amber-ink)' : 'var(--ink-4)', fontWeight: subPaperChoice === 'live' ? 600 : 400 }}>Live</span>
@@ -492,7 +497,15 @@ export default function BotConfigPanel() {
)} )}
{/* Live mode: show key input */} {/* Live mode: show key input */}
{!paperMode && (hlApiKeySet && !apiKey ? ( {!paperMode && (hlApiKeySet && !apiKey ? (
<button className="btn ghost" style={{ padding: '6px 14px', fontSize: 12, flexShrink: 0 }} onClick={() => setApiKey(' ')}>Rotate</button> <button
className="btn ghost"
style={{ padding: '6px 14px', fontSize: 12, flexShrink: 0 }}
onClick={() => {
// Switch to edit mode AND clear any stale error / status from
// a previous failed save so the row isn't pre-stained red.
setApiKey(' '); setKeyState('idle'); setKeyErr('')
}}
>Rotate</button>
) : ( ) : (
<div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
<input <input
@@ -787,13 +800,13 @@ export default function BotConfigPanel() {
<div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}> <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
<div className="num-field"> <div className="num-field">
<span className="prefix">From</span> <span className="prefix">From</span>
<input type="datetime-local" value={fromLocal} <input type="datetime-local" lang="en-US" value={fromLocal}
onChange={e => { setFromLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} /> onChange={e => { setFromLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
</div> </div>
<span style={{ fontSize: 12, color: 'var(--ink-4)' }}></span> <span style={{ fontSize: 12, color: 'var(--ink-4)' }}></span>
<div className="num-field"> <div className="num-field">
<span className="prefix">Until</span> <span className="prefix">Until</span>
<input type="datetime-local" value={untilLocal} <input type="datetime-local" lang="en-US" value={untilLocal}
onChange={e => { setUntilLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} /> onChange={e => { setUntilLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
</div> </div>
</div> </div>
+43 -11
View File
@@ -3,6 +3,7 @@
import { useState, useMemo } from 'react' import { useState, useMemo } from 'react'
import { useLocale } from 'next-intl' import { useLocale } from 'next-intl'
import type { BotTrade, TrumpPost } from '@/types' import type { BotTrade, TrumpPost } from '@/types'
import Pagination from '@/components/ui/Pagination'
// ── Formatters ──────────────────────────────────────────────────────────────── // ── Formatters ────────────────────────────────────────────────────────────────
function fmtMoney(n: number, opts: { sign?: boolean; decimals?: number } = {}) { function fmtMoney(n: number, opts: { sign?: boolean; decimals?: number } = {}) {
@@ -28,8 +29,11 @@ interface Props {
loading: boolean loading: boolean
} }
const ASSETS = ['all', 'BTC', 'ETH', 'SOL'] as const // ASSETS filter is derived dynamically from the trade set (see useMemo below)
const SIDES = ['all', 'long', 'short'] as const // so new assets (TRUMP, BNB, DOGE, LINK, AAVE, ...) appear automatically.
const SIDES = ['all', 'long', 'short'] as const
const TRADES_PER_PAGE = 25
export default function TradeTable({ trades, posts, loading }: Props) { export default function TradeTable({ trades, posts, loading }: Props) {
const locale = useLocale() const locale = useLocale()
@@ -38,6 +42,18 @@ export default function TradeTable({ trades, posts, loading }: Props) {
const [sideFilter, setSideFilter] = useState('all') const [sideFilter, setSideFilter] = useState('all')
const [sourceFilter, setSourceFilter] = useState('all') const [sourceFilter, setSourceFilter] = useState('all')
const [hidePaper, setHidePaper] = useState(false) 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. // Distinct sources present in the loaded trade set — drives the filter UI.
// Includes 'unknown' as a bucket for trades whose trigger post was deleted. // Includes 'unknown' as a bucket for trades whose trigger post was deleted.
@@ -65,13 +81,17 @@ export default function TradeTable({ trades, posts, loading }: Props) {
return acc return acc
}, [trades]) }, [trades])
const filtered = trades.filter(t => { const filtered = useMemo(() => trades.filter(t => {
if (sourceFilter !== 'all' && (t.trigger_source || 'unknown') !== sourceFilter) return false if (sourceFilter !== 'all' && (t.trigger_source || 'unknown') !== sourceFilter) return false
if (assetFilter !== 'all' && t.asset !== assetFilter) return false if (assetFilter !== 'all' && t.asset !== assetFilter) return false
if (sideFilter !== 'all' && t.side !== sideFilter) return false if (sideFilter !== 'all' && t.side !== sideFilter) return false
if (hidePaper && t.is_paper) return false if (hidePaper && t.is_paper) return false
return true 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. // Exclude externally-closed trades (pnl_usd null) from aggregates.
const priced = filtered.filter(t => t.pnl_usd !== null && t.pnl_usd !== undefined) const priced = filtered.filter(t => t.pnl_usd !== null && t.pnl_usd !== undefined)
@@ -111,7 +131,7 @@ export default function TradeTable({ trades, posts, loading }: Props) {
return ( return (
<button <button
key={src} key={src}
onClick={() => setSourceFilter(sourceFilter === src ? 'all' : src)} onClick={() => { setSourceFilter(sourceFilter === src ? 'all' : src); setPage(1) }}
style={{ style={{
textAlign: 'left', cursor: 'pointer', textAlign: 'left', cursor: 'pointer',
background: bg, borderRadius: 8, padding: '12px 14px', background: bg, borderRadius: 8, padding: '12px 14px',
@@ -146,7 +166,7 @@ export default function TradeTable({ trades, posts, loading }: Props) {
<div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 8 }}> <div style={{ fontSize: 10, color: 'var(--ink-4)', marginTop: 8 }}>
{isZh ? '点击来源可筛选表格。' : 'Click a source to filter the table.'} {sourceFilter !== 'all' && ( {isZh ? '点击来源可筛选表格。' : 'Click a source to filter the table.'} {sourceFilter !== 'all' && (
<button <button
onClick={() => setSourceFilter('all')} onClick={() => { setSourceFilter('all'); setPage(1) }}
style={{ marginLeft: 8, padding: '2px 8px', fontSize: 10, style={{ marginLeft: 8, padding: '2px 8px', fontSize: 10,
border: '1px solid var(--line)', borderRadius: 4, border: '1px solid var(--line)', borderRadius: 4,
background: 'transparent', cursor: 'pointer', color: 'var(--ink-2)' }} background: 'transparent', cursor: 'pointer', color: 'var(--ink-2)' }}
@@ -182,11 +202,11 @@ export default function TradeTable({ trades, posts, loading }: Props) {
{/* Filters */} {/* Filters */}
<div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', marginBottom: 14 }}> <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center', marginBottom: 14 }}>
<div className="nav-tabs"> <div className="nav-tabs">
{ASSETS.map(a => ( {assets.map(a => (
<button <button
key={a} key={a}
className={`nav-tab ${assetFilter === a ? 'active' : ''}`} className={`nav-tab ${assetFilter === a ? 'active' : ''}`}
onClick={() => setAssetFilter(a)} onClick={() => { setAssetFilter(a); setPage(1) }}
> >
{a === 'all' ? (isZh ? '全部资产' : 'All assets') : a} {a === 'all' ? (isZh ? '全部资产' : 'All assets') : a}
</button> </button>
@@ -197,7 +217,7 @@ export default function TradeTable({ trades, posts, loading }: Props) {
<button <button
key={s} key={s}
className={`nav-tab ${sideFilter === s ? 'active' : ''}`} className={`nav-tab ${sideFilter === s ? 'active' : ''}`}
onClick={() => setSideFilter(s)} onClick={() => { setSideFilter(s); setPage(1) }}
> >
{s === 'all' ? (isZh ? '全部方向' : 'All') : s === 'long' ? (isZh ? '做多' : 'Long') : (isZh ? '做空' : 'Short')} {s === 'all' ? (isZh ? '全部方向' : 'All') : s === 'long' ? (isZh ? '做多' : 'Long') : (isZh ? '做空' : 'Short')}
</button> </button>
@@ -212,7 +232,7 @@ export default function TradeTable({ trades, posts, loading }: Props) {
<input <input
type="checkbox" type="checkbox"
checked={hidePaper} checked={hidePaper}
onChange={e => setHidePaper(e.target.checked)} onChange={e => { setHidePaper(e.target.checked); setPage(1) }}
/> />
{isZh ? '隐藏模拟交易' : 'Hide paper trades'} {isZh ? '隐藏模拟交易' : 'Hide paper trades'}
</label> </label>
@@ -247,7 +267,7 @@ export default function TradeTable({ trades, posts, loading }: Props) {
</td> </td>
</tr> </tr>
)} )}
{filtered.map(t => { {pageRows.map(t => {
const tp = posts.find(p => p.id === t.trigger_post_id) const tp = posts.find(p => p.id === t.trigger_post_id)
const roi = const roi =
t.entry_price && t.exit_price != null t.entry_price && t.exit_price != null
@@ -326,6 +346,18 @@ export default function TradeTable({ trades, posts, loading }: Props) {
</table> </table>
</div> </div>
)} )}
{/* Pagination */}
{!loading && (
<Pagination
page={safePage}
total={totalPages}
count={filtered.length}
pageSize={TRADES_PER_PAGE}
onChange={setPage}
scrollTop={false}
/>
)}
</> </>
) )
} }
+204
View File
@@ -0,0 +1,204 @@
'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 151180 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(--brand, #f5a524)'
: hover
? 'var(--bg-sunk)'
: 'transparent'
const color = active
? '#fff'
: hover
? 'var(--ink)'
: 'var(--ink-2)'
const border = active
? '1.5px solid var(--brand, #f5a524)'
: '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',
}
+17 -1
View File
@@ -27,9 +27,18 @@ export interface SignConfirmOptions {
danger?: boolean 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). */ /** Renders a confirmation sheet and resolves true (confirm) or false (cancel). */
export function confirmSign(opts: SignConfirmOptions): Promise<boolean> { export function confirmSign(opts: SignConfirmOptions): Promise<boolean> {
return new Promise((resolve) => { 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') const existing = document.getElementById('sign-confirm-sheet-root')
if (existing?.parentNode) { if (existing?.parentNode) {
existing.parentNode.removeChild(existing) existing.parentNode.removeChild(existing)
@@ -43,6 +52,9 @@ export function confirmSign(opts: SignConfirmOptions): Promise<boolean> {
function cleanup(result: boolean) { function cleanup(result: boolean) {
if (settled) return if (settled) return
settled = true 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() root.unmount()
if (container.parentNode) { if (container.parentNode) {
container.parentNode.removeChild(container) container.parentNode.removeChild(container)
@@ -50,7 +62,11 @@ export function confirmSign(opts: SignConfirmOptions): Promise<boolean> {
resolve(result) resolve(result)
} }
root.render(<Sheet {...opts} onConfirm={() => cleanup(true)} onCancel={() => cleanup(false)} />) // 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} />)
}) })
} }
+3 -1
View File
@@ -37,7 +37,9 @@ export async function getPost(id: number): Promise<TrumpPost> {
return fetchJson<TrumpPost>(`/posts/${id}`) return fetchJson<TrumpPost>(`/posts/${id}`)
} }
export async function getPrices(asset: 'BTC' | 'ETH', tf: string): Promise<Candle[]> { // asset widened from 'BTC' | 'ETH' to string — chart will eventually support
// SOL/TRUMP etc. once the backend /prices/{asset} endpoint covers them.
export async function getPrices(asset: string, tf: string): Promise<Candle[]> {
return fetchJson<Candle[]>(`/prices/${asset}?tf=${tf}`) return fetchJson<Candle[]>(`/prices/${asset}?tf=${tf}`)
} }
+4 -2
View File
@@ -3,11 +3,13 @@
import { useWsSubscribe } from './wsContext' import { useWsSubscribe } from './wsContext'
interface Handlers { interface Handlers {
onPrice?: (asset: 'BTC' | 'ETH', price: number) => void // BUG-08 fix: backend now broadcasts SOL/TRUMP/BNB/DOGE/LINK/AAVE ticks
// in addition to BTC/ETH — widen asset to string.
onPrice?: (asset: string, price: number) => void
onNewPost?: (post: object) => void onNewPost?: (post: object) => void
} }
type PriceMsg = { type: 'price'; asset: 'BTC' | 'ETH'; price: number } type PriceMsg = { type: 'price'; asset: string; price: number }
type PostMsg = { type: 'new_post'; post: object } type PostMsg = { type: 'new_post'; post: object }
/** /**
+35 -5
View File
@@ -29,6 +29,15 @@ const WsContext = createContext<WsContextValue | null>(null)
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8000' const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8000'
// Exponential backoff: 2s → 4s → 8s → … capped at 60s, plus ±30% jitter
// so a server restart doesn't get hit by all clients at the same instant.
const WS_RETRY_BASE_MS = 2_000
const WS_RETRY_MAX_MS = 60_000
function retryDelay(attempt: number): number {
const exp = Math.min(WS_RETRY_BASE_MS * 2 ** attempt, WS_RETRY_MAX_MS)
return exp * (0.7 + Math.random() * 0.6) // ±30% jitter
}
export function WsProvider({ children }: { children: ReactNode }) { export function WsProvider({ children }: { children: ReactNode }) {
// Stable map: message-type → set of handlers. Never replaced, only mutated. // Stable map: message-type → set of handlers. Never replaced, only mutated.
const subs = useRef<Map<string, Set<Handler>>>(new Map()) const subs = useRef<Map<string, Set<Handler>>>(new Map())
@@ -36,10 +45,7 @@ export function WsProvider({ children }: { children: ReactNode }) {
useEffect(() => { useEffect(() => {
let dead = false let dead = false
let retryTimer: ReturnType<typeof setTimeout> | null = null let retryTimer: ReturnType<typeof setTimeout> | null = null
// Hold the current socket at useEffect scope so cleanup can close it. let attempt = 0
// Previously `ws` lived inside connect() and cleanup couldn't reach it,
// leaking one connection per StrictMode remount and one per [locale]
// layout swap (which remounts WsProvider).
let socket: WebSocket | null = null let socket: WebSocket | null = null
function connect() { function connect() {
@@ -47,6 +53,10 @@ export function WsProvider({ children }: { children: ReactNode }) {
socket = new WebSocket(`${WS_URL}/ws/prices`) socket = new WebSocket(`${WS_URL}/ws/prices`)
const ws = socket // local alias for handler closures const ws = socket // local alias for handler closures
ws.onopen = () => {
attempt = 0 // reset backoff on successful connection
}
ws.onmessage = (e) => { ws.onmessage = (e) => {
try { try {
const msg = JSON.parse(e.data) as { type?: string } const msg = JSON.parse(e.data) as { type?: string }
@@ -58,14 +68,34 @@ export function WsProvider({ children }: { children: ReactNode }) {
} }
ws.onclose = () => { ws.onclose = () => {
if (!dead) retryTimer = setTimeout(connect, 3000) if (!dead) {
const delay = retryDelay(attempt++)
retryTimer = setTimeout(connect, delay)
}
} }
ws.onerror = () => ws.close() ws.onerror = () => ws.close()
} }
// Reconnect immediately when the tab comes back to the foreground
// (the socket may have silently died while the tab was hidden).
function onVisible() {
if (document.visibilityState !== 'visible') return
if (socket && socket.readyState === WebSocket.OPEN) return
// Cancel any pending retry — we're reconnecting now.
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
attempt = 0
if (socket && socket.readyState < WebSocket.CLOSING) {
socket.onclose = null
socket.close()
}
connect()
}
document.addEventListener('visibilitychange', onVisible)
connect() connect()
return () => { return () => {
dead = true dead = true
document.removeEventListener('visibilitychange', onVisible)
if (retryTimer) clearTimeout(retryTimer) if (retryTimer) clearTimeout(retryTimer)
// Actively close any live socket so the OS-level connection releases // Actively close any live socket so the OS-level connection releases
// immediately on unmount instead of waiting for the next server keepalive. // immediately on unmount instead of waiting for the next server keepalive.
+1 -1
View File
@@ -8,7 +8,7 @@
"kol": "KOL", "kol": "KOL",
"trades": "Trades", "trades": "Trades",
"analytics": "Analytics", "analytics": "Analytics",
"settings": "Settings" "settings": "Config"
}, },
"actions": { "actions": {
"connectWallet": "Connect wallet", "connectWallet": "Connect wallet",
+1
View File
@@ -5,6 +5,7 @@ const withNextIntl = createNextIntlPlugin('./i18n.ts')
/** @type {import('next').NextConfig} */ /** @type {import('next').NextConfig} */
const nextConfig = { const nextConfig = {
reactStrictMode: true, reactStrictMode: true,
allowedDevOrigins: ['*'],
async rewrites() { async rewrites() {
return [ return [
{ {
+5
View File
@@ -8,6 +8,7 @@
"name": "trumpsignal", "name": "trumpsignal",
"version": "0.1.0", "version": "0.1.0",
"dependencies": { "dependencies": {
"@parcel/watcher-linux-arm64-glibc": "*",
"@rainbow-me/rainbowkit": "^2.1.3", "@rainbow-me/rainbowkit": "^2.1.3",
"@tanstack/react-query": "^5.40.0", "@tanstack/react-query": "^5.40.0",
"lightweight-charts": "^4.1.3", "lightweight-charts": "^4.1.3",
@@ -32,6 +33,9 @@
}, },
"engines": { "engines": {
"node": ">=20.19.0" "node": ">=20.19.0"
},
"optionalDependencies": {
"@parcel/watcher-linux-arm64-glibc": "^2.5.6"
} }
}, },
"node_modules/@adraffy/ens-normalize": { "node_modules/@adraffy/ens-normalize": {
@@ -2358,6 +2362,7 @@
"cpu": [ "cpu": [
"arm64" "arm64"
], ],
"license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
"linux" "linux"
+3
View File
@@ -34,5 +34,8 @@
"postcss": "^8", "postcss": "^8",
"tailwindcss": "^3.4.4", "tailwindcss": "^3.4.4",
"typescript": "^5" "typescript": "^5"
},
"optionalDependencies": {
"@parcel/watcher-linux-arm64-glibc": "^2.5.6"
} }
} }
+1 -1
View File
@@ -40,7 +40,7 @@ Optional: bring your own Hyperliquid account for auto-trading.
- Backend: Python / FastAPI - Backend: Python / FastAPI
- AI: Claude (Anthropic) for signal extraction - AI: Claude (Anthropic) for signal extraction
- On-chain: Etherscan API + Hyperliquid public API - On-chain: Etherscan API + Hyperliquid public API
- Frontend: Next.js 14 - Frontend: Next.js 16
## URLs ## URLs
+5 -3
View File
@@ -9,7 +9,9 @@ interface DashboardState {
botReadiness: 'unknown' | 'saved' | 'verified' | 'ready' botReadiness: 'unknown' | 'saved' | 'verified' | 'ready'
hlApiKeySet: boolean // true if user already has a key saved in backend hlApiKeySet: boolean // true if user already has a key saved in backend
hlApiKeyMasked: string | null // e.g. "...a1b2c3" shown after successful save hlApiKeyMasked: string | null // e.g. "...a1b2c3" shown after successful save
livePrices: { BTC: number | null; ETH: number | null } // BUG-08 fix: backend now streams SOL/TRUMP/BNB/etc. — use an open Record
// so any asset tick can be stored, not just BTC/ETH.
livePrices: Record<string, number | null>
setSelectedPost: (id: number | null) => void setSelectedPost: (id: number | null) => void
setAsset: (asset: 'BTC' | 'ETH') => void setAsset: (asset: 'BTC' | 'ETH') => void
setTimeframe: (tf: '5m' | '15m' | '1H' | '4H' | '1D' | '1W') => void setTimeframe: (tf: '5m' | '15m' | '1H' | '4H' | '1D' | '1W') => void
@@ -17,7 +19,7 @@ interface DashboardState {
setSubscribed: (subscribed: boolean) => void setSubscribed: (subscribed: boolean) => void
setBotReadiness: (state: DashboardState['botReadiness']) => void setBotReadiness: (state: DashboardState['botReadiness']) => void
setHlApiKeySet: (set: boolean, masked?: string) => void setHlApiKeySet: (set: boolean, masked?: string) => void
setLivePrice: (asset: 'BTC' | 'ETH', price: number) => void setLivePrice: (asset: string, price: number) => void
} }
export const useDashboardStore = create<DashboardState>((set) => ({ export const useDashboardStore = create<DashboardState>((set) => ({
@@ -29,7 +31,7 @@ export const useDashboardStore = create<DashboardState>((set) => ({
botReadiness: 'unknown', botReadiness: 'unknown',
hlApiKeySet: false, hlApiKeySet: false,
hlApiKeyMasked: null, hlApiKeyMasked: null,
livePrices: { BTC: null, ETH: null }, livePrices: { BTC: null, ETH: null, SOL: null, TRUMP: null },
setSelectedPost: (id) => set({ selectedPostId: id }), setSelectedPost: (id) => set({ selectedPostId: id }),
setAsset: (asset) => set({ asset }), setAsset: (asset) => set({ asset }),
setTimeframe: (timeframe) => set({ timeframe }), setTimeframe: (timeframe) => set({ timeframe }),
+4 -2
View File
@@ -18,7 +18,9 @@ export interface TrumpPost {
category: string | null category: string | null
expected_move_pct: number | null expected_move_pct: number | null
price_impact: { price_impact: {
asset: 'BTC' | 'ETH' // BUG-14 fix: tracked_asset is now target_asset ?? sentiment_asset, which
// can be SOL/TRUMP/BNB/etc. — no longer restricted to BTC | ETH.
asset: string
m5: number | null // null = window still open (live rolling peak pending) m5: number | null // null = window still open (live rolling peak pending)
m15: number | null m15: number | null
m1h: number | null m1h: number | null
@@ -66,7 +68,7 @@ export interface BotPerformance {
} }
// ── KOL module ──────────────────────────────────────────────────── // ── KOL module ────────────────────────────────────────────────────
export type KolAction = 'buy' | 'sell' | 'bullish' | 'bearish' | 'mention' export type KolAction = 'buy' | 'sell' | 'reduce' | 'bullish' | 'bearish' | 'mention'
export interface KolTicker { export interface KolTicker {
ticker: string ticker: string