diff --git a/CLAUDE.md b/CLAUDE.md index a642770..e35a4dd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -166,8 +166,10 @@ Tokens in `app/[locale]/globals.css`: ## Things that LOOK like bugs but aren't - **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 - `/en/btc` reference, it's a real bug — fix it (we've found and fixed 3). + Signal" in v2.0. All routes are now `/en/macro`. `app/[locale]/btc/page.tsx` + 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. See "Stack quirks" above. - **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 WS / wallet interactions. Don't try to convert without verifying the WS + 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-01–06, 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`; `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 ```bash diff --git a/app/[locale]/DashboardClient.tsx b/app/[locale]/DashboardClient.tsx index 27118e3..0a638cd 100644 --- a/app/[locale]/DashboardClient.tsx +++ b/app/[locale]/DashboardClient.tsx @@ -1,6 +1,7 @@ 'use client' import { useState, useEffect } from 'react' +import dynamic from 'next/dynamic' import Link from 'next/link' import { useParams } from 'next/navigation' 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 { getCachedViewEnvelope } from '@/lib/signedRequest' import { swrFetch } from '@/lib/cache' -import ChartPanel from '@/components/dashboard/ChartPanel' import PostRow, { SignalPill, SourceIcon, fmtPct, TimeAgo, LocalDateTime } from '@/components/dashboard/PostCards' import OpenPositions from '@/components/positions/OpenPositions' 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: () =>
, +}) + interface Props { initialPosts: TrumpPost[] } @@ -211,7 +218,10 @@ export default function DashboardClient({ initialPosts }: Props) { getPrices(asset, timeframe) .then(c => { setCandles(c); setChartErr('') }) .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(() => { let alive = true diff --git a/app/[locale]/archive/page.tsx b/app/[locale]/archive/page.tsx index ec15563..49a65de 100644 --- a/app/[locale]/archive/page.tsx +++ b/app/[locale]/archive/page.tsx @@ -6,6 +6,9 @@ import type { TrumpPost } from '@/types' import { getPosts } from '@/lib/api' import PostRow from '@/components/dashboard/PostCards' import PageHint from '@/components/ui/PageHint' +import Pagination from '@/components/ui/Pagination' + +const ARCHIVE_PAGE_SIZE = 30 const LIVE_SOURCES = new Set([ 'truth', @@ -25,6 +28,7 @@ export default function ArchivePage() { const [loading, setLoading] = useState(true) const [loadErr, setLoadErr] = useState('') const [src, setSrc] = useState('all') + const [archivePage, setArchivePage] = useState(1) useEffect(() => { getPosts(500, 1) @@ -49,6 +53,9 @@ export default function ArchivePage() { () => src === 'all' ? archivePosts : archivePosts.filter(p => p.source === 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 (
@@ -67,7 +74,7 @@ export default function ArchivePage() { {[['all', archivePosts.length] as [string, number], ...sources].map(([s, n]) => (
)} - {!loading && filtered.length > 0 && ( -
- {filtered.map(p => )} -
+ {!loading && archivePageItems.length > 0 && ( + <> +
+ {archivePageItems.map(p => )} +
+ + )}
) diff --git a/app/[locale]/globals.css b/app/[locale]/globals.css index 1cd2bd4..0e85ee4 100644 --- a/app/[locale]/globals.css +++ b/app/[locale]/globals.css @@ -363,7 +363,7 @@ html[data-theme="dark"] .asset-switch button.on { background: var(--surface-2); .page { max-width: 1360px; margin: 0 auto; - padding: 32px 28px 80px; + padding: 28px 28px 64px; width: 100%; } .page.wide { max-width: 1600px; } @@ -372,20 +372,20 @@ html[data-theme="dark"] .asset-switch button.on { background: var(--surface-2); display: flex; align-items: flex-end; justify-content: space-between; - margin-bottom: 28px; + margin-bottom: 24px; gap: 24px; } .page-title { - font-size: 34px; - letter-spacing: -0.02em; - font-weight: 600; - line-height: 1.05; + font-size: 28px; + letter-spacing: -0.025em; + font-weight: 700; + line-height: 1.1; margin: 0; } .page-sub { color: var(--ink-3); - font-size: 14px; - margin-top: 6px; + font-size: 13px; + margin-top: 5px; margin-bottom: 0; } diff --git a/app/[locale]/kol/KolPageClient.tsx b/app/[locale]/kol/KolPageClient.tsx index f7f7ed8..c526412 100644 --- a/app/[locale]/kol/KolPageClient.tsx +++ b/app/[locale]/kol/KolPageClient.tsx @@ -10,6 +10,7 @@ import type { import { getKolPosts, getKolPost, getKolDigest, getKolChanges, getKolDivergence } from '@/lib/api' import { swrFetch } from '@/lib/cache' import PageHint from '@/components/ui/PageHint' +import Pagination from '@/components/ui/Pagination' /** * KOL feed — independent module. Lists analyzed posts from tracked KOLs @@ -22,6 +23,7 @@ const ACTION_COLOR: Record = { bullish: '#16a34a', sell: '#dc2626', bearish: '#dc2626', + reduce: '#f59e0b', mention: '#9ca3af', } @@ -31,6 +33,7 @@ function actionLabel(action: KolTicker['action'], isZh: boolean) { const labels: Record = { buy: 'BUY', sell: 'SELL', + reduce: 'Reduce', bullish: 'Bullish', bearish: 'Bearish', mention: 'Mention', @@ -78,6 +81,7 @@ function postActionLabel(action: string, isZh: boolean) { const labels: Record = { buy: 'BUY', sell: 'SELL', + reduce: 'Reducing', bullish: 'Bullish post', bearish: 'Bearish post', } @@ -780,12 +784,14 @@ export default function KolPage({ const locale = useLocale() 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 KOL_PAGE_SIZE = 20 const [posts, setPosts] = useState(initialPosts ?? []) const [loading, setLoading] = useState(initialPosts === null) const [err, setErr] = useState('') const [openPost, setOpenPost] = useState(null) const [handleFilter, setHandleFilter] = useState('all') const [tickerFilter, setTickerFilter] = useState(null) + const [kolPage, setKolPage] = useState(1) useEffect(() => { swrFetch( @@ -812,6 +818,10 @@ export default function KolPage({ return out }, [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) { try { const detail = await getKolPost(id) @@ -837,8 +847,10 @@ export default function KolPage({ isZh={isZh} initialDigest={initialDigest} activeTicker={tickerFilter} - onTickerClick={(sym) => - setTickerFilter(prev => prev === sym ? null : sym)} + onTickerClick={(sym) => { + setTickerFilter(prev => prev === sym ? null : sym) + setKolPage(1) + }} /> {isZh ? '当前筛选标的:' : 'Filtered asset:'} {tickerFilter} ))} + + {/* Sentiment filter */}
Sentiment @@ -125,7 +126,7 @@ export default function TrumpSignalPage({ initialPosts = null }: TrumpSignalPage {SENTIMENTS.map(f => (
{loading && } + {!loading && loadErr && (
- ⚠️ {`Couldn’t load signals — ${loadErr}`} + ⚠️ {`Couldn't load signals — ${loadErr}`}
+ onClick={() => location.reload()}>Retry
)} + {!loading && !loadErr && filtered.length === 0 && (
No Trump signals match the current filter.
)} - {!loading && filtered.length > 0 && ( -
- {filtered.map(p => )} -
+ + {!loading && pageItems.length > 0 && ( + <> +
+ {pageItems.map(p => )} +
+ + + )} ) diff --git a/app/[locale]/trump/loading.tsx b/app/[locale]/trump/loading.tsx new file mode 100644 index 0000000..351316f --- /dev/null +++ b/app/[locale]/trump/loading.tsx @@ -0,0 +1,26 @@ +/** Instant skeleton shown by Next.js while TrumpPage compiles / fetches. */ +export default function TrumpLoading() { + return ( +
+
+
+
+
+
+
+
+ {Array.from({ length: 8 }).map((_, i) => ( +
+
+
+
+
+
+
+
+
+ ))} +
+
+ ) +} diff --git a/app/api/proxy/[...path]/route.ts b/app/api/proxy/[...path]/route.ts index a98a52b..7ce16d2 100644 --- a/app/api/proxy/[...path]/route.ts +++ b/app/api/proxy/[...path]/route.ts @@ -8,12 +8,23 @@ async function handler(request: NextRequest): Promise { const targetUrl = `${API_BASE}${targetPath}${url.search}` 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('x-forwarded-for') headers.delete('x-forwarded-host') 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 = request.method !== 'GET' && request.method !== 'HEAD' ? await request.arrayBuffer() diff --git a/app/landing.css b/app/landing.css index b012426..849b3ef 100644 --- a/app/landing.css +++ b/app/landing.css @@ -4,21 +4,21 @@ ============================================================ */ .lp-root { - --lp-bg: #0a0907; - --lp-bg-2: #12100c; - --lp-surface: rgba(255, 255, 255, 0.04); - --lp-surface-2: rgba(255, 255, 255, 0.07); - --lp-line: rgba(255, 255, 255, 0.08); - --lp-line-2: rgba(255, 255, 255, 0.14); - --lp-ink: #f5f2ea; - --lp-ink-2: #c9c3b5; + --lp-bg: #060605; + --lp-bg-2: #0e0d0b; + --lp-surface: rgba(255, 255, 255, 0.045); + --lp-surface-2: rgba(255, 255, 255, 0.08); + --lp-line: rgba(255, 255, 255, 0.10); + --lp-line-2: rgba(255, 255, 255, 0.18); + --lp-ink: #ffffff; + --lp-ink-2: #d4cfc5; --lp-ink-3: #8a8578; --lp-ink-4: #5c584e; --lp-amber: #f5a524; --lp-amber-2: #e68a00; - --lp-amber-glow: rgba(245, 165, 36, 0.35); - --lp-red: #ef4444; - --lp-green: #22c55e; + --lp-amber-glow: rgba(245, 165, 36, 0.40); + --lp-red: #f43f3f; + --lp-green: #1fdb63; --lp-violet: #a78bfa; min-height: 100vh; @@ -104,7 +104,7 @@ .lp-nav-inner { max-width: 1180px; margin: 0 auto; - padding: 14px 24px; + padding: 12px 24px; display: flex; align-items: center; justify-content: space-between; @@ -142,24 +142,46 @@ /* ---------- 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; flex-direction: column; - justify-content: center; - padding: 80px 0 100px; - text-align: center; + align-items: flex-start; + padding-top: 4px; +} +.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 { display: inline-flex; align-items: center; gap: 8px; - margin: 0 auto 28px; - padding: 7px 14px 7px 10px; - font-size: 12px; font-weight: 600; - color: var(--lp-ink-2); - background: rgba(239, 68, 68, 0.1); - border: 1px solid rgba(239, 68, 68, 0.25); - border-radius: 999px; - letter-spacing: 0.04em; + margin: 0 0 22px; + padding: 5px 12px 5px 9px; + font-size: 11px; font-weight: 700; + color: var(--lp-ink-3); + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.10); + border-radius: 6px; + letter-spacing: 0.08em; text-transform: uppercase; animation: lp-fade-up 0.7s ease both; } @@ -176,11 +198,11 @@ } .lp-h1 { - font-size: clamp(40px, 7.2vw, 88px); - font-weight: 800; - line-height: 1.02; - letter-spacing: -0.035em; - margin: 0 0 22px; + font-size: clamp(36px, 5.0vw, 72px); + font-weight: 900; + line-height: 1.05; + letter-spacing: -0.04em; + margin: 0 0 18px; animation: lp-fade-up 0.9s 0.1s ease both; } .lp-h1 .grad { @@ -210,28 +232,36 @@ } .lp-sub { - max-width: 640px; - margin: 0 auto 40px; - font-size: clamp(16px, 1.8vw, 20px); + max-width: 480px; + margin: 0 0 32px; + font-size: clamp(14px, 1.5vw, 17px); line-height: 1.55; - color: var(--lp-ink-2); + color: var(--lp-ink-3); 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 { - display: flex; gap: 14px; - justify-content: center; + display: flex; gap: 12px; + justify-content: flex-start; flex-wrap: wrap; animation: lp-fade-up 0.9s 0.4s ease both; } +@media (max-width: 920px) { + .lp-ctas { justify-content: center; } +} .lp-btn { - display: inline-flex; align-items: center; gap: 10px; - padding: 16px 28px; - font-size: 16px; font-weight: 600; - border-radius: 14px; + display: inline-flex; align-items: center; gap: 8px; + padding: 14px 24px; + font-size: 15px; font-weight: 700; + border-radius: 10px; text-decoration: none; transition: all 0.18s ease; cursor: pointer; border: none; + letter-spacing: -0.01em; } /* 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. @@ -265,8 +295,8 @@ /* ---------- Ticker strip ---------- */ .lp-ticker { - margin-top: 64px; - padding: 18px 0; + margin-top: 0; + padding: 16px 0; border-top: 1px solid var(--lp-line); border-bottom: 1px solid var(--lp-line); overflow: hidden; @@ -277,7 +307,7 @@ display: flex; gap: 48px; width: max-content; - animation: lp-scroll 40s linear infinite; + animation: lp-scroll 28s linear infinite; white-space: nowrap; } @keyframes lp-scroll { @@ -302,30 +332,30 @@ /* ---------- Section ---------- */ .lp-section { - padding: 80px 0; + padding: 72px 0; position: relative; } .lp-eyebrow { - font-size: 12px; - font-weight: 600; - letter-spacing: 0.16em; + font-size: 11px; + font-weight: 700; + letter-spacing: 0.14em; text-transform: uppercase; color: var(--lp-amber); - margin-bottom: 16px; + margin-bottom: 12px; } .lp-h2 { - font-size: clamp(30px, 4.5vw, 52px); - font-weight: 700; - letter-spacing: -0.025em; - line-height: 1.08; - margin: 0 0 20px; + font-size: clamp(26px, 3.8vw, 48px); + font-weight: 800; + letter-spacing: -0.03em; + line-height: 1.1; + margin: 0 0 16px; } .lp-lead { - max-width: 600px; - font-size: 17px; - line-height: 1.55; - color: var(--lp-ink-2); - margin: 0 0 40px; + max-width: 580px; + font-size: 16px; + line-height: 1.6; + color: var(--lp-ink-3); + margin: 0 0 36px; } /* ---------- Scroll reveal ---------- */ @@ -545,7 +575,7 @@ /* ---------- Final CTA ---------- */ .lp-cta-final { - padding: 120px 0; + padding: 88px 0 96px; text-align: center; position: relative; } @@ -1469,19 +1499,19 @@ /* ===== Mobile polish (≤720px / ≤480px) ===== */ @media (max-width: 720px) { .lp-wrap { padding: 0 16px; } - .lp-nav-inner { padding: 12px 16px; } + .lp-nav-inner { padding: 10px 16px; } .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 { min-height: auto; - padding: 48px 0 56px; + padding: 44px 0 52px; } .lp-h1 { - font-size: clamp(30px, 8.4vw, 56px); - margin-bottom: 18px; + font-size: clamp(28px, 8.0vw, 52px); + margin-bottom: 16px; } - .lp-sub { margin-bottom: 28px; font-size: 15px; } + .lp-sub { margin-bottom: 24px; font-size: 14px; } .lp-live-badge { font-size: 10px; padding: 6px 10px 6px 8px; @@ -1496,10 +1526,10 @@ .lp-ticker-track { gap: 24px; } .lp-ticker-item { font-size: 11px; } - .lp-section { padding: 60px 0; } - .lp-h2 { font-size: clamp(24px, 6.4vw, 40px); } - .lp-lead { font-size: 15px; } - .lp-eyebrow { font-size: 11px; } + .lp-section { padding: 52px 0; } + .lp-h2 { font-size: clamp(22px, 6.0vw, 38px); } + .lp-lead { font-size: 14px; } + .lp-eyebrow { font-size: 10px; } /* Terminal */ .lp-term { border-radius: 14px; } @@ -1535,7 +1565,7 @@ .lp-stat-val { font-size: 28px; } /* Final CTA */ - .lp-cta-final { padding: 64px 0 72px; } + .lp-cta-final { padding: 56px 0 64px; } } @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) ────────────────────────── */ .lp-herostats { - margin: 56px auto 0; - align-self: center; /* center inside .lp-hero flex column */ - display: inline-flex; align-items: stretch; gap: 28px; - padding: 18px 28px; + margin: 32px 0 0; + display: inline-flex; align-items: stretch; gap: 24px; + padding: 14px 20px; border: 1px solid var(--lp-line); border-radius: 16px; background: @@ -1697,6 +1843,9 @@ background: linear-gradient(180deg, transparent, var(--lp-line), transparent); align-self: stretch; } +@media (max-width: 960px) { + .lp-herostats { align-self: center; } +} @media (max-width: 560px) { .lp-herostats { gap: 16px; padding: 14px 18px; } } diff --git a/app/page.tsx b/app/page.tsx index da3852d..20d52dd 100644 --- a/app/page.tsx +++ b/app/page.tsx @@ -224,8 +224,9 @@ export default function LandingPage() { useCursorVars(rootRef as React.RefObject) // Decoded hero text — assembles from random glyphs on mount. - const heroLine1 = useScramble('Where crypto alpha actually lives —', 1100) - const heroLine2 = useScramble('all in one tab.', 1500) + const heroLine1 = useScramble('Trump. KOL. Macro.', 900) + const heroLine2 = useScramble('Six engines.', 1200) + const heroLine3 = useScramble('Always first.', 1500) // primaryRef / useMagnetic intentionally removed — the hero CTA is now a // static button. The hook is still defined above in case the effect is // reinstated on another element later. @@ -254,56 +255,74 @@ export default function LandingPage() {
{/* ---------- HERO ---------- */}
-
- - Six signal engines running · right now -
- -

- {heroLine1} -
- {heroLine2} -

- -

- 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’s tradeable. You sleep. It doesn’t. -

- -
- - Launch Dashboard - - - - See all six signals - -
- - {/* Live counter strip — animates in when hero is visible */} - - - - {/* Ticker strip */} -
-
- {[0, 1].map((k) => ( -
- - - - - - -
- ))} + {/* LEFT column */} +
+
+ + 6 signal engines · live right now
+ +

+ {heroLine1} +
+ {heroLine2} +
+ {heroLine3} +

+ +

+ AI reads every signal in under 3 seconds. + You’re in the position before the headline hits. +

+ +
+ + Launch Dashboard + + + + See all six signals + +
+ + {/* Engine chips — show breadth at a glance */} +
+ Trump Signal + Macro Vibes + KOL Signal + Talks vs Trades + Funding Reversal + Auto-Trader +
+ + {/* Live counter strip */} + +
+ + {/* RIGHT column — X-style live signal feed */} +
+
+ {/* Ticker strip — below the 2-col hero */} +
+
+ {[0, 1].map((k) => ( +
+ + + + + + +
+ ))} +
+
+ {/* ---------- FOUR PILLARS ---------- */} -
+
What runs inside

@@ -369,7 +388,7 @@ export default function LandingPage() {

{/* ---------- THE ENGINE (terminal block) — Pillar 1 deep-dive ---------- */} -
+
Pillar 1 · live engine

@@ -439,7 +458,7 @@ export default function LandingPage() {

{/* ---------- PRESS / HEADLINES ---------- */} -
+
Headlines you can Google

@@ -598,7 +617,7 @@ export default function LandingPage() {

{/* ---------- COMPARISON TABLE ---------- */} -
+
How it compares

@@ -631,7 +650,7 @@ export default function LandingPage() {

{/* ---------- WHAT IS TRUMP ALPHA (canonical definition for GEO) ---------- */} -
+
What is Trump Alpha

@@ -730,6 +749,76 @@ export default function LandingPage() { ) } +/* ---------- Live feed (hero right column) ---------- */ +function LiveFeed() { + return ( +
+
+ + Live signal feed + 3 today +
+ + + +
+ ) +} + +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 ( +
+
+ Donald Trump + @realDonaldTrump + {isNew && new} + {ts} +
+

{text}

+
+ + {t} + + {'asset' in signal && ( + <> + {signal.asset} + CONF {signal.conf} + + · {signal.action} + + + )} + {'skip' in signal && ( + · {signal.skip} + )} +
+
+ ) +} + /* ---------- Terminal row ---------- */ function TermRow({ isNew, diff --git a/components/dashboard/PostCards.tsx b/components/dashboard/PostCards.tsx index b5a7cf4..a1794be 100644 --- a/components/dashboard/PostCards.tsx +++ b/components/dashboard/PostCards.tsx @@ -1,6 +1,6 @@ 'use client' -import { useEffect, useState } from 'react' +import { memo, useEffect, useState } from 'react' import type { TrumpPost } from '@/types' function fmtPct(n: number | null | undefined) { @@ -93,7 +93,7 @@ interface PostRowProps { 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 impact = post.price_impact @@ -260,6 +260,7 @@ export default function PostRow({ post, selected, onClick }: PostRowProps) { )}

) -} +}) +export default PostRow export { SignalPill, SourceIcon, fmtPct, timeAgo, TimeAgo, LocalDateTime } diff --git a/components/nav/Navbar.tsx b/components/nav/Navbar.tsx index b6ff778..25051db 100644 --- a/components/nav/Navbar.tsx +++ b/components/nav/Navbar.tsx @@ -136,6 +136,7 @@ export default function Navbar() { key={tab.key} href={`/${locale}${tab.key === '/' ? '' : tab.key}`} className={`nav-tab ${isActive(tab.key) ? 'active' : ''}`} + prefetch > {tab.label} diff --git a/components/positions/OpenPositions.tsx b/components/positions/OpenPositions.tsx index 28a765e..46a190f 100644 --- a/components/positions/OpenPositions.tsx +++ b/components/positions/OpenPositions.tsx @@ -179,11 +179,20 @@ export default function OpenPositions() { useEffect(() => { setMounted(true) }, []) const [closeErr, setCloseErr] = useState('') const [growId, setGrowId] = useState(null) + // Separate error slot for the Grow toggle so a transient toggle failure + // doesn't squat in the panel-header `err` banner (which is otherwise + // owned by the 15s poll). Auto-clears after 4s. + const [growErr, setGrowErr] = useState('') + useEffect(() => { + if (!growErr) return + const t = setTimeout(() => setGrowErr(''), 4000) + return () => clearTimeout(t) + }, [growErr]) async function toggleGrow(p: OpenPosition) { if (!address || growId !== null) return const next = !p.grow_mode - setGrowId(p.trade_id) + setGrowId(p.trade_id); setGrowErr('') try { const env = await signRequest({ 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)) } catch (e) { if (isUserRejection(e)) { - setErr(isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled') + setGrowErr(isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled') } else { - setErr(walletErrorLabel(e, isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled', 90) + setGrowErr(walletErrorLabel(e, isZh ? 'Grow 切换已取消' : 'Grow toggle cancelled', 90) || (isZh ? 'Grow 切换失败' : 'grow toggle failed')) } } finally { setGrowId(null) } @@ -237,7 +246,12 @@ export default function OpenPositions() { void load() const id = setInterval(() => { void load() }, POLL_MS) 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. async function confirmCloseTrade() { @@ -257,8 +271,15 @@ export default function OpenPositions() { setClosing(null) setCloseState('idle') } catch (e: unknown) { - setCloseErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 120)) - setCloseState('err') + // Distinguish a user-cancelled signature (benign, close the modal) from + // a real failure (keep modal open in 'err' state so user can retry or + // read the error). + if (isUserRejection(e)) { + setClosing(null); setCloseState('idle'); setCloseErr('') + } else { + setCloseErr(walletErrorLabel(e, isZh ? '已取消' : 'Cancelled', 120)) + setCloseState('err') + } } } @@ -351,6 +372,9 @@ export default function OpenPositions() { {err && ( ● {err} )} + {growErr && !err && ( + ● {growErr} + )}
{/* Position list (or empty state) */} @@ -396,7 +420,14 @@ export default function OpenPositions() { presses "Close now", reads the impact summary, then confirms. */} {closing && (
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={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,0.55)', diff --git a/components/signals/SystemControl.tsx b/components/signals/SystemControl.tsx index 1dc9c55..fc30494 100644 --- a/components/signals/SystemControl.tsx +++ b/components/signals/SystemControl.tsx @@ -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 (autoOn === on) return + // Claim the busy slot BEFORE awaiting confirmSign — otherwise a rapid + // second click on the same pill (or the opposite pill) slips past the + // `if (busy) return` guard and queues a second sheet + second signature. + // We still clear it in `finally` below. + setBusy(true); setErr('') + // Show pre-signing confirmation sheet before triggering MetaMask const confirmed = await confirmSign(on ? { @@ -96,9 +102,8 @@ export default function SystemControl({ system }: { system: 'trump' | 'btc' }) { danger: false, } ) - if (!confirmed) return + if (!confirmed) { setBusy(false); return } // release the slot we claimed - setErr(''); setBusy(true) try { const env = await signRequest({ action: 'set_auto_trade', wallet: address, diff --git a/components/trades/BotConfigPanel.tsx b/components/trades/BotConfigPanel.tsx index 1b23e40..79a500e 100644 --- a/components/trades/BotConfigPanel.tsx +++ b/components/trades/BotConfigPanel.tsx @@ -389,7 +389,12 @@ export default function BotConfigPanel() { Paper 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" /> Live @@ -492,7 +497,15 @@ export default function BotConfigPanel() { )} {/* Live mode: show key input */} {!paperMode && (hlApiKeySet && !apiKey ? ( - + ) : (
From - { setFromLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
Until - { setUntilLocal(e.target.value); setDirty(true) }} style={{ width: 190 }} />
diff --git a/components/trades/TradeTable.tsx b/components/trades/TradeTable.tsx index 2d18dd7..4d90021 100644 --- a/components/trades/TradeTable.tsx +++ b/components/trades/TradeTable.tsx @@ -3,6 +3,7 @@ import { useState, useMemo } from 'react' import { useLocale } from 'next-intl' import type { BotTrade, TrumpPost } from '@/types' +import Pagination from '@/components/ui/Pagination' // ── Formatters ──────────────────────────────────────────────────────────────── function fmtMoney(n: number, opts: { sign?: boolean; decimals?: number } = {}) { @@ -28,8 +29,11 @@ interface Props { loading: boolean } -const ASSETS = ['all', 'BTC', 'ETH', 'SOL'] as const -const SIDES = ['all', 'long', 'short'] as const +// ASSETS filter is derived dynamically from the trade set (see useMemo below) +// so new assets (TRUMP, BNB, DOGE, LINK, AAVE, ...) appear automatically. +const SIDES = ['all', 'long', 'short'] as const + +const TRADES_PER_PAGE = 25 export default function TradeTable({ trades, posts, loading }: Props) { const locale = useLocale() @@ -38,6 +42,18 @@ export default function TradeTable({ trades, posts, loading }: Props) { const [sideFilter, setSideFilter] = useState('all') const [sourceFilter, setSourceFilter] = useState('all') const [hidePaper, setHidePaper] = useState(false) + const [page, setPage] = useState(1) + + // Distinct assets present in the loaded trade set — drives the asset filter. + // Dynamic so new perps (TRUMP, BNB, DOGE, LINK, AAVE, ...) appear without + // a code change; sorted alphabetically with BTC/ETH first for familiarity. + const assets: string[] = useMemo(() => { + const set = new Set() + for (const t of trades) if (t.asset) set.add(t.asset) + const priority = ['BTC', 'ETH', 'SOL', 'TRUMP'] + const rest = Array.from(set).filter(a => !priority.includes(a)).sort() + return ['all', ...priority.filter(a => set.has(a)), ...rest] + }, [trades]) // Distinct sources present in the loaded trade set — drives the filter UI. // Includes 'unknown' as a bucket for trades whose trigger post was deleted. @@ -65,13 +81,17 @@ export default function TradeTable({ trades, posts, loading }: Props) { return acc }, [trades]) - const filtered = trades.filter(t => { + const filtered = useMemo(() => trades.filter(t => { if (sourceFilter !== 'all' && (t.trigger_source || 'unknown') !== sourceFilter) return false if (assetFilter !== 'all' && t.asset !== assetFilter) return false if (sideFilter !== 'all' && t.side !== sideFilter) return false if (hidePaper && t.is_paper) return false return true - }) + }), [trades, sourceFilter, assetFilter, sideFilter, hidePaper]) + + const totalPages = Math.max(1, Math.ceil(filtered.length / TRADES_PER_PAGE)) + const safePage = Math.min(page, totalPages) + const pageRows = filtered.slice((safePage - 1) * TRADES_PER_PAGE, safePage * TRADES_PER_PAGE) // Exclude externally-closed trades (pnl_usd null) from aggregates. const priced = filtered.filter(t => t.pnl_usd !== null && t.pnl_usd !== undefined) @@ -111,7 +131,7 @@ export default function TradeTable({ trades, posts, loading }: Props) { return ( @@ -197,7 +217,7 @@ export default function TradeTable({ trades, posts, loading }: Props) { @@ -212,7 +232,7 @@ export default function TradeTable({ trades, posts, loading }: Props) { setHidePaper(e.target.checked)} + onChange={e => { setHidePaper(e.target.checked); setPage(1) }} /> {isZh ? '隐藏模拟交易' : 'Hide paper trades'} @@ -247,7 +267,7 @@ export default function TradeTable({ trades, posts, loading }: Props) { )} - {filtered.map(t => { + {pageRows.map(t => { const tp = posts.find(p => p.id === t.trigger_post_id) const roi = t.entry_price && t.exit_price != null @@ -326,6 +346,18 @@ export default function TradeTable({ trades, posts, loading }: Props) {
)} + + {/* Pagination */} + {!loading && ( + + )} ) } diff --git a/components/ui/Pagination.tsx b/components/ui/Pagination.tsx new file mode 100644 index 0000000..972769a --- /dev/null +++ b/components/ui/Pagination.tsx @@ -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 151–180 of 340 + * + * Active page uses brand orange. Ellipsis collapses distant pages. + * Prev/Next disabled at boundaries (dimmed, not hidden). + */ +export default function Pagination({ + page, total, count, pageSize, onChange, scrollTop = true, +}: PaginationProps) { + if (total <= 1) return null + + const from = (page - 1) * pageSize + 1 + const to = Math.min(page * pageSize, count) + + function go(p: number) { + if (p < 1 || p > total || p === page) return + onChange(p) + if (scrollTop) window.scrollTo({ top: 0, behavior: 'smooth' }) + } + + /** Page number list with ellipsis compression. */ + function pages(): (number | '…')[] { + if (total <= 7) return Array.from({ length: total }, (_, i) => i + 1) + const out: (number | '…')[] = [] + const push = (n: number | '…') => { + if (out[out.length - 1] !== n) out.push(n) + } + push(1) + if (page > 3) push('…') + for (let i = Math.max(2, page - 1); i <= Math.min(total - 1, page + 1); i++) push(i) + if (page < total - 2) push('…') + push(total) + return out + } + + return ( +
+ {/* ← Prev */} + go(page - 1)} disabled={page === 1} label="Previous page"> + + + + Prev + + + {/* Page numbers */} +
+ {pages().map((n, i) => + n === '…' ? ( + + ) : ( + + ) + )} +
+ + {/* Next → */} + go(page + 1)} disabled={page === total} label="Next page"> + Next + + + + + + {/* Count */} + + {from}–{to} of {count.toLocaleString()} + +
+ ) +} + +// ── 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 ( + + ) +} + +function NavBtn({ + onClick, disabled, label, children, +}: { + onClick: () => void; disabled: boolean; label: string; children: React.ReactNode +}) { + const [hover, setHover] = React.useState(false) + + return ( + + ) +} + +// ── 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', +} diff --git a/components/wallet/SignConfirmSheet.tsx b/components/wallet/SignConfirmSheet.tsx index d016e68..6b7a2b7 100644 --- a/components/wallet/SignConfirmSheet.tsx +++ b/components/wallet/SignConfirmSheet.tsx @@ -27,9 +27,18 @@ export interface SignConfirmOptions { danger?: boolean } +// Track the currently-mounted sheet so a second confirmSign() call can resolve +// the first one with `false` instead of leaving its promise dangling forever. +let _activeCancel: (() => void) | null = null + /** Renders a confirmation sheet and resolves true (confirm) or false (cancel). */ export function confirmSign(opts: SignConfirmOptions): Promise { return new Promise((resolve) => { + // If another sheet is already mounted, cancel it first so its awaiting + // caller resolves with `false` rather than hanging indefinitely. + if (_activeCancel) { + try { _activeCancel() } catch { /* ignore */ } + } const existing = document.getElementById('sign-confirm-sheet-root') if (existing?.parentNode) { existing.parentNode.removeChild(existing) @@ -43,6 +52,9 @@ export function confirmSign(opts: SignConfirmOptions): Promise { function cleanup(result: boolean) { if (settled) return settled = true + // Clear the active-cancel slot only if it still points to *this* sheet — + // a later confirmSign() may have already replaced it. + if (_activeCancel === cancelSelf) _activeCancel = null root.unmount() if (container.parentNode) { container.parentNode.removeChild(container) @@ -50,7 +62,11 @@ export function confirmSign(opts: SignConfirmOptions): Promise { resolve(result) } - root.render( 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( cleanup(true)} onCancel={cancelSelf} />) }) } diff --git a/lib/api.ts b/lib/api.ts index 2246a3e..02e41a9 100644 --- a/lib/api.ts +++ b/lib/api.ts @@ -37,7 +37,9 @@ export async function getPost(id: number): Promise { return fetchJson(`/posts/${id}`) } -export async function getPrices(asset: 'BTC' | 'ETH', tf: string): Promise { +// 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 { return fetchJson(`/prices/${asset}?tf=${tf}`) } diff --git a/lib/useRealtimeData.ts b/lib/useRealtimeData.ts index 9cbded9..402a94b 100644 --- a/lib/useRealtimeData.ts +++ b/lib/useRealtimeData.ts @@ -3,11 +3,13 @@ import { useWsSubscribe } from './wsContext' 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 } -type PriceMsg = { type: 'price'; asset: 'BTC' | 'ETH'; price: number } +type PriceMsg = { type: 'price'; asset: string; price: number } type PostMsg = { type: 'new_post'; post: object } /** diff --git a/lib/wsContext.tsx b/lib/wsContext.tsx index c9aedd4..c7c0db3 100644 --- a/lib/wsContext.tsx +++ b/lib/wsContext.tsx @@ -29,6 +29,15 @@ const WsContext = createContext(null) 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 }) { // Stable map: message-type → set of handlers. Never replaced, only mutated. const subs = useRef>>(new Map()) @@ -36,10 +45,7 @@ export function WsProvider({ children }: { children: ReactNode }) { useEffect(() => { let dead = false let retryTimer: ReturnType | null = null - // Hold the current socket at useEffect scope so cleanup can close it. - // 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 attempt = 0 let socket: WebSocket | null = null function connect() { @@ -47,6 +53,10 @@ export function WsProvider({ children }: { children: ReactNode }) { socket = new WebSocket(`${WS_URL}/ws/prices`) const ws = socket // local alias for handler closures + ws.onopen = () => { + attempt = 0 // reset backoff on successful connection + } + ws.onmessage = (e) => { try { const msg = JSON.parse(e.data) as { type?: string } @@ -58,14 +68,34 @@ export function WsProvider({ children }: { children: ReactNode }) { } ws.onclose = () => { - if (!dead) retryTimer = setTimeout(connect, 3000) + if (!dead) { + const delay = retryDelay(attempt++) + retryTimer = setTimeout(connect, delay) + } } 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() return () => { dead = true + document.removeEventListener('visibilitychange', onVisible) if (retryTimer) clearTimeout(retryTimer) // Actively close any live socket so the OS-level connection releases // immediately on unmount instead of waiting for the next server keepalive. diff --git a/messages/en.json b/messages/en.json index 5771836..6fec3b4 100644 --- a/messages/en.json +++ b/messages/en.json @@ -8,7 +8,7 @@ "kol": "KOL", "trades": "Trades", "analytics": "Analytics", - "settings": "Settings" + "settings": "Config" }, "actions": { "connectWallet": "Connect wallet", diff --git a/next.config.mjs b/next.config.mjs index 9345373..72f53a1 100644 --- a/next.config.mjs +++ b/next.config.mjs @@ -5,6 +5,7 @@ const withNextIntl = createNextIntlPlugin('./i18n.ts') /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, + allowedDevOrigins: ['*'], async rewrites() { return [ { diff --git a/package-lock.json b/package-lock.json index d856e64..2280bcb 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "trumpsignal", "version": "0.1.0", "dependencies": { + "@parcel/watcher-linux-arm64-glibc": "*", "@rainbow-me/rainbowkit": "^2.1.3", "@tanstack/react-query": "^5.40.0", "lightweight-charts": "^4.1.3", @@ -32,6 +33,9 @@ }, "engines": { "node": ">=20.19.0" + }, + "optionalDependencies": { + "@parcel/watcher-linux-arm64-glibc": "^2.5.6" } }, "node_modules/@adraffy/ens-normalize": { @@ -2358,6 +2362,7 @@ "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "linux" diff --git a/package.json b/package.json index f719497..0584fe5 100644 --- a/package.json +++ b/package.json @@ -34,5 +34,8 @@ "postcss": "^8", "tailwindcss": "^3.4.4", "typescript": "^5" + }, + "optionalDependencies": { + "@parcel/watcher-linux-arm64-glibc": "^2.5.6" } } diff --git a/public/llms.txt b/public/llms.txt index 0ca4303..1edf700 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -40,7 +40,7 @@ Optional: bring your own Hyperliquid account for auto-trading. - Backend: Python / FastAPI - AI: Claude (Anthropic) for signal extraction - On-chain: Etherscan API + Hyperliquid public API -- Frontend: Next.js 14 +- Frontend: Next.js 16 ## URLs diff --git a/store/dashboard.ts b/store/dashboard.ts index bcf621c..0e4d9e2 100644 --- a/store/dashboard.ts +++ b/store/dashboard.ts @@ -9,7 +9,9 @@ interface DashboardState { botReadiness: 'unknown' | 'saved' | 'verified' | 'ready' hlApiKeySet: boolean // true if user already has a key saved in backend 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 setSelectedPost: (id: number | null) => void setAsset: (asset: 'BTC' | 'ETH') => void setTimeframe: (tf: '5m' | '15m' | '1H' | '4H' | '1D' | '1W') => void @@ -17,7 +19,7 @@ interface DashboardState { setSubscribed: (subscribed: boolean) => void setBotReadiness: (state: DashboardState['botReadiness']) => void setHlApiKeySet: (set: boolean, masked?: string) => void - setLivePrice: (asset: 'BTC' | 'ETH', price: number) => void + setLivePrice: (asset: string, price: number) => void } export const useDashboardStore = create((set) => ({ @@ -29,7 +31,7 @@ export const useDashboardStore = create((set) => ({ botReadiness: 'unknown', hlApiKeySet: false, hlApiKeyMasked: null, - livePrices: { BTC: null, ETH: null }, + livePrices: { BTC: null, ETH: null, SOL: null, TRUMP: null }, setSelectedPost: (id) => set({ selectedPostId: id }), setAsset: (asset) => set({ asset }), setTimeframe: (timeframe) => set({ timeframe }), diff --git a/types/index.ts b/types/index.ts index bde95a5..73fc87e 100644 --- a/types/index.ts +++ b/types/index.ts @@ -18,7 +18,9 @@ export interface TrumpPost { category: string | null expected_move_pct: number | null 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) m15: number | null m1h: number | null @@ -66,7 +68,7 @@ export interface BotPerformance { } // ── KOL module ──────────────────────────────────────────────────── -export type KolAction = 'buy' | 'sell' | 'bullish' | 'bearish' | 'mention' +export type KolAction = 'buy' | 'sell' | 'reduce' | 'bullish' | 'bearish' | 'mention' export interface KolTicker { ticker: string