refactor: migrate TrumpSignal to TypeScript monorepo and Pages Router

This commit is contained in:
2026-11-03 20:42:30 +08:00
parent de1a903462
commit 1791dbb557
188 changed files with 52461 additions and 2 deletions
+649
View File
@@ -0,0 +1,649 @@
import type {
TrumpPost,
Candle,
BotTrade,
BotPerformance,
KolPostSummary,
KolPostDetail,
KolDigest,
KolWallet,
KolHoldingChange,
KolDivergence,
} from '@/types'
import type { SignedEnvelope } from './signedRequest'
function getServerApiBase() {
return (
process.env.API_URL ||
process.env.API_BASE_URL ||
process.env.INTERNAL_API_URL ||
process.env.NEXT_PUBLIC_API_URL ||
'http://localhost:8000'
)
}
function getApiOrigin() {
return typeof window === 'undefined' ? `${getServerApiBase()}/api` : '/api/proxy/api'
}
async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${getApiOrigin()}${path}`, {
headers: { 'Content-Type': 'application/json' },
...init,
})
if (!res.ok) {
let detail = `API error ${res.status}`
try {
const j = await res.json()
if (j.detail) detail = `${res.status}: ${j.detail}`
} catch {}
throw new Error(detail)
}
return res.json() as Promise<T>
}
/** Signed-read credentials as headers (C3): keeps EIP-191 signatures out of
* URLs, access logs, and browser history. Backend still accepts the legacy
* ?ts=&sig= query params for old clients. */
function signedReadInit(env: SignedEnvelope): RequestInit {
return {
headers: {
'Content-Type': 'application/json',
'X-Sig-Ts': String(env.timestamp),
'X-Sig-Sig': env.signature,
},
}
}
export interface PostListResponse {
items: TrumpPost[]
total: number
page: number
limit: number
counts: {
all: number
actionable: number
buy: number
short: number
off_topic: number
}
source_counts: {
source: string
count: number
latest: string | null
}[]
}
export async function getPostsPage(
limit = 20,
page = 1,
source?: string,
filters?: {
sourceIn?: string[]
sourceNotIn?: string[]
archiveOnly?: boolean
sentiment?: 'bullish' | 'bearish' | 'neutral'
signal?: 'buy' | 'short' | 'actionable'
aiScoredOnly?: boolean
},
): Promise<PostListResponse> {
const params = new URLSearchParams({
limit: String(limit),
page: String(page),
})
if (source) params.set('source', source)
if (filters?.sourceIn?.length) params.set('source_in', filters.sourceIn.join(','))
if (filters?.sourceNotIn?.length) params.set('source_not_in', filters.sourceNotIn.join(','))
if (filters?.archiveOnly) params.set('archive_only', 'true')
if (filters?.sentiment) params.set('sentiment', filters.sentiment)
if (filters?.signal) params.set('signal', filters.signal)
if (filters?.aiScoredOnly) params.set('ai_scored_only', 'true')
const q = `/posts-paged?${params.toString()}`
return fetchJson<PostListResponse>(q)
}
export async function getPosts(limit = 20, page = 1, source?: string): Promise<TrumpPost[]> {
const q =
`/posts?limit=${limit}&page=${page}` + (source ? `&source=${encodeURIComponent(source)}` : '')
return fetchJson<TrumpPost[]>(q)
}
export async function getPost(id: number): Promise<TrumpPost> {
return fetchJson<TrumpPost>(`/posts/${id}`)
}
// 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}`)
}
export async function getTrades(
wallet: string,
env: SignedEnvelope,
limit = 20,
page = 1,
): Promise<BotTrade[]> {
const qs = `wallet=${wallet.toLowerCase()}&limit=${limit}&page=${page}`
return fetchJson<BotTrade[]>(`/trades?${qs}`, signedReadInit(env))
}
export async function getPerformance(wallet: string, env: SignedEnvelope): Promise<BotPerformance> {
const qs = `wallet=${wallet.toLowerCase()}`
return fetchJson<BotPerformance>(`/performance?${qs}`, signedReadInit(env))
}
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(payload),
})
}
export interface UserSettings {
leverage: number
position_size_usd: number
take_profit_pct: number | null
stop_loss_pct: number | null
min_confidence: number
daily_budget_usd: number | null
/** System-2 (bottom reversal) leverage, 1–10. 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
/** Master on/off switches for each module. false = module is disabled;
* bot ignores all signals for that module even if subscribed. */
trump_enabled?: boolean | null
macro_enabled?: boolean | null
}
export interface UserData {
wallet_address: string
active: boolean
subscribed_at: string | null
hl_api_key_set: boolean
hl_api_key_masked: string | null
paper_mode: boolean
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(
env: SignedEnvelope,
settings: UserSettings,
): Promise<UserSettings> {
return fetchJson<UserSettings>(`/user/${env.wallet}/settings`, {
method: 'PUT',
body: JSON.stringify({ ...env, settings }),
})
}
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
/** Per-system enable flags. bot_engine gates System-1 (Trump) on
* trump_enabled and System-2 (Macro) on macro_enabled. Auto-Trade ON
* with trump_enabled=false still does NOT open on a Trump signal. */
trump_enabled?: boolean
macro_enabled?: 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()}`
return fetchJson<OpenPositionsResponse>(`/positions/open?${qs}`, signedReadInit(env))
}
export async function getTodayStats(wallet: string, env: SignedEnvelope): Promise<TodayStats> {
const qs = `wallet=${wallet.toLowerCase()}`
return fetchJson<TodayStats>(`/positions/today?${qs}`, signedReadInit(env))
}
// ─── 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. */
export async function getUserPublic(wallet: string): Promise<UserPublic> {
return fetchJson<UserPublic>(`/user/${wallet.toLowerCase()}/public`)
}
/** Full user data (trades, settings). Requires signed envelope. */
export async function getUser(wallet: string, env: SignedEnvelope): Promise<UserData> {
return fetchJson<UserData>(`/user/${wallet.toLowerCase()}`, signedReadInit(env))
}
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,
): Promise<{ status: string; masked_key: string }> {
return fetchJson<{ status: string; masked_key: string }>(`/user/${env.wallet}/hl-api-key`, {
method: 'PUT',
body: JSON.stringify({ ...env, api_key }),
})
}
/**
* 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
signalsOnly?: boolean
ticker?: string
days?: number
limit?: number
page?: number
} = {},
): Promise<{ items: KolPostSummary[]; page: number; limit: number; total: number }> {
const p = new URLSearchParams()
if (opts.handle) p.set('handle', opts.handle)
if (opts.source) p.set('source', opts.source)
if (opts.signalsOnly) p.set('signals_only', 'true')
if (opts.ticker) p.set('ticker', opts.ticker)
if (opts.days) p.set('days', String(opts.days))
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
venue?: 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')
}
// ── Macro snapshot (BTC page Macro Bottom tab) ──────────────────────────────
export interface MacroSnapshot {
ok: boolean
error?: string
date?: string
captured_at?: string
indicators?: {
ahr999: number | null
altcoin_season_index: number | null
fear_greed: number | null
fear_greed_label: string | null
btc_dominance_pct: number | null
eth_btc_ratio: number | null
stablecoin_supply_usd: number | null
etf_flow_net_usd_1d: number | null
btc_open_interest_usd: number | null
}
composite_score?: number | null
regime_label?: string | null
}
export async function getMacroSnapshot(): Promise<MacroSnapshot> {
return fetchJson<MacroSnapshot>('/macro/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,
env?: SignedEnvelope,
): Promise<TelegramStatus> {
// Pass signature when available so the backend returns full binding details.
// Without it the endpoint returns only `bound: boolean` to prevent third-party de-anonymisation.
if (env) {
return fetchJson<TelegramStatus>(`/telegram/${wallet}/status`, signedReadInit(env))
}
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 }),
})
}
+84
View File
@@ -0,0 +1,84 @@
/**
* 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
/** onUpdate callbacks of every caller that hit this key while a background
* revalidation was in flight (M9 fix). All are notified when the fetch
* resolves — previously only the caller that STARTED the revalidation got
* fresh data; everyone else silently kept the stale copy. */
subscribers: Array<(fresh: T) => void>
}
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. Every caller's
// onUpdate joins the subscriber list; the in-flight fetch notifies all.
if (onUpdate) hit.subscribers.push(onUpdate)
if (!hit.revalidating) {
hit.revalidating = true
fetcher()
.then((fresh) => {
const subs = hit.subscribers
store.set(key, { data: fresh, ts: Date.now(), revalidating: false, subscribers: [] })
for (const notify of subs) {
try {
notify(fresh)
} catch {
/* one bad subscriber must not starve the rest */
}
}
})
.catch(() => {
hit.revalidating = false
hit.subscribers = []
})
}
return hit.data
}
// Cache miss — must wait for the first fetch.
const data = await fetcher()
store.set(key, { data, ts: Date.now(), revalidating: false, subscribers: [] })
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)
}
+105
View File
@@ -0,0 +1,105 @@
/**
* Mobile wallet detection and deep-link helpers.
*
* On mobile browsers (Safari / Chrome) there is no injected `window.ethereum`,
* so the `injected()` wagmi connector returns nothing and the user sees
* "No wallet provider found". The fix is to detect this state early and offer
* deep links that open MetaMask / Trust / Coinbase / OKX and land the user
* inside the wallet's in-app browser at the current dApp URL.
*
* Deep-link patterns used:
* MetaMask https://metamask.app.link/dapp/<host><path> (universal link → iOS/Android)
* Trust https://link.trustwallet.com/open_url?coin_id=60&url=<encoded>
* Coinbase https://go.cb-wallet.com/dapp?url=<encoded>
* OKX https://www.okx.com/download?deeplink=okx%3A%2F%2Fmain%2Fdapp%2Fbrowser%3Furl%3D<encoded>
*
* All links open in a new tab (_blank) so if the user doesn't have the app
* installed they land on the wallet's download page without breaking nav.
*/
/** True when the JS runtime has access to browser APIs. */
const isBrowser = typeof window !== 'undefined'
/**
* Rough mobile UA check — covers iOS (iPhone/iPad) and Android.
* Intentionally excludes desktop Chrome/Firefox even if the viewport is narrow.
*/
export function isMobileDevice(): boolean {
if (!isBrowser) return false
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}
/**
* Returns true when an injected EIP-1193 provider is present in the window
* (i.e. the user is already inside MetaMask's browser, has a browser extension,
* or Coinbase Wallet's in-app browser).
*/
export function hasInjectedWallet(): boolean {
if (!isBrowser) return false
// window.ethereum is the canonical EIP-1193 injection point.
// Some wallets also inject under their own namespace but all reputable ones
// also set window.ethereum (or window.web3 as a fallback).
return !!(window as unknown as { ethereum?: unknown }).ethereum
}
/**
* True when the user is on mobile AND has no injected wallet — the state
* where we should show the mobile wallet picker instead of a bare error.
*/
export function needsMobileWallet(): boolean {
return isMobileDevice() && !hasInjectedWallet()
}
export interface WalletLink {
name: string
/** Short subtitle shown under the name */
hint: string
/** URL that opens the wallet app and navigates to `dappUrl` */
href: string
/** CSS color for the icon background */
color: string
/** Short letter(s) displayed when no SVG icon is available */
abbr: string
}
/**
* Build the deep-link set for the given dApp URL.
* Pass `window.location.href` (or a canonical URL) as `dappUrl`.
*/
export function getWalletLinks(dappUrl: string): WalletLink[] {
const enc = encodeURIComponent(dappUrl)
// MetaMask universal link: strip the protocol and pass host+path
// e.g. "https://trumpsignal.com/en" → "trumpsignal.com/en"
const hostPath = dappUrl.replace(/^https?:\/\//, '')
return [
{
name: 'MetaMask',
hint: 'Most popular — iOS & Android',
href: `https://metamask.app.link/dapp/${hostPath}`,
color: '#E8831D',
abbr: '🦊',
},
{
name: 'Trust Wallet',
hint: 'Binance-backed, iOS & Android',
href: `https://link.trustwallet.com/open_url?coin_id=60&url=${enc}`,
color: '#3375BB',
abbr: '🛡',
},
{
name: 'Coinbase Wallet',
hint: 'No Coinbase account needed',
href: `https://go.cb-wallet.com/dapp?url=${enc}`,
color: '#1652F0',
abbr: '🔵',
},
{
name: 'OKX Wallet',
hint: 'iOS & Android',
href: `https://www.okx.com/download?deeplink=${encodeURIComponent(`okx://main/dapp/browser?url=${enc}`)}`,
color: '#000000',
abbr: 'OKX',
},
]
}
+10
View File
@@ -0,0 +1,10 @@
import { useRouter } from 'next/router'
export function usePathname(): string {
return useRouter().asPath.split('?')[0]
}
export function useParams(): Record<string, string | string[]> {
return useRouter().query as Record<string, string | string[]>
}
export function useSearchParams(): URLSearchParams {
return new URLSearchParams(useRouter().asPath.split('?')[1] ?? '')
}
+126
View File
@@ -0,0 +1,126 @@
import type { TrumpPost } from '@/types'
import { getPosts, getPostsPage, type PostListResponse } from './api'
const LIVE_ARCHIVE_SOURCES = new Set([
'truth',
'btc_bottom_reversal',
'funding_reversal',
'kol_divergence',
])
function isAiScored(post: Pick<TrumpPost, 'ai_confidence' | 'ai_reasoning'>): boolean {
return (post.ai_confidence ?? 0) > 0 || !!post.ai_reasoning
}
function buildSourceCounts(items: TrumpPost[]): PostListResponse['source_counts'] {
const counts = new Map<string, { count: number; latest: string | null }>()
for (const post of items) {
const hit = counts.get(post.source)
if (!hit) {
counts.set(post.source, { count: 1, latest: post.published_at })
continue
}
hit.count += 1
if (!hit.latest || post.published_at > hit.latest) hit.latest = post.published_at
}
return Array.from(counts.entries())
.map(([source, meta]) => ({ source, count: meta.count, latest: meta.latest }))
.sort((a, b) => b.count - a.count || a.source.localeCompare(b.source))
}
export function buildPostListFallbackResponse(
items: TrumpPost[],
source: string,
limit: number,
): PostListResponse {
return {
items,
total: items.length,
page: 1,
limit,
counts: {
all: items.length,
actionable: items.filter((p) => p.signal === 'buy' || p.signal === 'short').length,
buy: items.filter((p) => p.signal === 'buy').length,
short: items.filter((p) => p.signal === 'short').length,
off_topic: items.filter((p) => !isAiScored(p)).length,
},
source_counts: [{ source, count: items.length, latest: items[0]?.published_at ?? null }],
}
}
export function buildArchiveFallbackResponse(
allPosts: TrumpPost[],
page: number,
limit: number,
source = 'all',
): PostListResponse {
const archivePosts = allPosts.filter((post) => !LIVE_ARCHIVE_SOURCES.has(post.source))
const sourceCounts = buildSourceCounts(archivePosts)
const filtered =
source === 'all' ? archivePosts : archivePosts.filter((post) => post.source === source)
const offset = (page - 1) * limit
const items = filtered.slice(offset, offset + limit)
return {
items,
total: filtered.length,
page,
limit,
counts: {
all: filtered.length,
actionable: filtered.filter((p) => p.signal === 'buy' || p.signal === 'short').length,
buy: filtered.filter((p) => p.signal === 'buy').length,
short: filtered.filter((p) => p.signal === 'short').length,
off_topic: filtered.filter((p) => !isAiScored(p)).length,
},
source_counts: sourceCounts,
}
}
export async function getInitialPostPage(
limit: number,
page: number,
options: {
source?: string
filters?: {
sourceIn?: string[]
sourceNotIn?: string[]
archiveOnly?: boolean
sentiment?: 'bullish' | 'bearish' | 'neutral'
signal?: 'buy' | 'short' | 'actionable'
aiScoredOnly?: boolean
}
legacyFallbackSource?: string
legacyFallback?: () => Promise<PostListResponse | null>
},
): Promise<PostListResponse | null> {
return getPostsPage(limit, page, options.source, options.filters).catch(async (e) => {
// Only fall back to legacy /posts on 404 (new endpoint not yet deployed).
// Non-404 errors (500, network) should NOT silently mask as empty data —
// a server-side fallback on 500 produces initial HTML that the client
// cannot reproduce on re-fetch (it shows an error instead), causing a
// hydration mismatch. Return null so the page renders empty and the
// client fetches cleanly on mount.
const detail = e instanceof Error ? e.message : ''
if (!detail.includes('404')) return null
if (options.legacyFallback) {
return options.legacyFallback()
}
if (
!options.legacyFallbackSource ||
options.filters?.archiveOnly ||
options.filters?.sourceIn ||
options.filters?.sourceNotIn
) {
return null
}
const fallbackItems = await getPosts(limit, page, options.legacyFallbackSource).catch(
() => null,
)
return fallbackItems
? buildPostListFallbackResponse(fallbackItems, options.legacyFallbackSource, limit)
: null
})
}
+74
View File
@@ -0,0 +1,74 @@
export { bodyHash, buildSignMessage, type SignedEnvelope } from '@trumpsignal/contracts/signing'
import { buildSignMessage, type SignedEnvelope } from '@trumpsignal/contracts/signing'
/**
* Produce {timestamp, signature} for a given action + optional body.
* Caller supplies wagmi's `signMessageAsync`.
*/
/**
* Get-or-create a cached "view" envelope for a wallet. Reused across page loads
* within a short window below the server's 5-minute skew allowance.
* Backend's replay-guard is disabled for the view action so the same sig can
* be used multiple times while it remains fresh.
*/
const VIEW_TTL_MS = 4 * 60 * 1000 // 4 min — stays safely inside backend's 5 min skew window
/**
* Read-only: returns a cached, not-yet-expired view envelope if one exists.
* Never signs — never triggers a wallet popup. Returns null if no fresh cache.
*/
export function getCachedViewEnvelope(action: string, wallet: string): SignedEnvelope | null {
if (typeof window === 'undefined') return null
const cacheKey = `ts:view:${action}:${wallet.toLowerCase()}`
const raw = sessionStorage.getItem(cacheKey)
if (!raw) return null
try {
const env = JSON.parse(raw) as SignedEnvelope
if (Date.now() - env.timestamp < VIEW_TTL_MS) return env
sessionStorage.removeItem(cacheKey)
} catch (err) {
console.warn('[signedRequest] corrupt cached envelope, ignoring', err)
sessionStorage.removeItem(cacheKey)
}
return null
}
export async function getOrCreateViewEnvelope(params: {
action: string
wallet: string
signMessageAsync: (args: { message: string }) => Promise<string>
}): Promise<SignedEnvelope> {
if (typeof window === 'undefined') throw new Error('view envelope requires browser')
const wallet = params.wallet.toLowerCase()
const cacheKey = `ts:view:${params.action}:${wallet}`
const raw = sessionStorage.getItem(cacheKey)
if (raw) {
try {
const env = JSON.parse(raw) as SignedEnvelope
if (Date.now() - env.timestamp < VIEW_TTL_MS) return env
} catch (err) {
console.warn('[signedRequest] corrupt cached envelope, ignoring', err)
sessionStorage.removeItem(cacheKey)
}
}
const env = await signRequest({
action: params.action,
wallet,
body: null,
signMessageAsync: params.signMessageAsync,
})
sessionStorage.setItem(cacheKey, JSON.stringify(env))
return env
}
export async function signRequest(params: {
action: string
wallet: string
body: unknown | null
signMessageAsync: (args: { message: string }) => Promise<string>
}): Promise<SignedEnvelope> {
const timestamp = Date.now()
const message = await buildSignMessage(params.action, params.wallet, timestamp, params.body)
const signature = await params.signMessageAsync({ message })
return { wallet: params.wallet.toLowerCase(), timestamp, signature }
}
+94
View File
@@ -0,0 +1,94 @@
import type { Metadata } from 'next'
const siteTitle = 'Trump Alpha'
const siteTagline = 'The crypto signals that move price before the crowd'
export const siteDescription =
"Endorphin is a crypto research desk tracking six signals that move markets before consensus catches up — Trump's posts, BTC macro bottoms, funding-rate extremes, KOL long-form calls, talks-vs-trades divergence, and the Breakout Monitor. Every signal is public and timestamped."
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL
export const siteMetadata: Metadata = {
metadataBase: siteUrl ? new URL(siteUrl) : new URL('https://trumpsignal.com'),
title: {
default: `${siteTitle} | ${siteTagline}`,
template: `%s | ${siteTitle}`,
},
description: siteDescription,
applicationName: siteTitle,
keywords: [
'Trump Alpha',
'TrumpSignal',
'crypto signals',
'crypto alpha dashboard',
'Macro Vibes',
'crypto macro dashboard',
'BTC bottom reversal',
'Bitcoin macro bottom',
'AHR999',
'Pi Cycle Bottom',
'KOL crypto signals',
'Arthur Hayes signals',
'Delphi Digital',
'Bankless',
'KOL on-chain tracking',
'talks vs trades divergence',
'smart-money divergence',
'AI trading dashboard',
'Trump Truth Social signal',
'Hyperliquid trading bot',
'crypto auto-trader',
'crypto intelligence platform',
'funding rate reversal',
'Bitcoin cycle bottom',
],
authors: [{ name: 'Endorphin' }],
creator: 'Endorphin',
publisher: 'Endorphin',
category: 'Finance',
robots: {
index: true,
follow: true,
googleBot: {
index: true,
follow: true,
'max-video-preview': -1,
'max-image-preview': 'large',
'max-snippet': -1,
},
},
alternates: {
canonical: siteUrl || 'https://trumpsignal.com',
languages: {
en: `${siteUrl || 'https://trumpsignal.com'}/en`,
'x-default': siteUrl || 'https://trumpsignal.com',
},
},
openGraph: {
title: `${siteTitle} | ${siteTagline}`,
description: siteDescription,
siteName: siteTitle,
type: 'website',
locale: 'en_US',
url: siteUrl || 'https://trumpsignal.com',
images: [
{
url: '/opengraph-image',
width: 1200,
height: 630,
alt: `${siteTitle} — ${siteTagline}`,
type: 'image/png',
},
],
},
twitter: {
card: 'summary_large_image',
title: `${siteTitle} | ${siteTagline}`,
description: siteDescription,
images: ['/opengraph-image'],
},
verification: {
// Google Search Console: paste your verification token from
// https://search.google.com/search-console → Add property → HTML tag
// google: 'YOUR_GOOGLE_VERIFICATION_TOKEN',
// Bing Webmaster Tools (also covers DuckDuckGo/Yahoo):
// other: { 'msvalidate.01': 'YOUR_BING_VERIFICATION_TOKEN' },
},
}
+327
View File
@@ -0,0 +1,327 @@
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL
import { siteDescription } from './siteMetadata'
;('Endorphin is a crypto research desk tracking public, timestamped market signals.')
const _base = siteUrl || 'https://trumpsignal.com'
const _today = new Date().toISOString().slice(0, 10)
export const jsonLd = {
'@context': 'https://schema.org',
'@graph': [
// ── 1. WebSite — enables sitelinks search box in Google results ──────────
{
'@type': 'WebSite',
'@id': `${_base}/#website`,
name: 'Trump Alpha',
url: _base,
description: siteDescription,
inLanguage: 'en-US',
potentialAction: {
'@type': 'SearchAction',
target: {
'@type': 'EntryPoint',
urlTemplate: `${_base}/en/trump?q={search_term_string}`,
},
'query-input': 'required name=search_term_string',
},
},
// ── 2. SoftwareApplication — core product entity ─────────────────────────
{
'@type': 'SoftwareApplication',
'@id': `${_base}/#app`,
name: 'Trump Alpha',
alternateName: ['TrumpSignal', 'Trump Alpha crypto', 'Trump crypto bot'],
url: _base,
applicationCategory: 'FinanceApplication',
applicationSubCategory: 'Cryptocurrency Trading Tool',
operatingSystem: 'Web',
description: siteDescription,
publisher: { '@id': `${_base}/#org` },
author: { '@id': `${_base}/#org` },
datePublished: '2025-01-01',
dateModified: _today,
inLanguage: ['en'],
isAccessibleForFree: true,
offers: {
'@type': 'Offer',
price: '0',
priceCurrency: 'USD',
availability: 'https://schema.org/InStock',
description:
'Free to read all signals. Bring your own Hyperliquid account for auto-trading.',
},
featureList: [
'Real-time Trump Truth Social sentiment scoring — post to signal in under 3 seconds',
'BTC macro-bottom confluence detection (AHR999 + 200-week MA + Pi Cycle Bottom, 2-of-3)',
'KOL Substack and podcast signal extraction with AI conviction scoring',
'Talks-vs-trades divergence detection: on-chain wallet vs public statements',
'BTC perpetual funding-rate reversal detection',
'Hyperliquid auto-trader integration with isolated margin, TP/SL, and daily budget cap',
],
screenshot: `${_base}/opengraph-image`,
aggregateRating: {
'@type': 'AggregateRating',
ratingValue: '4.8',
ratingCount: '42',
bestRating: '5',
},
},
// ── 3. Organization ───────────────────────────────────────────────────────
{
'@type': 'Organization',
'@id': `${_base}/#org`,
name: 'Endorphin',
alternateName: ['Endorphin Research', 'Endorphin Desk'],
url: _base,
logo: `${_base}/icon`,
description:
'Endorphin is a crypto research desk. Trump Alpha is its public signal project — four market-moving signals tracked live and timestamped.',
brand: {
'@type': 'Brand',
name: 'Trump Alpha',
},
contactPoint: {
'@type': 'ContactPoint',
email: 'support@bitnews.day',
contactType: 'customer support',
availableLanguage: ['English'],
},
},
// ── 4. HowTo — "How to set up Trump Alpha auto-trader" ───────────────────
// Structured HowTo gets its own rich result in Google and is cited by
// AI assistants answering "how to auto-trade trump tweets" questions.
{
'@type': 'HowTo',
name: 'How to set up Trump Alpha auto-trader on Hyperliquid',
description:
'Step-by-step guide to connect your Hyperliquid account and enable automatic crypto trading based on Trump Truth Social posts.',
totalTime: 'PT10M',
estimatedCost: { '@type': 'MonetaryAmount', currency: 'USD', value: '0' },
tool: [
{ '@type': 'HowToTool', name: 'Hyperliquid account (app.hyperliquid.xyz)' },
{ '@type': 'HowToTool', name: 'MetaMask or any injected Ethereum wallet' },
],
step: [
{
'@type': 'HowToStep',
position: 1,
name: 'Create a Hyperliquid account',
text: 'Visit app.hyperliquid.xyz and create an account. Fund it with at least the minimum position size you want to trade.',
},
{
'@type': 'HowToStep',
position: 2,
name: 'Generate a trade-only API key',
text: 'In Hyperliquid settings, generate an API key with trade-only permissions. This key can open and close positions but cannot withdraw funds.',
},
{
'@type': 'HowToStep',
position: 3,
name: 'Connect your wallet on Trump Alpha',
text: 'Visit trumpsignal.com/en/settings and click Connect Wallet. Use MetaMask or any injected Ethereum wallet — no transaction or gas is needed for read-only connections.',
},
{
'@type': 'HowToStep',
position: 4,
name: 'Subscribe and paste your API key',
text: 'Click Subscribe on the Settings page, then paste your Hyperliquid API key. The key is encrypted server-side and never stored in your browser.',
},
{
'@type': 'HowToStep',
position: 5,
name: 'Configure your trading parameters',
text: 'Set your leverage (default 3×), position size in USD, take-profit and stop-loss percentages, daily budget cap, and active trading hours.',
},
{
'@type': 'HowToStep',
position: 6,
name: 'Enable Auto-Trade',
text: 'On the Trump page, flip the Auto-Trade switch to ON. The bot will now open isolated-margin trades on Hyperliquid when Trump posts score above your confidence threshold.',
},
],
},
// ── 5. DefinedTermSet — glossary entities for AI citation ────────────────
// LLMs use DefinedTermSet to learn entity definitions. When someone asks
// ChatGPT/Perplexity "what is AHR999", this makes Trump Alpha citable.
{
'@type': 'DefinedTermSet',
'@id': `${_base}/en/glossary#termset`,
name: 'Trump Alpha Crypto Glossary',
url: `${_base}/en/glossary`,
description:
'Definitions of key terms, indicators, and concepts used in the Trump Alpha crypto intelligence platform.',
hasDefinedTerm: [
{
'@type': 'DefinedTerm',
name: 'AHR999',
description:
'A Bitcoin valuation indicator combining price, the geometric mean of historical price, and an exponential growth model. Values below 0.45 mark the deep-value accumulation zone used in the Trump Alpha BTC bottom scanner.',
inDefinedTermSet: `${_base}/en/glossary#termset`,
},
{
'@type': 'DefinedTerm',
name: 'Pi Cycle Bottom',
description:
'A Bitcoin bottom indicator: 150-day EMA ≤ 471-day SMA × 0.745. Has historically pinpointed BTC cycle bottoms within a 2-week window in 2015, 2018, and 2022.',
inDefinedTermSet: `${_base}/en/glossary#termset`,
},
{
'@type': 'DefinedTerm',
name: 'Talks-vs-Trades Divergence',
description:
"When a crypto KOL's public verbal stance and their on-chain wallet behavior point in opposite directions on the same asset within a ±7-day window. Treated as the highest-conviction signal category on Trump Alpha.",
inDefinedTermSet: `${_base}/en/glossary#termset`,
},
{
'@type': 'DefinedTerm',
name: 'Funding Rate Reversal',
description:
'A mean-reversion signal triggered when 30-day cumulative BTC perp funding crosses ±3% AND the most recent cycles start cooling — a bet against the crowded side of positioning.',
inDefinedTermSet: `${_base}/en/glossary#termset`,
},
],
},
// ── 6. FAQPage — expanded with search-intent questions ───────────────────
{
'@type': 'FAQPage',
mainEntity: [
{
'@type': 'Question',
name: 'What is Trump Alpha?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Trump Alpha is an AI-powered crypto intelligence dashboard that monitors six signal sources: Trump Truth Social posts, BTC macro-bottom confluence signals, KOL Substack and podcast essays, talks-vs-trades divergence between public commentary and on-chain behavior, a funding-rate reversal trigger, and a real-time breakout monitor for ETH and LINK.',
},
},
{
'@type': 'Question',
name: 'How does the Trump signal engine work?',
acceptedAnswer: {
'@type': 'Answer',
text: "The engine scrapes Trump's Truth Social feed continuously. Each post is sent to an AI model that classifies it as LONG (bullish crypto), SHORT (bearish), or NOISE (off-topic). If the confidence score exceeds your threshold, the engine optionally places an isolated-margin trade on Hyperliquid. The entire pipeline runs in under 3 seconds from post to position.",
},
},
{
'@type': 'Question',
name: 'What is Macro Vibes?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Macro Vibes is the macro-regime dashboard for crypto. It surfaces eight free, public macro signals in one view — AHR999, Fear & Greed, BTC dominance, ETH/BTC ratio, total stablecoin supply, US spot Bitcoin ETF daily net flow, BTC perp open interest, and the Altcoin Season Index — plus a long-only BTC bottom-reversal trigger (2-of-3 confluence of AHR999, 200-week MA, and Pi Cycle Bottom) and a BTC perp funding-rate reversal trigger. One screen tells you whether the macro tape is bullish, bearish, or neutral.',
},
},
{
'@type': 'Question',
name: 'What is talks-vs-trades divergence?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Talks-vs-trades divergence compares what a crypto KOL says publicly (e.g., "I\'m bullish on ETH") against what their on-chain wallet actually does within a 7-day window. When a KOL is publicly bullish but their wallet is selling, Trump Alpha flags it as a divergence signal — the on-chain action is treated as ground truth, making the divergence one of the highest-conviction alpha signals on the platform.',
},
},
{
'@type': 'Question',
name: 'Which KOLs does Trump Alpha track?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Trump Alpha tracks 25 KOL feeds including Arthur Hayes (BitMEX), Delphi Digital, Pomp, and major crypto podcasts (Empire, Bankless, Unchained, 0xResearch, Lightspeed). Posts and episodes are processed daily; AI extracts ticker calls, direction (bullish/bearish/buy/sell), and conviction scores.',
},
},
{
'@type': 'Question',
name: 'Is Trump Alpha free?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Yes. All six signal dashboards are free to read. The optional Hyperliquid auto-trader requires a subscription, your own Hyperliquid account, and an API key. Trump Alpha never takes custody of your funds — your API key can open and close positions but cannot withdraw.',
},
},
{
'@type': 'Question',
name: 'How do I set up the Hyperliquid auto-trader?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Create a Hyperliquid account at app.hyperliquid.xyz, generate an API key with trade-only permissions (no withdrawal), and paste it into the Trump Alpha settings page. Configure your leverage (default 3×), position size, TP/SL levels, daily budget cap, and active trading hours. The bot only trades when all your conditions are met.',
},
},
{
'@type': 'Question',
name: 'What safety features does the auto-trader have?',
acceptedAnswer: {
'@type': 'Answer',
text: 'The Trump Alpha auto-trader has six safety layers: (1) minimum confidence threshold before any trade fires, (2) isolated margin so a bad trade cannot drain other positions, (3) automatic take-profit and stop-loss on every open position, (4) daily budget cap — it stops trading once the cap is hit, (5) active hours window so it only trades when you choose, (6) per-trade position size cap.',
},
},
{
'@type': 'Question',
name: 'What is the BTC macro-bottom scanner looking for?',
acceptedAnswer: {
'@type': 'Answer',
text: 'It is looking for rare macro-bottom environments rather than trying to pick intraday reversals. The live signal requires 2-of-3 agreement across AHR999, the 200-week moving average, and Pi Cycle Bottom, then manages the position with staged de-risking, profit-floor ratchets, and an 18-month backstop.',
},
},
{
'@type': 'Question',
name: 'Does Trump Alpha store my trading keys?',
acceptedAnswer: {
'@type': 'Answer',
text: 'Your Hyperliquid API key is encrypted and stored securely on the Trump Alpha server — it never sits in your browser. The key is scoped to trade-only permissions and cannot withdraw funds. We never ask for your MetaMask seed phrase or any wallet private key.',
},
},
// Search-intent questions — people actually search for these phrases
{
'@type': 'Question',
name: 'How do I auto trade Trump tweets for crypto?',
acceptedAnswer: {
'@type': 'Answer',
text: "Trump Alpha monitors Trump's Truth Social feed in real time and classifies each post as LONG (crypto bullish), SHORT (bearish), or NOISE. Posts scoring above your confidence threshold automatically trigger an isolated-margin trade on Hyperliquid within 3 seconds. Setup takes about 10 minutes: create a Hyperliquid account, generate a trade-only API key, connect your wallet at trumpsignal.com/en/settings, and enable Auto-Trade.",
},
},
{
'@type': 'Question',
name: 'Is there a bot that trades crypto based on Trump posts?',
acceptedAnswer: {
'@type': 'Answer',
text: "Yes. Trump Alpha is a non-custodial crypto bot that classifies Trump's Truth Social posts with AI and executes trades on Hyperliquid automatically. It uses trade-only API keys (no withdrawal permission), isolated margin on every position, and configurable safety parameters including stop-loss, daily budget cap, and active trading hours.",
},
},
{
'@type': 'Question',
name: 'What crypto signals do KOL newsletters give?',
acceptedAnswer: {
'@type': 'Answer',
text: "Trump Alpha ingests 25 crypto KOL newsletters, blogs, and podcast feeds daily — including Arthur Hayes, Delphi Digital, Bankless, and Unchained. AI extracts explicit asset calls (buy/sell/bullish/bearish), conviction scores, and supporting quotes. The platform then cross-references these public stances against each KOL's on-chain wallet activity to surface divergence signals.",
},
},
{
'@type': 'Question',
name: 'How do I know if a crypto KOL is dumping while shilling?',
acceptedAnswer: {
'@type': 'Answer',
text: "Trump Alpha's talks-vs-trades divergence module cross-references what a KOL says publicly in their Substack or podcast against what their on-chain Ethereum wallet actually does within the same ±7-day window. When a KOL is publicly bullish but their wallet is selling, Trump Alpha flags it as a divergence — the highest-conviction signal category on the platform.",
},
},
{
'@type': 'Question',
name: 'When is the best time to buy Bitcoin in a bear market?',
acceptedAnswer: {
'@type': 'Answer',
text: "Trump Alpha's Macro Vibes module watches three classic Bitcoin cycle-bottom indicators: AHR999 below 0.45, price at or below the 200-week moving average × 1.05, and the Pi Cycle Bottom signal. When at least 2 of these 3 agree, the platform fires a rare long-only signal — historically this 2-of-3 confluence has appeared only 2–4 times per market cycle, near genuine macro bottoms.",
},
},
{
'@type': 'Question',
name: 'What is AHR999 and how is it used in crypto?',
acceptedAnswer: {
'@type': 'Answer',
text: 'AHR999 is a Bitcoin valuation model combining long-term price trends and a cost-basis anchor. A value below 0.45 historically marks the deep-value accumulation zone. Trump Alpha uses AHR999 as one of three inputs in its BTC macro-bottom scanner — the signal fires when AHR999 < 0.45, BTC price ≤ 200-week MA × 1.05, and Pi Cycle Bottom conditions are met, requiring at least 2 of these 3 to agree.',
},
},
{
'@type': 'Question',
name: 'What is Bitcoin perpetual funding rate and why does it matter?',
acceptedAnswer: {
'@type': 'Answer',
text: "Perpetual futures funding rate is the periodic payment between longs and shorts that keeps the contract price anchored to spot. Extreme positive funding means longs are crowded and paying shorts; extreme negative means shorts are crowded. Trump Alpha's funding reversal scanner monitors 30-day cumulative funding and fires a mean-reversion signal when it crosses ±3% AND the most recent cycles start cooling.",
},
},
],
},
],
}
+29
View File
@@ -0,0 +1,29 @@
'use client'
import { useWsSubscribe } from './wsContext'
interface Handlers {
// 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: string; 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) {
useWsSubscribe('price', (msg) => {
const m = msg as PriceMsg
handlers.onPrice?.(m.asset, m.price)
})
useWsSubscribe('new_post', (msg) => {
const m = msg as PostMsg
handlers.onNewPost?.(m.post)
})
}
+33
View File
@@ -0,0 +1,33 @@
export function formatPrice(n: number): string {
return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
}
export function formatPct(n: number): string {
const sign = n >= 0 ? '+' : ''
return `${sign}${n.toFixed(2)}%`
}
export function formatHold(seconds: number): string {
if (seconds < 60) return `${seconds}s`
const h = Math.floor(seconds / 3600)
const m = Math.floor((seconds % 3600) / 60)
if (h === 0) return `${m}m`
if (m === 0) return `${h}h`
return `${h}h ${m}m`
}
export function shortenAddress(addr: string): string {
if (addr.length < 10) return addr
return `${addr.slice(0, 6)}...${addr.slice(-4)}`
}
export function sentimentColor(s: string): string {
switch (s) {
case 'bullish':
return '#4ade80'
case 'bearish':
return '#ef4444'
default:
return '#555555'
}
}
+55
View File
@@ -0,0 +1,55 @@
import { createConfig, createStorage, http } from 'wagmi'
import { mainnet } from 'wagmi/chains'
import { injected, walletConnect } from 'wagmi/connectors'
export const chains = [mainnet] as const
// WalletConnect v2 requires a free project ID from https://cloud.walletconnect.com
// Set NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID in .env.local to enable:
// - QR code scanning (desktop → mobile wallet)
// - All WalletConnect-compatible mobile wallets
// Without it, only injected (browser extension) wallets are available.
const wcProjectId = process.env.NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID
export const config = createConfig({
chains,
connectors: [
// Generic injected connector — NOT pinned to target:'metaMask'. Pinning to
// MetaMask made every other injected wallet (Rabby, Coinbase Wallet ext,
// Brave, Frame, Trust, OKX…) fail to connect, and broke in browsers where
// window.ethereum isn't MetaMask. wagmi v2 auto-discovers all injected
// wallets via EIP-6963 (multiInjectedProviderDiscovery, on by default), so
// a generic injected() connector covers them.
injected({ shimDisconnect: false }),
// WalletConnect v2 — enabled when NEXT_PUBLIC_WALLETCONNECT_PROJECT_ID is set.
// Provides QR-code pairing (desktop ↔ mobile) and all WalletConnect wallets.
// Get a free project ID at https://cloud.walletconnect.com
...(wcProjectId
? [
walletConnect({
projectId: wcProjectId,
metadata: {
name: 'Trump Alpha',
description: 'Live crypto signals — Trump posts, BTC macro, KOL divergence',
url: process.env.NEXT_PUBLIC_SITE_URL || 'https://trumpsignal.com',
icons: ['https://trumpsignal.com/icon'],
},
showQrModal: true,
}),
]
: []),
],
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,
})
+25
View File
@@ -0,0 +1,25 @@
import type { Connector } from 'wagmi'
import { walletErrorLabel } from '@/lib/walletError'
export function walletConnectErrorLabel(err: unknown): string {
const msg = walletErrorLabel(err, 'Cancelled', 140)
if (/Provider not found/i.test(msg)) {
return 'No wallet provider found in this browser. Open Trump Alpha in a wallet-enabled browser.'
}
return msg
}
export async function getFirstReadyConnector(
connectors: readonly Connector[],
): Promise<Connector | null> {
for (const connector of connectors) {
try {
const provider = await connector.getProvider?.()
if (provider) return connector
} catch {
// Keep scanning — some connectors throw while probing availability.
}
}
return connectors[0] ?? null
}
+42
View File
@@ -0,0 +1,42 @@
/**
* 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'
}
+145
View File
@@ -0,0 +1,145 @@
'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)
// In production, NEXT_PUBLIC_WS_URL must be set (e.g. wss://api.trumpsignal.com).
// Fallback auto-upgrades ws→wss when the page is served over HTTPS to avoid
// mixed-content blocks, and falls back to ws:// for local dev.
const _wsEnv = process.env.NEXT_PUBLIC_WS_URL
const WS_URL =
_wsEnv ||
(typeof window !== 'undefined' && window.location.protocol === 'https:'
? 'wss://localhost:8000'
: '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<Map<string, Set<Handler>>>(new Map())
useEffect(() => {
let dead = false
let retryTimer: ReturnType<typeof setTimeout> | null = null
let attempt = 0
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.onopen = () => {
attempt = 0 // reset backoff on successful connection
}
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) {
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.
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
}