This commit is contained in:
k
2026-04-21 19:32:53 +08:00
parent 1747fc489f
commit 83e5892ddf
25 changed files with 2582 additions and 916 deletions
+68 -10
View File
@@ -1,4 +1,5 @@
import type { TrumpPost, Candle, BotTrade, BotPerformance } from '@/types'
import type { SignedEnvelope } from './signedRequest'
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
@@ -7,7 +8,14 @@ async function fetchJson<T>(path: string, init?: RequestInit): Promise<T> {
headers: { 'Content-Type': 'application/json' },
...init,
})
if (!res.ok) throw new Error(`API error ${res.status}: ${path}`)
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>
}
@@ -31,20 +39,70 @@ export async function getPerformance(): Promise<BotPerformance> {
return fetchJson<BotPerformance>(`/performance`)
}
export async function subscribe(
wallet: string,
signature: string,
): Promise<{ success: boolean; message: string }> {
return fetchJson<{ success: boolean; message: string }>(`/subscribe`, {
export async function subscribe(env: SignedEnvelope): Promise<{ status: string; wallet: string }> {
return fetchJson<{ status: string; wallet: string }>(`/subscribe`, {
method: 'POST',
body: JSON.stringify({ wallet, signature }),
body: JSON.stringify(env),
})
}
export interface UserSettings {
leverage: number
position_size_usd: number
take_profit_pct: number | null
stop_loss_pct: number | null
min_confidence: number
}
export interface UserData {
wallet_address: string
active: boolean
subscribed_at: string | null
hl_api_key_set: boolean
hl_api_key_masked: string | null
trades: BotTrade[]
settings: UserSettings
}
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
}
/** 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,
): Promise<{ wallet_address: string; active: boolean; subscribed_at: string | null; hl_api_key_set: boolean; trades: BotTrade[] }> {
return fetchJson<{ wallet_address: string; active: boolean; subscribed_at: string | null; hl_api_key_set: boolean; trades: BotTrade[] }>(
`/user/${wallet}`,
env: SignedEnvelope,
): Promise<UserData> {
const qs = `ts=${env.timestamp}&sig=${encodeURIComponent(env.signature)}`
return fetchJson<UserData>(`/user/${wallet.toLowerCase()}?${qs}`)
}
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 }),
},
)
}
+93
View File
@@ -0,0 +1,93 @@
/**
* Signed-request helper. Must match backend/app/services/signed_request.py exactly.
*
* Message format:
* TrumpSignal · {ACTION}
* wallet: {wallet_lowercase}
* timestamp: {ms}
* body: {sha256_hex or "-"}
*/
async function sha256Hex(text: string): Promise<string> {
const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
return Array.from(new Uint8Array(buf))
.map((b) => b.toString(16).padStart(2, '0'))
.join('')
}
/** Canonical JSON: sorted keys, no whitespace. Must match Python's json.dumps(..., sort_keys, separators). */
function canonicalJson(v: unknown): string {
if (v === null || typeof v !== 'object') return JSON.stringify(v)
if (Array.isArray(v)) return '[' + v.map(canonicalJson).join(',') + ']'
const keys = Object.keys(v as object).sort()
return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonicalJson((v as Record<string, unknown>)[k])).join(',') + '}'
}
export async function bodyHash(body: unknown | null): Promise<string> {
if (body === null || body === undefined) return '-'
return sha256Hex(canonicalJson(body))
}
export async function buildSignMessage(
action: string,
wallet: string,
timestampMs: number,
body: unknown | null,
): Promise<string> {
const h = await bodyHash(body)
return `TrumpSignal · ${action}\nwallet: ${wallet.toLowerCase()}\ntimestamp: ${timestampMs}\nbody: ${h}`
}
export interface SignedEnvelope {
wallet: string
timestamp: number
signature: string
}
/**
* 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 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
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 {}
}
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 }
}
+2 -2
View File
@@ -30,8 +30,8 @@ export function usePriceSocket(handlers: Handlers) {
} else if (msg.type === 'new_post' && handlersRef.current.onNewPost) {
handlersRef.current.onNewPost(msg.post)
}
} catch {
// ignore malformed messages
} catch (err) {
console.warn('[WS] malformed message:', e.data, err)
}
}