Production polish: i18n shelved, PWA icons, SEO/GEO cleanup, UX fixes

Big-picture changes since 01be8e7:

New routes — /trump /btc /kol /trades /analytics /archive plus four
SEO landing pages (/methodology /glossary /case-studies /contact),
all served under /[locale]. Each has dedicated metadata + JSON-LD.

KOL page (new) — DigestWidget + OnchainWidget + TalkVsTradesWidget,
filter by handle/ticker, click-through to per-post detail with the
original AI-extracted ticker/conviction/quote.

BTC page (new) — tabbed: macro-bottom (AHR999 + 200WMA + Pi Cycle)
and funding-rate reversal, with live sparkline + threshold bands.

Telegram card on Settings — wallet-link code generation, status,
disconnect. Preferences moved into the bot itself (/trump /btc etc.)
so the card stays minimal.

SignalMonitor (new) — ETH/LINK Bollinger breakout monitor in its own
component, shares the singleton WsProvider so no second WS opens.

WS singleton refactor (lib/wsContext) — shared WsProvider + useWsSubscribe
hook. Cleanup now actively closes the socket on unmount; previously the
local `ws` couldn't be reached from cleanup and leaked one connection
per StrictMode remount.

OpenPositions polling no longer pops MetaMask in the background —
splits into load('first') for user-initiated and load('poll') that
uses getCachedViewEnvelope without signing.

i18n shelved — proxy.ts (Next 16 middleware rename) wires next-intl
but only Navbar + layout footer have translations. Rest of UI used
isZh ternary scattered across 28 files. All `const isZh = locale === 'zh'`
flipped to `const isZh = false` so every site renders English; Chinese
branches kept as dead code so revival is one regex away.
LanguageSwitch hidden but file kept. zh-CN hreflang removed from
metadata + sitemap to avoid duplicate-content penalties.

Wallet error handling — lib/walletError.ts: isUserRejection walks EIP-1193
code 4001 + .cause chain; previous string-match for "reject"/"denied"
broke for users running MetaMask in non-English UIs. 12 call sites
migrated across 5 components.

PWA icons — app/icon.tsx + app/apple-icon.tsx render the brand "α" via
Next's ImageResponse so no static PNG asset is required. manifest.ts
references /icon and /apple-icon dynamic routes.

OG image + sitemap + robots — dynamic 1200×630 OG card; robots blocks
both /en/settings and /zh/settings; sitemap only emits /en routes;
JSON-LD covers SoftwareApplication + Organization + 10-Q FAQPage.

Landing page polish — Launch Dashboard button stripped of magnetic
hover + shimmer + lift + glow expansion (multiple users found it busy);
hero scramble alphabet swapped to alphanumeric (was block characters);
"15 KOL feeds" copy updated to 19 in 5 places.

PostCards source icons — new entries for btc_bottom_reversal,
funding_reversal, kol_divergence so they no longer fall through to
the generic "first letter" fallback.

Archive page filter — excludes funding_reversal + kol_divergence
(previously only excluded truth + btc_bottom_reversal so new live
signals leaked into the legacy archive).

Cache + skeleton loading — lib/cache.ts SWR module with per-key TTL,
applied across the major pages so navigation feels instant.

SignConfirmSheet — 4 hardcoded Chinese strings translated to English
(English users were seeing zh-only "需要钱包签名" etc).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
k
2026-05-25 00:53:27 +08:00
parent 01be8e790b
commit d72323b1c6
67 changed files with 11735 additions and 2530 deletions
+420 -9
View File
@@ -1,10 +1,20 @@
import type { TrumpPost, Candle, BotTrade, BotPerformance } from '@/types'
import type {
TrumpPost, Candle, BotTrade, BotPerformance,
KolPostSummary, KolPostDetail, KolDigest,
KolWallet, KolHoldingChange, KolDivergence,
} from '@/types'
import type { SignedEnvelope } from './signedRequest'
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
function getApiOrigin() {
return typeof window === 'undefined'
? `${BASE_URL}/api`
: '/api/proxy/api'
}
async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${BASE_URL}/api${path}`, {
const res = await fetch(`${getApiOrigin()}${path}`, {
headers: { 'Content-Type': 'application/json' },
...init,
})
@@ -31,18 +41,42 @@ export async function getPrices(asset: 'BTC' | 'ETH', tf: string): Promise<Candl
return fetchJson<Candle[]>(`/prices/${asset}?tf=${tf}`)
}
export async function getTrades(limit = 20, page = 1): Promise<BotTrade[]> {
return fetchJson<BotTrade[]>(`/trades?limit=${limit}&page=${page}`)
export async function getTrades(
wallet: string,
env: SignedEnvelope,
limit = 20,
page = 1,
): Promise<BotTrade[]> {
const qs = [
`wallet=${wallet.toLowerCase()}`,
`ts=${env.timestamp}`,
`sig=${encodeURIComponent(env.signature)}`,
`limit=${limit}`,
`page=${page}`,
].join('&')
return fetchJson<BotTrade[]>(`/trades?${qs}`)
}
export async function getPerformance(): Promise<BotPerformance> {
return fetchJson<BotPerformance>(`/performance`)
export async function getPerformance(
wallet: string,
env: SignedEnvelope,
): Promise<BotPerformance> {
const qs = `wallet=${wallet.toLowerCase()}&ts=${env.timestamp}&sig=${encodeURIComponent(env.signature)}`
return fetchJson<BotPerformance>(`/performance?${qs}`)
}
export async function subscribe(env: SignedEnvelope): Promise<{ status: string; wallet: string }> {
return fetchJson<{ status: string; wallet: string }>(`/subscribe`, {
export async function subscribe(
env: SignedEnvelope,
options: { paper_mode?: boolean } = {},
): Promise<{ status: string; wallet: string; paper_mode: boolean }> {
// paper_mode is a top-level body field (not nested) so the canonical
// signed body matches the backend's expectation: { paper_mode: true } | null.
const payload = options.paper_mode
? { ...env, paper_mode: true }
: env
return fetchJson<{ status: string; wallet: string; paper_mode: boolean }>(`/subscribe`, {
method: 'POST',
body: JSON.stringify(env),
body: JSON.stringify(payload),
})
}
@@ -53,6 +87,13 @@ export interface UserSettings {
stop_loss_pct: number | null
min_confidence: number
daily_budget_usd: number | null
/** System-2 (bottom reversal) leverage, 110. null = platform default.
* Independent of `leverage` (Trump). The protective stop auto-scales to
* this so the position is never exchange-liquidated. */
sys2_leverage: number | null
/** System-2 risk mode: 'standard' (cycle-rider) or 'aggressive'
* (separately-funded high-risk/high-explosiveness sleeve). */
sys2_mode?: 'standard' | 'aggressive' | null
active_from: string | null // ISO UTC
active_until: string | null // ISO UTC
}
@@ -65,6 +106,8 @@ export interface UserData {
hl_api_key_masked: string | null
trades: BotTrade[]
settings: UserSettings
/** ISO-UTC timestamp until which the bot is manually armed (null = use schedule). */
manual_window_until: string | null
}
export async function setUserSettings(
@@ -81,6 +124,181 @@ export interface UserPublic {
wallet_address: string
active: boolean
hl_api_key_set: boolean
/** Phase 1 operational state — surfaced on /signals page. */
paper_mode?: boolean
manual_window_until?: string | null
circuit_breaker_tripped_at?: string | null
circuit_breaker_reason?: string | null
/** Master Auto-Trade gate. false (default) = signals shown, not traded. */
auto_trade?: boolean
}
export interface SignalSource {
source: string
count: number
latest: string | null
}
export async function getSignalSources(): Promise<{ sources: SignalSource[] }> {
return fetchJson<{ sources: SignalSource[] }>(`/signals/sources`)
}
/**
* Toggle paper mode for a wallet. Hits the dev endpoint — no signature
* required. Only available in development environments where the dev router
* is mounted; in production this will 404.
*/
export async function setPaperMode(
wallet: string,
enabled: boolean,
): Promise<{ status: string; paper_mode: boolean }> {
return fetchJson<{ status: string; paper_mode: boolean }>(
`/dev/paper-mode?wallet=${wallet.toLowerCase()}&enabled=${enabled}`,
{ method: 'POST' },
)
}
// ─── Open positions + today stats ───────────────────────────────────────────
export interface OpenPosition {
trade_id: number
asset: string
side: 'long' | 'short'
entry_price: number
current_price: number | null
size_usd: number | null
leverage: number | null
opened_at: string
hold_minutes: number
unrealized_pct: number | null
unrealized_usd: number | null
is_paper: boolean
trigger_post_id: number | null
/** System-2 staged lifecycle. size_usd above is the OPEN notional after
* de-risk; realized_usd is PnL already banked by partial de-risk. */
realized_usd?: number | null
derisk_steps?: number
addon_steps?: number
/** Per-trade pyramiding switch. */
grow_mode?: boolean
}
export interface OpenPositionsResponse {
wallet: string
count: number
positions: OpenPosition[]
}
export interface TodayStats {
wallet: string
realized_pnl_usd: number
trades_closed: number
wins: number
losses: number
open_count: number
/** Cumulative PnL banked by staged de-risk on still-open positions.
* Shown separately — not part of realized_pnl_usd (closed trades only). */
open_realized_usd?: number
}
export async function getOpenPositions(
wallet: string,
env: SignedEnvelope,
): Promise<OpenPositionsResponse> {
const qs = `wallet=${wallet.toLowerCase()}&ts=${env.timestamp}&sig=${encodeURIComponent(env.signature)}`
return fetchJson<OpenPositionsResponse>(`/positions/open?${qs}`)
}
export async function getTodayStats(
wallet: string,
env: SignedEnvelope,
): Promise<TodayStats> {
const qs = `wallet=${wallet.toLowerCase()}&ts=${env.timestamp}&sig=${encodeURIComponent(env.signature)}`
return fetchJson<TodayStats>(`/positions/today?${qs}`)
}
// ─── Scanner control (module 2) ─────────────────────────────────────────────
export interface ScannerSummary {
name: string
enabled: boolean
last_run_at: string | null
last_status: string
last_message: string | null
last_fired_at: string | null
total_runs: number
total_fires: number
consecutive_errors: number
}
export interface ScannersResponse {
count: number
enabled: number
scanners: ScannerSummary[]
}
export async function getScanners(): Promise<ScannersResponse> {
return fetchJson<ScannersResponse>(`/scanners`)
}
/**
* Toggle ONE scanner. Signed + subscriber-gated on the backend: the wallet
* must own the signature AND already be a subscriber. The signed body is
* { enabled, name } — must match the backend's canonical hash exactly.
*/
export async function toggleScanner(
env: SignedEnvelope,
name: string,
enabled: boolean,
): Promise<{ status: string; name: string; enabled: boolean }> {
return fetchJson<{ status: string; name: string; enabled: boolean }>(
`/scanners/${name}/toggle`,
{
method: 'POST',
body: JSON.stringify({ ...env, name, enabled }),
},
)
}
export async function killAllScanners(
env: SignedEnvelope,
): Promise<{ status: string; count: number }> {
return fetchJson<{ status: string; count: number }>(
`/scanners/all/disable`,
{ method: 'POST', body: JSON.stringify(env) },
)
}
export async function reviveAllScanners(
env: SignedEnvelope,
): Promise<{ status: string; count: number }> {
return fetchJson<{ status: string; count: number }>(
`/scanners/all/enable`,
{ method: 'POST', body: JSON.stringify(env) },
)
}
export interface CloseTradeResponse {
status: string
trade_id: number
exit_price: number | null
pnl_usd: number | null
reason: string
note: string | null
}
/**
* Manual emergency close. Requires a signed envelope produced for the action
* "close_trade" with body { trade_id }. The backend re-checks wallet ownership.
*/
export async function manualCloseTrade(
env: SignedEnvelope,
trade_id: number,
): Promise<CloseTradeResponse> {
return fetchJson<CloseTradeResponse>(`/positions/${trade_id}/close`, {
method: 'POST',
body: JSON.stringify({ ...env, trade_id }),
})
}
/** No-auth boolean state. Safe to call on every page load. */
@@ -97,6 +315,29 @@ export async function getUser(
return fetchJson<UserData>(`/user/${wallet.toLowerCase()}?${qs}`)
}
export interface WindowAccuracy {
checked: number
correct: number
accuracy_pct: number
}
export interface SignalAccuracyEntry {
count: number
m5: WindowAccuracy
m15: WindowAccuracy
m1h: WindowAccuracy
}
export interface SignalAccuracy {
overall: { m5: WindowAccuracy; m15: WindowAccuracy; m1h: WindowAccuracy }
by_signal: Record<string, SignalAccuracyEntry>
total_directional_signals: number
}
export async function getSignalAccuracy(): Promise<SignalAccuracy> {
return fetchJson<SignalAccuracy>(`/signals/accuracy`)
}
export async function setHlApiKey(
env: SignedEnvelope,
api_key: string,
@@ -109,3 +350,173 @@ export async function setHlApiKey(
},
)
}
/**
* Arm (or clear) the manual-window override. Pass `hours = 0` to disarm.
* Backend stores `manual_window_until = now + hours`; when in the future the
* bot trades regardless of the schedule.
*/
/** Master Auto-Trade switch (signed). enabled=true also acknowledges +
* clears a tripped circuit breaker. */
export async function setAutoTrade(
env: SignedEnvelope,
enabled: boolean,
): Promise<{ auto_trade: boolean; circuit_breaker_cleared: boolean }> {
return fetchJson<{ auto_trade: boolean; circuit_breaker_cleared: boolean }>(
`/user/${env.wallet}/auto-trade`,
{ method: 'POST', body: JSON.stringify({ ...env, enabled }) },
)
}
/** Per-trade Grow (pyramiding) switch (signed). */
export async function setTradeGrow(
env: SignedEnvelope,
trade_id: number,
enabled: boolean,
): Promise<{ trade_id: number; grow_mode: boolean }> {
return fetchJson<{ trade_id: number; grow_mode: boolean }>(
`/positions/${trade_id}/grow`,
{ method: 'POST', body: JSON.stringify({ ...env, trade_id, enabled }) },
)
}
export async function setManualWindow(
env: SignedEnvelope,
hours: number,
): Promise<{ manual_window_until: string | null }> {
return fetchJson<{ manual_window_until: string | null }>(
`/user/${env.wallet}/manual-window`,
{
method: 'POST',
body: JSON.stringify({ ...env, hours }),
},
)
}
// ── KOL module ────────────────────────────────────────────────────
export async function getKolPosts(opts: {
handle?: string; source?: string; limit?: number; page?: number
} = {}): Promise<{ items: KolPostSummary[]; page: number; limit: number }> {
const p = new URLSearchParams()
if (opts.handle) p.set('handle', opts.handle)
if (opts.source) p.set('source', opts.source)
p.set('limit', String(opts.limit ?? 50))
p.set('page', String(opts.page ?? 1))
return fetchJson(`/kol/posts?${p.toString()}`)
}
export async function getKolPost(id: number): Promise<KolPostDetail> {
return fetchJson<KolPostDetail>(`/kol/posts/${id}`)
}
export async function getKolDigest(days = 7): Promise<KolDigest> {
return fetchJson<KolDigest>(`/kol/digest?days=${days}`)
}
export async function getKolWallets(handle?: string): Promise<{ wallets: KolWallet[] }> {
const p = handle ? `?handle=${handle}` : ''
return fetchJson<{ wallets: KolWallet[] }>(`/kol/wallets${p}`)
}
export async function addKolWallet(body: {
handle: string; chain: string; address: string; label?: string; source_url?: string
}): Promise<KolWallet> {
return fetchJson<KolWallet>(`/kol/wallets`, {
method: 'POST',
body: JSON.stringify(body),
})
}
export async function getKolChanges(opts: {
handle?: string; days?: number
} = {}): Promise<{ window_days: number; since: string; count: number; changes: KolHoldingChange[] }> {
const p = new URLSearchParams()
if (opts.handle) p.set('handle', opts.handle)
p.set('days', String(opts.days ?? 7))
return fetchJson(`/kol/changes?${p.toString()}`)
}
export async function getKolDivergence(opts: {
handle?: string; ticker?: string; signal_type?: 'divergence' | 'alignment'; days?: number
} = {}): Promise<{ window_days: number; since: string; count: number; items: KolDivergence[] }> {
const p = new URLSearchParams()
if (opts.handle) p.set('handle', opts.handle)
if (opts.ticker) p.set('ticker', opts.ticker)
if (opts.signal_type) p.set('signal_type', opts.signal_type)
p.set('days', String(opts.days ?? 30))
return fetchJson(`/kol/divergence?${p.toString()}`)
}
// ── Funding rate reversal (BTC tab) ─────────────────────────────────────────
export interface FundingSnapshot {
ok: boolean
error?: string
asset?: string
cadence_hours?: number
coverage_days?: number
latest_rate_pct?: number
last_24h_avg_pct?: number
cum_30d_pct?: number
extreme_threshold_pct?: number
signal_fired?: boolean
debug?: { reason?: string; direction?: string; [k: string]: unknown }
history?: { t: number; rate_pct: number }[]
}
export async function getFundingSnapshot(): Promise<FundingSnapshot> {
return fetchJson<FundingSnapshot>('/funding/snapshot')
}
// ── Telegram alerts ─────────────────────────────────────────────────────────
export interface TelegramStatus {
configured: boolean
bot_username: string | null
bound: boolean
wallet_address?: string | null
tg_username?: string | null
chat_id?: number | null
alerts_enabled?: boolean | null
alert_trump?: boolean | null
alert_btc_bottom?: boolean | null
alert_funding?: boolean | null
alert_kol_divergence?: boolean | null
min_confidence?: number | null
mute_from_hour?: number | null
mute_until_hour?: number | null
total_alerts_sent?: number | null
}
export interface TelegramInitResp {
code: string; deep_link: string; expires_in_seconds: number
}
export async function getTelegramStatus(wallet: string): Promise<TelegramStatus> {
return fetchJson<TelegramStatus>(`/telegram/${wallet}/status`)
}
// SignedEnvelope is already imported at the top of this file. Below we
// reuse it directly for the Telegram helpers — no separate alias needed.
export async function tgInit(wallet: string, env: SignedEnvelope): Promise<TelegramInitResp> {
return fetchJson(`/telegram/${wallet}/init`, {
method: 'POST', body: JSON.stringify(env),
})
}
export async function tgUnbind(wallet: string, env: SignedEnvelope): Promise<{ removed: number }> {
return fetchJson(`/telegram/${wallet}/unbind`, {
method: 'POST', body: JSON.stringify(env),
})
}
export async function tgTest(wallet: string, env: SignedEnvelope): Promise<{ sent: boolean }> {
return fetchJson(`/telegram/${wallet}/test`, {
method: 'POST', body: JSON.stringify(env),
})
}
export async function tgPreferences(
wallet: string,
env: SignedEnvelope,
prefs: Partial<{
alerts_enabled: boolean; alert_trump: boolean; alert_btc_bottom: boolean
alert_funding: boolean; alert_kol_divergence: boolean
min_confidence: number; mute_from_hour: number; mute_until_hour: number
}>,
): Promise<TelegramStatus> {
return fetchJson(`/telegram/${wallet}/preferences`, {
method: 'POST', body: JSON.stringify({ ...env, ...prefs }),
})
}
+69
View File
@@ -0,0 +1,69 @@
/**
* Lightweight in-memory SWR cache for API data.
*
* Lives at module scope — persists across React renders and page navigations
* within the same browser tab, but clears on hard-refresh / tab close.
*
* Usage:
* const data = await swrFetch('posts-500', 3 * 60_000, () => getPosts(500))
*
* On first call → fetches, caches, returns.
* On subsequent calls within TTL → returns cached data immediately.
* On calls after TTL → returns stale data immediately AND triggers a
* background revalidation; the `onUpdate` callback fires when fresh
* data arrives so the component can re-render without a loading flash.
*/
interface CacheEntry<T> {
data: T
ts: number
revalidating: boolean
}
const store = new Map<string, CacheEntry<unknown>>()
export async function swrFetch<T>(
key: string,
ttlMs: number,
fetcher: () => Promise<T>,
onUpdate?: (fresh: T) => void,
): Promise<T> {
const now = Date.now()
const hit = store.get(key) as CacheEntry<T> | undefined
if (hit) {
const age = now - hit.ts
if (age < ttlMs) {
// Still fresh — return immediately.
return hit.data
}
// Stale — return immediately AND revalidate in background.
if (!hit.revalidating) {
hit.revalidating = true
fetcher()
.then(fresh => {
store.set(key, { data: fresh, ts: Date.now(), revalidating: false })
onUpdate?.(fresh)
})
.catch(() => {
if (hit) hit.revalidating = false
})
}
return hit.data
}
// Cache miss — must wait for the first fetch.
const data = await fetcher()
store.set(key, { data, ts: Date.now(), revalidating: false })
return data
}
/** Manually invalidate a cache key (e.g. after a write action). */
export function invalidate(key: string) {
store.delete(key)
}
/** Peek at whether a key has any cached data (stale or fresh). */
export function hasCached(key: string): boolean {
return store.has(key)
}
+1 -1
View File
@@ -53,7 +53,7 @@ export interface SignedEnvelope {
* within a 4-minute window (server accepts 5-min skew). Backend's replay-guard
* is disabled for the view action so the same sig can be used multiple times.
*/
const VIEW_TTL_MS = 4 * 60 * 1000
const VIEW_TTL_MS = 20 * 60 * 1000 // 20 min — backend's replay-guard is disabled for view actions
/**
* Read-only: returns a cached, not-yet-expired view envelope if one exists.
+16 -51
View File
@@ -1,62 +1,27 @@
'use client'
import { useEffect, useRef, useCallback } from 'react'
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8000'
type PriceUpdate = { type: 'price'; asset: 'BTC' | 'ETH'; price: number }
type PostUpdate = { type: 'new_post'; post: object }
type WsMessage = PriceUpdate | PostUpdate
import { useWsSubscribe } from './wsContext'
interface Handlers {
onPrice?: (asset: 'BTC' | 'ETH', price: number) => void
onNewPost?: (post: object) => void
}
type PriceMsg = { type: 'price'; asset: 'BTC' | 'ETH'; price: number }
type PostMsg = { type: 'new_post'; post: object }
/**
* Subscribe to price ticks and new-post events from the shared WebSocket.
* Delegates to WsProvider's singleton connection — no new socket is opened.
*/
export function usePriceSocket(handlers: Handlers) {
const wsRef = useRef<WebSocket | null>(null)
const handlersRef = useRef(handlers)
const unmountedRef = useRef(false)
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
handlersRef.current = handlers
useWsSubscribe('price', (msg) => {
const m = msg as PriceMsg
handlers.onPrice?.(m.asset, m.price)
})
const connect = useCallback(() => {
if (unmountedRef.current) return
const ws = new WebSocket(`${WS_URL}/ws/prices`)
wsRef.current = ws
ws.onmessage = (e) => {
try {
const msg: WsMessage = JSON.parse(e.data)
if (msg.type === 'price' && handlersRef.current.onPrice) {
handlersRef.current.onPrice(msg.asset, msg.price)
} else if (msg.type === 'new_post' && handlersRef.current.onNewPost) {
handlersRef.current.onNewPost(msg.post)
}
} catch (err) {
console.warn('[WS] malformed message:', e.data, err)
}
}
ws.onclose = () => {
// Don't schedule a reconnect if the component already unmounted —
// otherwise we leak a socket per navigation forever.
if (unmountedRef.current) return
reconnectTimerRef.current = setTimeout(connect, 3000)
}
ws.onerror = () => {
ws.close()
}
}, [])
useEffect(() => {
unmountedRef.current = false
connect()
return () => {
unmountedRef.current = true
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current)
wsRef.current?.close()
}
}, [connect])
useWsSubscribe('new_post', (msg) => {
const m = msg as PostMsg
handlers.onNewPost?.(m.post)
})
}
+11 -1
View File
@@ -1,4 +1,4 @@
import { createConfig, http } from 'wagmi'
import { createConfig, createStorage, http } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { metaMask } from 'wagmi/connectors'
@@ -10,4 +10,14 @@ export const config = createConfig({
transports: {
[mainnet.id]: http(),
},
// sessionStorage: clears on tab close, prevents stale auto-reconnect across sessions.
// This means MetaMask only pops when the user explicitly clicks "Connect wallet".
storage: typeof window !== 'undefined'
? createStorage({ storage: window.sessionStorage })
: undefined,
// Disable silent auto-reconnect on page mount.
// Without this, wagmi checks localStorage/sessionStorage for a saved connector
// and tries to reconnect MetaMask silently — which can pop the MetaMask window.
// User must explicitly click "Connect wallet" each session.
ssr: true,
})
+39
View File
@@ -0,0 +1,39 @@
/**
* MetaMask / EIP-1193 wallet error helpers.
*
* Previously the codebase detected user rejections by string-matching the
* error message for "reject" or "denied". That breaks when MetaMask's UI
* language is set to anything other than English (the message is translated
* but our match string isn't). The reliable signal is the EIP-1193 error
* code: 4001 = "User rejected the request".
*
* Wagmi sometimes wraps the underlying provider error inside `.cause`, so we
* walk that chain too.
*/
interface WithCode { code?: number | string; cause?: unknown }
export function isUserRejection(err: unknown): boolean {
// Walk a small depth of .cause chains since wagmi/viem wrap provider errors
let cur: unknown = err
for (let i = 0; i < 4 && cur; i++) {
const c = (cur as WithCode)?.code
if (c === 4001 || c === 'ACTION_REJECTED' || c === 'USER_REJECTED') return true
cur = (cur as WithCode)?.cause
}
// Last-resort string fallback for providers that don't expose a code field.
// Kept narrow — "reject" + "denied" + a couple of locale variants we've
// actually seen from MetaMask zh-CN ("拒绝") and Rabby ("rejected by user").
const m = err instanceof Error ? err.message : ''
return /reject|denied|cancell|拒绝|已取消/i.test(m)
}
/**
* Convenience: return either a friendly cancellation label or a truncated
* version of the real error message — never raw user-facing crash text.
*/
export function walletErrorLabel(err: unknown, cancelledLabel = 'Cancelled', maxLen = 110): string {
if (isUserRejection(err)) return cancelledLabel
const m = err instanceof Error ? err.message : String(err ?? '')
return m.slice(0, maxLen) || 'unknown error'
}
+110
View File
@@ -0,0 +1,110 @@
'use client'
/**
* Singleton WebSocket provider.
*
* The entire app shares ONE connection to /ws/prices. Components subscribe
* to specific message types via `useWsSubscribe` — no component owns the socket.
*
* Why: previously DashboardClient (via usePriceSocket) and SignalMonitor each
* opened their own WebSocket, giving the server two connections per page load
* and causing each component to receive every broadcast twice.
*/
import {
createContext,
useContext,
useEffect,
useRef,
type ReactNode,
} from 'react'
type Handler = (msg: unknown) => void
interface WsContextValue {
subscribe: (type: string, fn: Handler) => () => void
}
const WsContext = createContext<WsContextValue | null>(null)
const WS_URL = process.env.NEXT_PUBLIC_WS_URL || 'ws://localhost:8000'
export function WsProvider({ children }: { children: ReactNode }) {
// Stable map: message-type → set of handlers. Never replaced, only mutated.
const subs = useRef<Map<string, Set<Handler>>>(new Map())
useEffect(() => {
let dead = false
let retryTimer: ReturnType<typeof setTimeout> | 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 socket: WebSocket | null = null
function connect() {
if (dead) return
socket = new WebSocket(`${WS_URL}/ws/prices`)
const ws = socket // local alias for handler closures
ws.onmessage = (e) => {
try {
const msg = JSON.parse(e.data) as { type?: string }
const t = msg.type ?? '__unknown__'
subs.current.get(t)?.forEach((fn) => fn(msg))
} catch {
// ignore malformed frames
}
}
ws.onclose = () => {
if (!dead) retryTimer = setTimeout(connect, 3000)
}
ws.onerror = () => ws.close()
}
connect()
return () => {
dead = true
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.
if (socket && socket.readyState <= WebSocket.OPEN) {
socket.onclose = null // suppress the auto-reconnect we'd otherwise queue
socket.close()
}
socket = null
}
}, [])
function subscribe(type: string, fn: Handler): () => void {
if (!subs.current.has(type)) subs.current.set(type, new Set())
subs.current.get(type)!.add(fn)
return () => subs.current.get(type)?.delete(fn)
}
return <WsContext.Provider value={{ subscribe }}>{children}</WsContext.Provider>
}
/**
* Subscribe to a specific WebSocket message type from the shared connection.
*
* @param type The `msg.type` string to listen for (e.g. 'price', 'new_post', 'funding_signal')
* @param handler Called with the full parsed message object on every matching frame.
* Always receives the latest handler reference — no stale-closure issues.
*
* Usage:
* useWsSubscribe('price', (msg) => { ... })
*/
export function useWsSubscribe(type: string, handler: Handler): void {
const ctx = useContext(WsContext)
// Keep a ref so the subscription closure never goes stale even if handler
// is an inline function that changes every render.
const handlerRef = useRef<Handler>(handler)
handlerRef.current = handler
useEffect(() => {
if (!ctx) return
return ctx.subscribe(type, (msg) => handlerRef.current(msg))
}, [ctx, type]) // type is stable in practice; ctx never changes
}