muthuk1 commited on
Commit
9e22644
·
1 Parent(s): f667d47

feat: Helius real on-chain wallet analysis

Browse files

- Add helius.ts client: fetches 50 txs, computes daysInactive/protocols/streak/volumeDropPct/hasLiquidation
- Add /api/helius/analyze POST endpoint with optional autoFire Torque event integration
- Wire LiveAnalyzer component into WalletsPage JSX

src/app/(dashboard)/wallets/page.tsx CHANGED
@@ -4,11 +4,138 @@ import { wallets } from '@/lib/mock-data'
4
  import { RiskBadge } from '@/components/ui/RiskBadge'
5
  import { RecoveryCard } from '@/components/ui/RecoveryCard'
6
  import { useToast } from '@/components/ui/Toast'
7
- import { Search, Flame, ExternalLink, ChevronRight, Zap, CheckCircle2, Loader2, Siren, Share2, AlertTriangle } from 'lucide-react'
8
  import { useState, useCallback, useMemo } from 'react'
9
  import type { ChurnRisk, Wallet } from '@/lib/types'
10
  import { classifyWalletType } from '@/lib/agent-engine'
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  type Filter = ChurnRisk | 'all'
13
  const filters: Filter[] = ['all', 'critical', 'high', 'medium', 'low', 'safe']
14
 
@@ -174,6 +301,8 @@ export default function WalletsPage() {
174
  </div>
175
  </div>
176
 
 
 
177
  <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
178
  {filters.map(r => (
179
  <button key={r} onClick={() => setF(r)} className={cn('rounded-xl border p-3 text-center transition-all', f === r ? 'border-brand-yellow/40 bg-brand-yellow/5' : 'border-hairline-dark bg-surface-card hover:border-brand-yellow/20')}>
 
4
  import { RiskBadge } from '@/components/ui/RiskBadge'
5
  import { RecoveryCard } from '@/components/ui/RecoveryCard'
6
  import { useToast } from '@/components/ui/Toast'
7
+ import { Search, Flame, ExternalLink, ChevronRight, Zap, CheckCircle2, Loader2, Siren, Share2, AlertTriangle, Radio } from 'lucide-react'
8
  import { useState, useCallback, useMemo } from 'react'
9
  import type { ChurnRisk, Wallet } from '@/lib/types'
10
  import { classifyWalletType } from '@/lib/agent-engine'
11
 
12
+ // --- Live Wallet Analyzer (Helius) ---
13
+ interface LiveResult {
14
+ address: string; score: number; risk: string; detectedSignals: string[]
15
+ signals: { daysInactive: number; protocols: string[]; currentStreak: number; volumeDropPct: number; totalTxLast30d: number; lastActiveDaysAgo: string }
16
+ torque: { fired: boolean; eventId?: string; eventName?: string }
17
+ }
18
+
19
+ function LiveAnalyzer() {
20
+ const [addr, setAddr] = useState('')
21
+ const [loading, setLoading] = useState(false)
22
+ const [result, setResult] = useState<LiveResult | null>(null)
23
+ const [err, setErr] = useState<string | null>(null)
24
+ const [autoFire, setAutoFire] = useState(false)
25
+ const { fire: toast } = useToast()
26
+
27
+ const analyze = useCallback(async () => {
28
+ if (!addr.trim() || loading) return
29
+ setLoading(true); setErr(null); setResult(null)
30
+ try {
31
+ const res = await fetch('/api/helius/analyze', {
32
+ method: 'POST',
33
+ headers: { 'Content-Type': 'application/json' },
34
+ body: JSON.stringify({ address: addr.trim(), autoFire }),
35
+ })
36
+ const data = await res.json()
37
+ if (!res.ok) { setErr(data.error); return }
38
+ setResult(data)
39
+ if (data.torque?.fired) {
40
+ toast({ type: 'event', title: `${data.torque.eventName} → ${addr.slice(0,8)}...`, body: data.torque.eventId?.slice(0,10) })
41
+ }
42
+ } catch (e: any) {
43
+ setErr(e.message)
44
+ } finally {
45
+ setLoading(false)
46
+ }
47
+ }, [addr, autoFire, loading, toast])
48
+
49
+ const RISK_CLR: Record<string, string> = { critical:'text-trading-down', high:'text-[#ff9500]', medium:'text-brand-yellow', low:'text-trading-up', safe:'text-muted' }
50
+ const RISK_BG: Record<string, string> = { critical:'border-trading-down/30 bg-trading-down/5', high:'border-[#ff9500]/30 bg-[#ff9500]/5', medium:'border-brand-yellow/30 bg-brand-yellow/5', low:'border-trading-up/30 bg-trading-up/5', safe:'border-hairline-dark bg-surface-elevated' }
51
+
52
+ return (
53
+ <div className="rounded-xl bg-surface-card border border-hairline-dark overflow-hidden">
54
+ <div className="px-5 py-4 border-b border-hairline-dark flex items-center gap-2">
55
+ <Radio className="w-4 h-4 text-trading-up" />
56
+ <h3 className="text-title-sm">Live Wallet Analyzer</h3>
57
+ <span className="text-[10px] px-2 py-0.5 rounded-pill bg-trading-up/10 text-trading-up font-semibold border border-trading-up/20">HELIUS</span>
58
+ <p className="text-caption text-muted ml-1">Enter any Solana address — real on-chain churn score</p>
59
+ </div>
60
+ <div className="p-5 space-y-4">
61
+ <div className="flex gap-2">
62
+ <input
63
+ value={addr} onChange={e => setAddr(e.target.value)}
64
+ onKeyDown={e => e.key === 'Enter' && analyze()}
65
+ placeholder="Enter Solana wallet address..."
66
+ className="flex-1 h-10 px-4 rounded-lg bg-surface-elevated border border-hairline-dark text-body-sm text-[#eaecef] placeholder:text-muted focus:outline-none focus:ring-1 focus:ring-brand-yellow/50 font-mono"
67
+ />
68
+ <label className="flex items-center gap-2 px-3 rounded-lg border border-hairline-dark bg-surface-elevated cursor-pointer select-none">
69
+ <input type="checkbox" checked={autoFire} onChange={e => setAutoFire(e.target.checked)} className="accent-brand-yellow" />
70
+ <span className="text-caption text-muted whitespace-nowrap">Auto-fire Torque</span>
71
+ </label>
72
+ <button onClick={analyze} disabled={loading || !addr.trim()}
73
+ className="flex items-center gap-2 px-4 py-2 rounded-lg bg-brand-yellow text-ink text-button font-semibold hover:bg-brand-yellow-active transition disabled:opacity-50">
74
+ {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Zap className="w-4 h-4" />}
75
+ {loading ? 'Scanning...' : 'Analyze'}
76
+ </button>
77
+ </div>
78
+
79
+ {err && <p className="text-body-sm text-trading-down px-1">Error: {err}</p>}
80
+
81
+ {result && (
82
+ <div className={cn('rounded-xl border p-4 space-y-3', RISK_BG[result.risk] || 'border-hairline-dark')}>
83
+ <div className="flex items-center justify-between">
84
+ <div>
85
+ <p className="font-mono text-body-sm text-[#eaecef]">{result.address.slice(0,8)}...{result.address.slice(-6)}</p>
86
+ <a href={`https://solscan.io/account/${result.address}`} target="_blank" rel="noreferrer" className="text-caption text-muted hover:text-brand-yellow transition flex items-center gap-1 mt-0.5">
87
+ <ExternalLink className="w-3 h-3" />View on Solscan
88
+ </a>
89
+ </div>
90
+ <div className="text-right">
91
+ <p className={cn('font-mono text-display-sm font-bold tabular-nums', RISK_CLR[result.risk])}>{result.score}</p>
92
+ <p className={cn('text-caption font-bold uppercase', RISK_CLR[result.risk])}>{result.risk}</p>
93
+ </div>
94
+ </div>
95
+ <div className="grid grid-cols-4 gap-3">
96
+ <div className="rounded-lg bg-surface-elevated p-2.5 text-center">
97
+ <p className="text-[10px] text-muted">Inactive</p>
98
+ <p className="font-mono text-body-sm text-[#eaecef] mt-0.5">{result.signals.lastActiveDaysAgo}</p>
99
+ </div>
100
+ <div className="rounded-lg bg-surface-elevated p-2.5 text-center">
101
+ <p className="text-[10px] text-muted">Streak</p>
102
+ <p className="font-mono text-body-sm text-[#eaecef] mt-0.5">{result.signals.currentStreak}d</p>
103
+ </div>
104
+ <div className="rounded-lg bg-surface-elevated p-2.5 text-center">
105
+ <p className="text-[10px] text-muted">Vol drop</p>
106
+ <p className="font-mono text-body-sm text-[#eaecef] mt-0.5">{result.signals.volumeDropPct}%</p>
107
+ </div>
108
+ <div className="rounded-lg bg-surface-elevated p-2.5 text-center">
109
+ <p className="text-[10px] text-muted">30d txs</p>
110
+ <p className="font-mono text-body-sm text-[#eaecef] mt-0.5">{result.signals.totalTxLast30d}</p>
111
+ </div>
112
+ </div>
113
+ {result.signals.protocols.length > 0 && (
114
+ <div className="flex flex-wrap gap-1">
115
+ {result.signals.protocols.map(p => <span key={p} className="text-[10px] px-1.5 py-0.5 rounded bg-surface-elevated text-muted">{p}</span>)}
116
+ </div>
117
+ )}
118
+ {result.detectedSignals.length > 0 && (
119
+ <div className="space-y-1">
120
+ {result.detectedSignals.map((s, i) => <p key={i} className="text-caption text-muted flex items-center gap-1.5"><span className="text-trading-down">↑</span>{s}</p>)}
121
+ </div>
122
+ )}
123
+ {result.torque.fired && (
124
+ <div className="flex items-center gap-2 p-2.5 rounded-lg bg-trading-up/10 border border-trading-up/30">
125
+ <CheckCircle2 className="w-4 h-4 text-trading-up flex-shrink-0" />
126
+ <div>
127
+ <p className="text-caption text-trading-up font-semibold">{result.torque.eventName} fired via Torque</p>
128
+ <p className="font-mono text-[10px] text-muted">{result.torque.eventId}</p>
129
+ </div>
130
+ </div>
131
+ )}
132
+ </div>
133
+ )}
134
+ </div>
135
+ </div>
136
+ )
137
+ }
138
+
139
  type Filter = ChurnRisk | 'all'
140
  const filters: Filter[] = ['all', 'critical', 'high', 'medium', 'low', 'safe']
141
 
 
301
  </div>
302
  </div>
303
 
304
+ <LiveAnalyzer />
305
+
306
  <div className="grid grid-cols-2 lg:grid-cols-6 gap-3">
307
  {filters.map(r => (
308
  <button key={r} onClick={() => setF(r)} className={cn('rounded-xl border p-3 text-center transition-all', f === r ? 'border-brand-yellow/40 bg-brand-yellow/5' : 'border-hairline-dark bg-surface-card hover:border-brand-yellow/20')}>
src/app/api/helius/analyze/route.ts ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { NextResponse } from 'next/server'
2
+ import { fetchWalletSignals, isHeliusConfigured } from '@/lib/helius'
3
+ import { calculateChurnScore } from '@/lib/agent-engine'
4
+ import { sendCustomEvent, isTorqueConfigured } from '@/lib/torque-mcp'
5
+ import { pushEvent } from '@/lib/event-store'
6
+ import { recordIntervention } from '@/lib/attribution-store'
7
+
8
+ export async function POST(req: Request) {
9
+ const { address, autoFire = false } = await req.json()
10
+
11
+ if (!address || typeof address !== 'string') {
12
+ return NextResponse.json({ error: 'address required' }, { status: 400 })
13
+ }
14
+ if (!isHeliusConfigured()) {
15
+ return NextResponse.json({ error: 'HELIUS_API_KEY not configured' }, { status: 503 })
16
+ }
17
+
18
+ const signals = await fetchWalletSignals(address)
19
+ if (!signals) {
20
+ return NextResponse.json({ error: 'Failed to fetch wallet data from Helius' }, { status: 502 })
21
+ }
22
+
23
+ const { score, risk, signals: detectedSignals } = calculateChurnScore({
24
+ daysInactive: signals.daysInactive,
25
+ volumeDropPct: signals.volumeDropPct,
26
+ uniqueProtocols: signals.uniqueProtocols,
27
+ currentStreak: signals.currentStreak,
28
+ hasLiquidation: signals.hasLiquidation,
29
+ })
30
+
31
+ let torqueResult: { fired: boolean; eventId?: string; eventName?: string } = { fired: false }
32
+
33
+ if (autoFire && isTorqueConfigured() && (risk === 'critical' || risk === 'high' || risk === 'medium')) {
34
+ const eventName = risk === 'critical' || risk === 'high' ? 'churn_risk_high' : 'churn_risk_medium'
35
+ const result = await sendCustomEvent(address, eventName, {
36
+ risk, score,
37
+ daysInactive: signals.daysInactive,
38
+ protocols: signals.protocols,
39
+ source: 'helius_live',
40
+ detectedBy: 'flowstate-helius-scan',
41
+ })
42
+ if (result.success && result.eventId) {
43
+ pushEvent({
44
+ ingestionId: result.eventId,
45
+ wallet: address,
46
+ eventName,
47
+ risk,
48
+ score,
49
+ firedAt: new Date().toISOString(),
50
+ source: 'scan',
51
+ })
52
+ recordIntervention(address, eventName, score)
53
+ torqueResult = { fired: true, eventId: result.eventId, eventName }
54
+ }
55
+ }
56
+
57
+ return NextResponse.json({
58
+ address,
59
+ signals,
60
+ score,
61
+ risk,
62
+ detectedSignals,
63
+ torque: torqueResult,
64
+ })
65
+ }
src/lib/helius.ts ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Helius RPC client — fetches real Solana wallet activity for churn scoring.
3
+ * Uses the enhanced transactions API to derive wallet signals without an indexer.
4
+ */
5
+
6
+ const HELIUS_BASE = 'https://api.helius.xyz/v0'
7
+ const KEY = process.env.HELIUS_API_KEY || ''
8
+
9
+ export function isHeliusConfigured() {
10
+ return KEY !== '' && !KEY.startsWith('your')
11
+ }
12
+
13
+ // Helius source → display protocol name
14
+ const SOURCE_MAP: Record<string, string> = {
15
+ JUPITER: 'Jupiter',
16
+ RAYDIUM: 'Raydium',
17
+ DRIFT: 'Drift',
18
+ KAMINO: 'Kamino',
19
+ KAMINO_FINANCE: 'Kamino',
20
+ MARGINFI: 'Marginfi',
21
+ TENSOR: 'Tensor',
22
+ ORCA: 'Orca',
23
+ METEORA: 'Meteora',
24
+ PHOENIX: 'Phoenix',
25
+ LIFINITY: 'Lifinity',
26
+ MARINADE: 'Marinade',
27
+ }
28
+
29
+ interface HeliusTx {
30
+ timestamp: number
31
+ source: string
32
+ type: string
33
+ nativeTransfers?: Array<{ amount: number }>
34
+ tokenTransfers?: Array<{ tokenAmount: number }>
35
+ }
36
+
37
+ export interface WalletSignals {
38
+ address: string
39
+ daysInactive: number
40
+ protocols: string[]
41
+ uniqueProtocols: number
42
+ currentStreak: number
43
+ volumeDropPct: number
44
+ hasLiquidation: boolean
45
+ totalTxLast30d: number
46
+ lastActiveDaysAgo: string
47
+ source: 'helius' | 'mock'
48
+ }
49
+
50
+ export async function fetchWalletSignals(address: string): Promise<WalletSignals | null> {
51
+ if (!isHeliusConfigured()) return null
52
+ try {
53
+ const res = await fetch(
54
+ `${HELIUS_BASE}/addresses/${address}/transactions?api-key=${KEY}&limit=50`,
55
+ { next: { revalidate: 60 } }
56
+ )
57
+ if (!res.ok) return null
58
+ const txs: HeliusTx[] = await res.json()
59
+ if (!txs.length) return null
60
+
61
+ const nowSec = Date.now() / 1000
62
+ const sorted = txs.sort((a, b) => b.timestamp - a.timestamp)
63
+
64
+ // Days since last tx
65
+ const daysInactive = Math.round((nowSec - sorted[0].timestamp) / 86400)
66
+
67
+ // Protocols used
68
+ const protocolSet = new Set<string>()
69
+ for (const tx of sorted) {
70
+ const mapped = SOURCE_MAP[tx.source]
71
+ if (mapped) protocolSet.add(mapped)
72
+ }
73
+ const protocols = Array.from(protocolSet)
74
+
75
+ // Streak: count distinct calendar days active in last 7d
76
+ const sevenDaysAgo = nowSec - 7 * 86400
77
+ const activeDays = new Set(
78
+ sorted
79
+ .filter(tx => tx.timestamp >= sevenDaysAgo)
80
+ .map(tx => new Date(tx.timestamp * 1000).toDateString())
81
+ )
82
+ const currentStreak = activeDays.size
83
+
84
+ // Volume drop: tx count in last 7d vs prior 7d (proxy for volume)
85
+ const fourteenDaysAgo = nowSec - 14 * 86400
86
+ const recentCount = sorted.filter(tx => tx.timestamp >= sevenDaysAgo).length
87
+ const priorCount = sorted.filter(tx => tx.timestamp >= fourteenDaysAgo && tx.timestamp < sevenDaysAgo).length
88
+ const volumeDropPct = priorCount > 0
89
+ ? Math.round(Math.max(0, (priorCount - recentCount) / priorCount * 100))
90
+ : 0
91
+
92
+ // Liquidation check
93
+ const hasLiquidation = sorted.some(tx => tx.type?.includes('LIQUIDAT'))
94
+
95
+ // tx count last 30d
96
+ const thirtyDaysAgo = nowSec - 30 * 86400
97
+ const totalTxLast30d = sorted.filter(tx => tx.timestamp >= thirtyDaysAgo).length
98
+
99
+ const lastActiveDaysAgo = daysInactive === 0 ? 'today'
100
+ : daysInactive === 1 ? '1d ago'
101
+ : `${daysInactive}d ago`
102
+
103
+ return {
104
+ address,
105
+ daysInactive,
106
+ protocols,
107
+ uniqueProtocols: protocols.length,
108
+ currentStreak,
109
+ volumeDropPct,
110
+ hasLiquidation,
111
+ totalTxLast30d,
112
+ lastActiveDaysAgo,
113
+ source: 'helius',
114
+ }
115
+ } catch {
116
+ return null
117
+ }
118
+ }
tsconfig.tsbuildinfo CHANGED
The diff for this file is too large to render. See raw diff