Files
trumpsignal-monorepo/apps/api/src/routes/kol.ts
T

183 lines
6.4 KiB
TypeScript

import type { FastifyInstance } from 'fastify'
import { z } from 'zod'
import { and, eq, gte, desc, asc, count, sql, or, ne, isNull } from 'drizzle-orm'
import {
kol_posts as posts,
kol_wallets as wallets,
kol_holdings_snapshots as snapshots,
kol_holding_changes as changes,
kol_divergence as divergence,
} from '@trumpsignal/database'
import type { Context } from '@trumpsignal/backend/context'
import { Kol, kolDto, parseArray } from '@trumpsignal/backend/kol'
import { requireThat, iso } from '@trumpsignal/backend/http'
import { requireIngestKey } from './signals'
const query = z.object({
handle: z.string().optional(),
source: z.string().optional(),
ticker: z
.string()
.regex(/^[A-Za-z0-9]{1,12}$/)
.optional(),
signal_type: z.string().optional(),
signals_only: z.enum(['true', 'false']).optional(),
days: z.coerce.number().int().min(1).max(365).optional(),
limit: z.coerce.number().int().min(1).max(200).default(50),
page: z.coerce.number().int().min(1).default(1),
lookback_days: z.coerce.number().int().min(1).max(90).default(30),
})
const since = (days: number) => new Date(Date.now() - days * 86400000).toISOString().slice(0, -1)
const walletDto = (w: typeof wallets.$inferSelect) => ({ ...w, added_at: iso(w.added_at) })
export async function registerKol(app: FastifyInstance, c: Context, kol: Kol) {
app.get('/api/kol/posts', async (req) => {
const q = query.parse(req.query),
scope = and(
q.handle ? eq(posts.kol_handle, q.handle) : undefined,
q.source ? eq(posts.source, q.source) : undefined,
q.signals_only === 'true' ? or(isNull(posts.tier), ne(posts.tier, 'noise')) : undefined,
q.ticker
? sql`${posts.tickers_json}::jsonb @> ${JSON.stringify([{ ticker: q.ticker.toUpperCase() }])}::jsonb`
: undefined,
q.days ? gte(posts.published_at, since(q.days)) : undefined,
)
const [rows, totals] = await Promise.all([
c.db
.select()
.from(posts)
.where(scope)
.orderBy(desc(posts.published_at))
.limit(q.limit)
.offset((q.page - 1) * q.limit),
c.db.select({ n: count() }).from(posts).where(scope),
])
return { items: rows.map(kolDto), page: q.page, limit: q.limit, total: totals[0].n }
})
app.get<{ Params: { id: string } }>('/api/kol/posts/:id', async (req) => {
const [p] = await c.db
.select()
.from(posts)
.where(eq(posts.id, z.coerce.number().int().positive().parse(req.params.id)))
.limit(1)
requireThat(p, 404, 'KOL post not found')
return { ...kolDto(p), raw_text: p.raw_text }
})
app.get('/api/kol/digest', async (req) => {
const q = query.parse(req.query)
return kol.digest(Math.min(q.days ?? 7, 90))
})
app.get('/api/kol/wallets', async (req) => {
const q = query.parse(req.query),
rows = await c.db
.select()
.from(wallets)
.where(and(eq(wallets.active, true), q.handle ? eq(wallets.handle, q.handle) : undefined))
.orderBy(asc(wallets.handle))
return { wallets: rows.map(walletDto) }
})
app.post('/api/kol/wallets', async (req) => {
requireIngestKey(c, req.headers['x-ingest-key'])
const b = z
.object({
handle: z.string().min(1).max(64),
chain: z.string().min(1).max(16),
address: z.string().min(1).max(128),
label: z.string().max(128).nullable().optional(),
source_url: z.string().max(256).nullable().optional(),
})
.parse(req.body)
const [row] = await c.db
.insert(wallets)
.values({ ...b, address: b.address.toLowerCase() })
.onConflictDoNothing()
.returning()
requireThat(row, 409, 'Wallet already tracked')
return walletDto(row)
})
app.get<{ Params: { id: string } }>('/api/kol/wallets/:id/snapshots', async (req) => {
const id = z.coerce.number().int().positive().parse(req.params.id),
q = query.parse(req.query),
[w] = await c.db.select().from(wallets).where(eq(wallets.id, id))
requireThat(w, 404, 'Wallet not found')
const rows = await c.db
.select()
.from(snapshots)
.where(eq(snapshots.wallet_id, id))
.orderBy(desc(snapshots.snapshot_date))
.limit(Math.min(q.limit, 90))
return {
wallet: walletDto(w),
snapshots: rows.map((s) => ({
id: s.id,
wallet_id: s.wallet_id,
snapshot_date: s.snapshot_date,
holdings: parseArray(s.holdings_json),
total_usd: s.total_usd,
source: s.source,
created_at: iso(s.created_at),
})),
}
})
app.get('/api/kol/changes', async (req) => {
const q = query.parse(req.query),
days = Math.min(q.days ?? 7, 90),
cutoff = since(days),
rows = await c.db
.select({ change: changes, handle: wallets.handle })
.from(changes)
.innerJoin(wallets, eq(changes.wallet_id, wallets.id))
.where(
and(
gte(changes.detected_at, cutoff),
q.handle ? eq(wallets.handle, q.handle) : undefined,
),
)
.orderBy(desc(changes.detected_at))
.limit(200)
return {
window_days: days,
since: iso(cutoff),
count: rows.length,
changes: rows.map(({ change, handle }) => ({
...change,
handle,
detected_at: iso(change.detected_at),
})),
}
})
app.get('/api/kol/divergence', async (req) => {
const q = query.parse(req.query),
days = Math.min(q.days ?? 30, 180),
cutoff = since(days),
rows = await c.db
.select()
.from(divergence)
.where(
and(
gte(divergence.post_at, cutoff),
q.handle ? eq(divergence.handle, q.handle) : undefined,
q.ticker ? eq(divergence.ticker, q.ticker.toUpperCase()) : undefined,
q.signal_type ? eq(divergence.signal_type, q.signal_type) : undefined,
),
)
.orderBy(desc(divergence.post_at), desc(divergence.created_at))
.limit(200)
return {
window_days: days,
since: iso(cutoff),
count: rows.length,
items: rows.map((d) => ({
...d,
post_at: iso(d.post_at),
onchain_at: iso(d.onchain_at),
created_at: iso(d.created_at),
})),
}
})
app.post('/api/kol/divergence/scan', async (req) => {
requireIngestKey(c, req.headers['x-ingest-key'])
const q = query.parse(req.query),
items = await kol.divergence(q.lookback_days)
return { new_pairs: items.length, items }
})
}